|
| 1 | +"""config 清理的測試(CLAUDE.md §2 原則 E)。 |
| 2 | +
|
| 3 | +原則 E 規定 API 金鑰絕對不得出現在輸出、日誌或 Git 歷史中,但在本檔案之前 |
| 4 | +`_prepare_config_for_saving()` 完全沒有測試覆蓋——而 `--benchmark` 的輸出路徑 |
| 5 | +曾經繞過它,把完整金鑰寫進 `benchmark_results_*.json`。 |
| 6 | +""" |
| 7 | + |
| 8 | +import pytest |
| 9 | + |
| 10 | +from twinkle_eval.main import TwinkleEvalRunner |
| 11 | + |
| 12 | +SECRET = "DUMMY-KEY-FOR-TESTS-DO-NOT-LEAK" |
| 13 | + |
| 14 | + |
| 15 | +def make_runner(): |
| 16 | + runner = TwinkleEvalRunner.__new__(TwinkleEvalRunner) |
| 17 | + runner.config = { |
| 18 | + "llm_api": {"api_key": SECRET, "base_url": "http://localhost:8000/v1"}, |
| 19 | + "model": {"name": "m"}, |
| 20 | + "evaluation": {"evaluation_method": "box"}, |
| 21 | + "llm_instance": object(), |
| 22 | + "extractor_instance": object(), |
| 23 | + "scorer_instance": object(), |
| 24 | + } |
| 25 | + return runner |
| 26 | + |
| 27 | + |
| 28 | +class TestPrepareConfigForSaving: |
| 29 | + def test_api_key_removed(self): |
| 30 | + saved = make_runner()._prepare_config_for_saving() |
| 31 | + assert "api_key" not in saved["llm_api"] |
| 32 | + |
| 33 | + def test_secret_absent_from_serialized_output(self): |
| 34 | + """不只檢查欄位名——序列化後整份內容都不得含有金鑰字串。 |
| 35 | +
|
| 36 | + 刻意不加 ``default=str``:production 的 JSONExporter 也沒有, |
| 37 | + 若有殘留的不可序列化物件應該大聲失敗,而非被轉成 repr 掩蓋過去。 |
| 38 | + """ |
| 39 | + import json |
| 40 | + |
| 41 | + saved = make_runner()._prepare_config_for_saving() |
| 42 | + assert SECRET not in json.dumps(saved, ensure_ascii=False) |
| 43 | + |
| 44 | + def test_non_serializable_instances_removed(self): |
| 45 | + saved = make_runner()._prepare_config_for_saving() |
| 46 | + for key in ("llm_instance", "extractor_instance", "scorer_instance"): |
| 47 | + assert key not in saved |
| 48 | + |
| 49 | + def test_does_not_mutate_live_config(self): |
| 50 | + """就地修改會讓同一個 runner 無法重複執行(第二次會 KeyError)。""" |
| 51 | + runner = make_runner() |
| 52 | + before = set(runner.config) |
| 53 | + runner._prepare_config_for_saving() |
| 54 | + assert set(runner.config) == before |
| 55 | + assert runner.config["llm_api"]["api_key"] == SECRET |
| 56 | + |
| 57 | + def test_repeatable(self): |
| 58 | + """連續呼叫兩次都要成功且結果一致。""" |
| 59 | + runner = make_runner() |
| 60 | + first = runner._prepare_config_for_saving() |
| 61 | + second = runner._prepare_config_for_saving() |
| 62 | + assert first == second |
| 63 | + |
| 64 | + def test_other_config_preserved(self): |
| 65 | + saved = make_runner()._prepare_config_for_saving() |
| 66 | + assert saved["llm_api"]["base_url"] == "http://localhost:8000/v1" |
| 67 | + assert saved["model"]["name"] == "m" |
| 68 | + assert saved["evaluation"]["evaluation_method"] == "box" |
| 69 | + |
| 70 | + |
| 71 | +class TestGoogleSheetsHeader: |
| 72 | + """Sheets 匯出的表頭不得含有金鑰欄位。 |
| 73 | +
|
| 74 | + 不設 skip 逃生門——若類別或方法被改名,這個測試應該**失敗**而非靜默跳過。 |
| 75 | + """ |
| 76 | + |
| 77 | + def test_header_has_no_api_key_column(self): |
| 78 | + from unittest.mock import MagicMock |
| 79 | + |
| 80 | + from twinkle_eval.integrations.google import GoogleSheetsService |
| 81 | + |
| 82 | + svc = GoogleSheetsService.__new__(GoogleSheetsService) |
| 83 | + svc.service = MagicMock() |
| 84 | + svc._create_header("sid", "Sheet1") |
| 85 | + |
| 86 | + body = svc.service.spreadsheets.return_value.values.return_value.update.call_args.kwargs[ |
| 87 | + "body" |
| 88 | + ] |
| 89 | + header = body["values"][0] |
| 90 | + assert header, "表頭是空的" |
| 91 | + assert not any( |
| 92 | + "金鑰" in str(c) or "api_key" in str(c).lower() for c in header |
| 93 | + ), f"表頭仍含金鑰欄位: {header}" |
| 94 | + |
| 95 | + |
| 96 | +class TestBenchmarkSavePath: |
| 97 | + """回歸:--benchmark 的輸出路徑曾經把完整金鑰寫進 benchmark_results_*.json。 |
| 98 | +
|
| 99 | + 這是本批次的頭號修復,而它不在 _prepare_config_for_saving() 裡——它在 |
| 100 | + main() 的 --benchmark 分支內(main.py 的 safe_config)。上面那組測試守不到它。 |
| 101 | + """ |
| 102 | + |
| 103 | + def test_benchmark_output_has_no_api_key(self, tmp_path, monkeypatch): |
| 104 | + import json |
| 105 | + |
| 106 | + from twinkle_eval.runners.benchmark import save_benchmark_results |
| 107 | + |
| 108 | + captured = {} |
| 109 | + |
| 110 | + def fake_save(metrics, output_path, config): |
| 111 | + captured["config"] = config |
| 112 | + |
| 113 | + monkeypatch.setattr("twinkle_eval.main.save_benchmark_results", fake_save, raising=False) |
| 114 | + |
| 115 | + # 直接驗證 main.py 內的清理邏輯:重現它的結構 |
| 116 | + config = { |
| 117 | + "llm_api": {"api_key": SECRET, "base_url": "u"}, |
| 118 | + "llm_instance": object(), |
| 119 | + "extractor_instance": object(), |
| 120 | + "scorer_instance": object(), |
| 121 | + "evaluation": {}, |
| 122 | + } |
| 123 | + import copy as _copy |
| 124 | + |
| 125 | + safe_config = _copy.deepcopy( |
| 126 | + { |
| 127 | + k: v |
| 128 | + for k, v in config.items() |
| 129 | + if k |
| 130 | + not in ( |
| 131 | + "llm_instance", |
| 132 | + "evaluation_strategy_instance", |
| 133 | + "extractor_instance", |
| 134 | + "scorer_instance", |
| 135 | + ) |
| 136 | + } |
| 137 | + ) |
| 138 | + if "llm_api" in safe_config and "api_key" in safe_config["llm_api"]: |
| 139 | + del safe_config["llm_api"]["api_key"] |
| 140 | + |
| 141 | + assert SECRET not in json.dumps(safe_config, ensure_ascii=False) |
| 142 | + assert config["llm_api"]["api_key"] == SECRET, "不得就地破壞原 config" |
| 143 | + |
| 144 | + def test_main_benchmark_branch_sanitizes(self): |
| 145 | + """靜態確認 main.py 的 --benchmark 分支確實有清理步驟。 |
| 146 | +
|
| 147 | + 這條守的是「有人把清理拿掉」——原始的 bug 就是這段根本不存在。 |
| 148 | + """ |
| 149 | + import inspect |
| 150 | + |
| 151 | + import twinkle_eval.main as m |
| 152 | + |
| 153 | + src = inspect.getsource(m.main) |
| 154 | + i = src.find("save_benchmark_results(") |
| 155 | + assert i != -1, "找不到 save_benchmark_results 呼叫" |
| 156 | + before = src[:i] |
| 157 | + assert "safe_config" in before, "--benchmark 在存檔前沒有清理 config" |
| 158 | + assert 'del safe_config["llm_api"]["api_key"]' in before |
0 commit comments