-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_cli_export_exit_codes.py
More file actions
261 lines (214 loc) · 8.13 KB
/
Copy pathtest_cli_export_exit_codes.py
File metadata and controls
261 lines (214 loc) · 8.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""CLI export exit codes for bulk export (partial / total failure)."""
from __future__ import annotations
import re
import types
from pathlib import Path
import pytest
import scripts.export as export
from models.error_codes import ErrorCode
from tests.test_cli_e2e import _run_cli, _seed_base_dir
from utils.export_engine import (
BulkExportResult,
ExportFailure,
bulk_export_exit_code,
dominant_failure_code,
)
from utils.jsonl_parser import parse_session
_SUMMARY_RE = re.compile(
r"Exported \d+ of \d+ sessions \(\d+ failed\)",
)
def _isolated_home_env(tmp_path: Path) -> dict[str, str]:
"""Redirect ~/.claude-code-chat-browser export state for subprocess CLI runs."""
home = str(tmp_path / "home")
return {"HOME": home, "USERPROFILE": home}
def _export_args(tmp_path: Path, base: Path, out_dir: Path) -> types.SimpleNamespace:
return types.SimpleNamespace(
base_dir=str(base),
out=str(out_dir),
since="all",
no_zip=True,
project=None,
format="md",
session=None,
exclude_rules=None,
)
def test_cli_export_clean_exits_zero(tmp_path):
base = _seed_base_dir(tmp_path)
out_dir = tmp_path / "out"
proc = _run_cli(
[
"export",
"--base-dir",
str(base),
"--since",
"all",
"--no-zip",
"--out",
str(out_dir),
]
)
assert proc.returncode == 0, proc.stderr
assert list(out_dir.rglob("*.md"))
# Success summary must go to stdout, not stderr
assert "Exported" not in proc.stderr
assert "Exported 1 of 1 sessions (0 failed)" in proc.stdout
def test_cli_export_partial_failure_exits_two(tmp_path, monkeypatch, capsys):
"""One session exports; a second fails parse (simulated corrupt file)."""
base = _seed_base_dir(tmp_path)
project_dir = base / "test-project"
bad = project_dir / "session_bad.jsonl"
bad.write_text('{"type": "user"}\n', encoding="utf-8")
out_dir = tmp_path / "out"
state_dir = tmp_path / "state"
state_dir.mkdir()
monkeypatch.setattr(export, "STATE_FILE", str(state_dir / "export_state.json"))
monkeypatch.setattr(export, "STATE_DIR", str(state_dir))
real_parse = parse_session
def _parse(path: str):
if bad.name in path.replace("\\", "/"):
raise ValueError("simulated corrupt jsonl")
return real_parse(path)
monkeypatch.setattr("utils.export_engine.parse_session", _parse)
with pytest.raises(SystemExit) as exc_info:
export.cmd_export(_export_args(tmp_path, base, out_dir))
assert exc_info.value.code == 2
captured = capsys.readouterr()
assert _SUMMARY_RE.search(captured.err), captured.err
assert "Exported 1 of 2 sessions (1 failed)" in captured.err
assert "PARSE_ERROR" in captured.err
assert "simulated corrupt jsonl" not in captured.err
assert len(list(out_dir.rglob("*.md"))) == 1
def test_since_last_early_return_invokes_exit_bulk_export(tmp_path, monkeypatch, capsys):
"""cmd_export --since last must call _exit_bulk_export on early-return paths."""
exit_calls: list[BulkExportResult] = []
def _track_exit(result: BulkExportResult) -> None:
exit_calls.append(result)
fake_result = BulkExportResult(latest_day=None)
monkeypatch.setattr(export, "_exit_bulk_export", _track_exit)
monkeypatch.setattr(
export,
"run_bulk_export",
lambda **kwargs: fake_result,
)
monkeypatch.setattr(export, "list_projects", lambda base: [{"name": "p", "path": "/p"}])
args = types.SimpleNamespace(
base_dir=str(tmp_path),
out=str(tmp_path / "out"),
since="last",
no_zip=True,
project=None,
format="md",
session=None,
exclude_rules=None,
)
export.cmd_export(args)
assert len(exit_calls) == 1
assert exit_calls[0] is fake_result
captured = capsys.readouterr()
assert "no qualifying sessions" in captured.out.lower()
assert "Exported" not in captured.err
def test_since_last_early_return_exits_one_on_failure(tmp_path, monkeypatch, capsys):
"""Since-last early-return with failures must produce real exit code 1."""
fake_result = BulkExportResult(
latest_day=None,
failures=[
ExportFailure(
session_id="session_fail",
message="Failed to parse session",
code=ErrorCode.PARSE_ERROR,
)
],
)
monkeypatch.setattr(export, "run_bulk_export", lambda **kwargs: fake_result)
monkeypatch.setattr(export, "list_projects", lambda base: [{"name": "p", "path": "/p"}])
args = types.SimpleNamespace(
base_dir=str(tmp_path),
out=str(tmp_path / "out"),
since="last",
no_zip=True,
project=None,
format="md",
session=None,
exclude_rules=None,
)
with pytest.raises(SystemExit) as exc_info:
export.cmd_export(args)
assert exc_info.value.code == 1
captured = capsys.readouterr()
assert "Exported 0 of 1 sessions (1 failed)" in captured.err
assert "PARSE_ERROR" in captured.err
def test_cli_export_incremental_noop_no_stderr_summary(tmp_path):
"""Second incremental run after state is saved: exit 0, no stderr summary."""
base = _seed_base_dir(tmp_path)
out_dir = tmp_path / "out"
home_env = _isolated_home_env(tmp_path)
argv = [
"export",
"--base-dir",
str(base),
"--no-zip",
"--out",
str(out_dir),
]
first = _run_cli([*argv, "--since", "all"], env=home_env)
assert first.returncode == 0, first.stderr
assert list(out_dir.rglob("*.md"))
second = _run_cli([*argv, "--since", "incremental"], env=home_env)
assert second.returncode == 0, second.stderr
assert "Exported" not in second.stderr
assert "Nothing to export" in second.stdout
def test_cli_export_total_failure_exits_one(tmp_path, monkeypatch, capsys):
project_dir = tmp_path / "test-project"
project_dir.mkdir(parents=True)
(project_dir / "bad_a.jsonl").write_text("{}", encoding="utf-8")
(project_dir / "bad_b.jsonl").write_text("{}", encoding="utf-8")
out_dir = tmp_path / "out"
state_dir = tmp_path / "state"
state_dir.mkdir()
monkeypatch.setattr(export, "STATE_FILE", str(state_dir / "export_state.json"))
monkeypatch.setattr(export, "STATE_DIR", str(state_dir))
def _parse(_path: str):
raise ValueError("simulated corrupt jsonl")
monkeypatch.setattr("utils.export_engine.parse_session", _parse)
with pytest.raises(SystemExit) as exc_info:
export.cmd_export(_export_args(tmp_path, tmp_path, out_dir))
assert exc_info.value.code == 1
captured = capsys.readouterr()
assert "Exported 0 of 2 sessions (2 failed)" in captured.err
assert "PARSE_ERROR" in captured.err
assert "simulated corrupt jsonl" not in captured.err
assert "Nothing to export." in captured.out
assert list(out_dir.rglob("*.md")) == []
@pytest.mark.parametrize(
"result,expected_exit",
[
(BulkExportResult(), 0),
(
BulkExportResult(
exported_session_count=2,
failures=[
ExportFailure("a", "Failed to parse session", ErrorCode.PARSE_ERROR),
],
),
2,
),
(
BulkExportResult(
failures=[
ExportFailure("a", "Failed to parse session", ErrorCode.PARSE_ERROR),
ExportFailure("b", "Failed to export session", ErrorCode.INTERNAL_ERROR),
],
),
1,
),
],
)
def test_bulk_export_exit_code_mapping(result: BulkExportResult, expected_exit: int) -> None:
assert bulk_export_exit_code(result) == expected_exit
def test_dominant_failure_code_picks_most_common() -> None:
failures = [
ExportFailure("a", "Failed to parse session", ErrorCode.PARSE_ERROR),
ExportFailure("b", "Failed to parse session", ErrorCode.PARSE_ERROR),
ExportFailure("c", "Failed to export session", ErrorCode.INTERNAL_ERROR),
]
assert dominant_failure_code(failures) == ErrorCode.PARSE_ERROR