|
1 | 1 | """Tests for config command and utility functions.""" |
2 | 2 |
|
3 | 3 | import json |
| 4 | +import os |
4 | 5 | from typer.testing import CliRunner |
5 | 6 | from transformerlab_cli.main import app |
6 | 7 | from transformerlab_cli.util.config import ( |
@@ -137,6 +138,54 @@ def test_load_config_with_data(tmp_config_dir): |
137 | 138 | assert config["server"] == "http://test:8338" |
138 | 139 |
|
139 | 140 |
|
| 141 | +def test_load_config_corrupt_moves_aside_and_returns_empty(tmp_config_dir): |
| 142 | + """A corrupt config must not silently resolve to {}; it must be renamed aside.""" |
| 143 | + import glob |
| 144 | + |
| 145 | + config_dir, config_file = tmp_config_dir |
| 146 | + with open(config_file, "w", encoding="utf-8") as f: |
| 147 | + f.write("{not: valid json,,") |
| 148 | + with _patch_config_paths(config_dir, config_file): |
| 149 | + config = load_config() |
| 150 | + assert config == {} |
| 151 | + assert not os.path.exists(config_file), "corrupt config should have been renamed aside" |
| 152 | + backups = glob.glob(f"{config_file}.corrupt-*") |
| 153 | + assert len(backups) == 1, f"expected one backup, got {backups}" |
| 154 | + |
| 155 | + |
| 156 | +def test_set_config_does_not_wipe_existing_keys_when_file_is_fine(tmp_config_dir): |
| 157 | + """Regression: a set_config call must merge, never wipe unrelated keys.""" |
| 158 | + config_dir, config_file = tmp_config_dir |
| 159 | + with open(config_file, "w", encoding="utf-8") as f: |
| 160 | + f.write( |
| 161 | + json.dumps( |
| 162 | + { |
| 163 | + "server": "http://localhost:8338", |
| 164 | + "team_id": "abc-123", |
| 165 | + "user_email": "u@example.com", |
| 166 | + "current_experiment": "alpha", |
| 167 | + } |
| 168 | + ) |
| 169 | + ) |
| 170 | + with _patch_config_paths(config_dir, config_file): |
| 171 | + assert set_config("current_experiment", "beta") is True |
| 172 | + with open(config_file, "r", encoding="utf-8") as f: |
| 173 | + data = json.loads(f.read()) |
| 174 | + assert data["server"] == "http://localhost:8338" |
| 175 | + assert data["team_id"] == "abc-123" |
| 176 | + assert data["user_email"] == "u@example.com" |
| 177 | + assert data["current_experiment"] == "beta" |
| 178 | + |
| 179 | + |
| 180 | +def test_save_config_is_atomic_no_tmp_left_behind(tmp_config_dir): |
| 181 | + """After a successful save, the sibling .tmp file must not exist.""" |
| 182 | + config_dir, config_file = tmp_config_dir |
| 183 | + with _patch_config_paths(config_dir, config_file): |
| 184 | + assert set_config("server", "http://localhost:8338") is True |
| 185 | + assert os.path.exists(config_file) |
| 186 | + assert not os.path.exists(f"{config_file}.tmp") |
| 187 | + |
| 188 | + |
140 | 189 | # --- JSON format output --- |
141 | 190 |
|
142 | 191 |
|
|
0 commit comments