-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathtest_cli.py
More file actions
429 lines (352 loc) Β· 17.4 KB
/
test_cli.py
File metadata and controls
429 lines (352 loc) Β· 17.4 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""Integration tests for the CLI module."""
import json
from io import StringIO
from unittest.mock import MagicMock, patch
import pytest
from toon_format.cli import decode_toon_to_json, encode_json_to_toon, main
class TestEncodeJsonToToon:
"""Tests for encode_json_to_toon function."""
def test_basic_encode(self):
"""Test basic JSON to TOON encoding."""
json_text = '{"name": "Alice", "age": 30}'
result = encode_json_to_toon(json_text)
assert "name: Alice" in result
assert "age: 30" in result
def test_encode_with_custom_delimiter(self):
"""Test encoding with custom delimiter."""
json_text = '{"items": [1, 2, 3]}'
result = encode_json_to_toon(json_text, delimiter="|")
assert "|" in result or "[3]:" in result # Either delimiter or inline format
def test_encode_with_custom_indent(self):
"""Test encoding with custom indentation."""
json_text = '{"outer": {"inner": 1}}'
result = encode_json_to_toon(json_text, indent=4)
# With 4-space indent, nested items should have 4 spaces
assert result is not None
def test_encode_with_length_marker(self):
"""Test encoding with length marker."""
json_text = '{"items": [1, 2, 3]}'
result = encode_json_to_toon(json_text, length_marker=True)
assert "#" in result or "items" in result
def test_encode_invalid_json_raises_error(self):
"""Test that invalid JSON raises JSONDecodeError."""
invalid_json = '{"broken": invalid}'
with pytest.raises(json.JSONDecodeError):
encode_json_to_toon(invalid_json)
class TestDecodeToonToJson:
"""Tests for decode_toon_to_json function."""
def test_basic_decode(self):
"""Test basic TOON to JSON decoding."""
toon_text = "name: Alice\nage: 30"
result = decode_toon_to_json(toon_text)
data = json.loads(result)
assert data["name"] == "Alice"
assert data["age"] == 30
def test_decode_with_custom_indent(self):
"""Test decoding with custom indentation."""
toon_text = "outer:\n inner: 1"
result = decode_toon_to_json(toon_text, indent=4)
data = json.loads(result)
assert data["outer"]["inner"] == 1
def test_decode_strict_mode(self):
"""Test decoding in strict mode."""
toon_text = "name: Alice\nage: 30"
result = decode_toon_to_json(toon_text, strict=True)
data = json.loads(result)
assert data["name"] == "Alice"
def test_decode_lenient_mode(self):
"""Test decoding in lenient mode."""
toon_text = "name: Alice\nage: 30"
result = decode_toon_to_json(toon_text, strict=False)
data = json.loads(result)
assert data["name"] == "Alice"
class TestStatsFlag:
"""Tests for the --stats CLI flag."""
def test_stats_flag_in_help(self, tmp_path):
"""Test that --stats appears in help text."""
with patch("sys.argv", ["toon", "--help"]):
with pytest.raises(SystemExit):
main()
def test_stats_with_file_input(self, tmp_path):
"""Test --stats with file input."""
input_file = tmp_path / "test.json"
input_file.write_text('{"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}')
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file), "--stats"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "users[2" in output
assert "Format Comparison" in output or "Savings" in output
def test_stats_with_stdin(self):
"""Test --stats with stdin input."""
input_data = '{"items": ["a", "b", "c"]}'
with patch("sys.stdin", StringIO(input_data)):
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", "-", "--stats"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "items[3" in output
def test_stats_ignored_in_decode_mode(self, tmp_path):
"""Test that --stats is ignored when decoding."""
input_file = tmp_path / "test.toon"
input_file.write_text("items[2]: a,b")
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.stderr", new_callable=StringIO) as mock_stderr:
with patch("sys.argv", ["toon", str(input_file), "--decode", "--stats"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert '"items"' in output
if mock_stderr.getvalue():
assert "warning" in mock_stderr.getvalue().lower()
def test_stats_with_different_delimiters(self, tmp_path):
"""Test that --stats works with alternative delimiters."""
input_file = tmp_path / "test.json"
input_file.write_text('{"data": [{"a": 1, "b": 2}]}')
# Test with tab delimiter
with patch("sys.stdout", new_callable=StringIO):
with patch("sys.argv", ["toon", str(input_file), "--delimiter", "\t", "--stats"]):
result = main()
assert result == 0
# Test with pipe delimiter
with patch("sys.stdout", new_callable=StringIO):
with patch("sys.argv", ["toon", str(input_file), "--delimiter", "|", "--stats"]):
result = main()
assert result == 0
def test_stats_without_tiktoken(self, tmp_path, monkeypatch):
"""Test graceful handling when tiktoken is not available."""
input_file = tmp_path / "test.json"
input_file.write_text('{"test": 123}')
# Mock compare_formats to raise RuntimeError (simulating missing tiktoken)
def mock_compare_formats(data):
raise RuntimeError("tiktoken is required")
with patch("toon_format.cli.compare_formats", side_effect=mock_compare_formats):
with patch("sys.stdout", new_callable=StringIO):
with patch("sys.stderr", new_callable=StringIO) as mock_stderr:
with patch("sys.argv", ["toon", str(input_file), "--stats"]):
result = main()
assert result == 0
assert "tiktoken" in mock_stderr.getvalue()
def test_stats_with_output_file(self, tmp_path):
"""Test --stats with -o output option."""
input_file = tmp_path / "test.json"
input_file.write_text('{"test": 123}')
output_file = tmp_path / "output.toon"
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file), "-o", str(output_file), "--stats"]):
result = main()
assert result == 0
assert output_file.exists()
assert (
"Format Comparison" in mock_stdout.getvalue()
or "Savings" in mock_stdout.getvalue()
)
class TestCLIMain:
"""Integration tests for the main CLI function."""
def test_encode_from_file_to_stdout(self, tmp_path):
"""Test encoding from file to stdout."""
# Create input file
input_file = tmp_path / "input.json"
input_file.write_text('{"name": "Alice"}')
# Mock stdout
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file), "--encode"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "name: Alice" in output
def test_decode_from_file_to_stdout(self, tmp_path):
"""Test decoding from file to stdout."""
# Create input file
input_file = tmp_path / "input.toon"
input_file.write_text("name: Alice\nage: 30")
# Mock stdout
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file), "--decode"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "Alice" in output
def test_encode_from_stdin_to_stdout(self):
"""Test encoding from stdin to stdout."""
input_data = '{"name": "Bob"}'
with patch("sys.stdin", StringIO(input_data)):
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", "-", "--encode"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "name: Bob" in output
def test_decode_from_stdin_to_stdout(self):
"""Test decoding from stdin to stdout."""
input_data = "name: Charlie\nage: 25"
with patch("sys.stdin", StringIO(input_data)):
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", "-", "--decode"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "Charlie" in output
def test_encode_to_output_file(self, tmp_path):
"""Test encoding with output file."""
input_file = tmp_path / "input.json"
output_file = tmp_path / "output.toon"
input_file.write_text('{"name": "Dave"}')
with patch("sys.argv", ["toon", str(input_file), "-o", str(output_file), "--encode"]):
result = main()
assert result == 0
assert output_file.exists()
content = output_file.read_text()
assert "name: Dave" in content
def test_decode_to_output_file(self, tmp_path):
"""Test decoding with output file."""
input_file = tmp_path / "input.toon"
output_file = tmp_path / "output.json"
input_file.write_text("name: Eve\nage: 35")
with patch("sys.argv", ["toon", str(input_file), "-o", str(output_file), "--decode"]):
result = main()
assert result == 0
assert output_file.exists()
content = output_file.read_text()
data = json.loads(content)
assert data["name"] == "Eve"
def test_auto_detect_json_extension(self, tmp_path):
"""Test auto-detection based on .json extension."""
input_file = tmp_path / "data.json"
input_file.write_text('{"test": true}')
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file)]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "test: true" in output
def test_auto_detect_toon_extension(self, tmp_path):
"""Test auto-detection based on .toon extension."""
input_file = tmp_path / "data.toon"
input_file.write_text("test: true")
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file)]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "true" in output
def test_auto_detect_json_content(self, tmp_path):
"""Test auto-detection based on JSON content."""
input_file = tmp_path / "data.txt"
input_file.write_text('{"format": "json"}')
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file)]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "format: json" in output
def test_auto_detect_toon_content(self, tmp_path):
"""Test auto-detection based on TOON content."""
input_file = tmp_path / "data.txt"
input_file.write_text("format: toon")
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", str(input_file)]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "toon" in output
def test_auto_detect_stdin_json(self):
"""Test auto-detection from stdin with JSON content."""
input_data = '{"source": "stdin"}'
with patch("sys.stdin", StringIO(input_data)):
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", "-"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "source: stdin" in output
def test_auto_detect_stdin_toon(self):
"""Test auto-detection from stdin with TOON content."""
input_data = "source: stdin"
with patch("sys.stdin", StringIO(input_data)):
with patch("sys.stdout", new_callable=StringIO) as mock_stdout:
with patch("sys.argv", ["toon", "-"]):
result = main()
assert result == 0
output = mock_stdout.getvalue()
assert "stdin" in output
def test_custom_delimiter_option(self, tmp_path):
"""Test custom delimiter option."""
input_file = tmp_path / "input.json"
input_file.write_text('{"items": [1, 2, 3]}')
with patch("sys.stdout", new_callable=StringIO):
with patch("sys.argv", ["toon", str(input_file), "--encode", "--delimiter", "|"]):
result = main()
assert result == 0
def test_custom_indent_option(self, tmp_path):
"""Test custom indent option."""
input_file = tmp_path / "input.json"
input_file.write_text('{"outer": {"inner": 1}}')
with patch("sys.stdout", new_callable=StringIO):
with patch("sys.argv", ["toon", str(input_file), "--encode", "--indent", "4"]):
result = main()
assert result == 0
def test_length_marker_option(self, tmp_path):
"""Test length marker option."""
input_file = tmp_path / "input.json"
input_file.write_text('{"items": [1, 2, 3]}')
with patch("sys.stdout", new_callable=StringIO):
with patch("sys.argv", ["toon", str(input_file), "--encode", "--length-marker"]):
result = main()
assert result == 0
def test_no_strict_option(self, tmp_path):
"""Test no-strict option."""
input_file = tmp_path / "input.toon"
input_file.write_text("name: Test")
with patch("sys.stdout", new_callable=StringIO):
with patch("sys.argv", ["toon", str(input_file), "--decode", "--no-strict"]):
result = main()
assert result == 0
def test_error_file_not_found(self):
"""Test error when input file doesn't exist."""
with patch("sys.stderr", new_callable=StringIO) as mock_stderr:
with patch("sys.argv", ["toon", "nonexistent.json"]):
result = main()
assert result == 1
assert "not found" in mock_stderr.getvalue()
def test_error_both_encode_and_decode(self, tmp_path):
"""Test error when both --encode and --decode are specified."""
input_file = tmp_path / "input.txt"
input_file.write_text("test")
with patch("sys.stderr", new_callable=StringIO) as mock_stderr:
with patch("sys.argv", ["toon", str(input_file), "--encode", "--decode"]):
result = main()
assert result == 1
assert "Cannot specify both" in mock_stderr.getvalue()
def test_error_during_encoding(self, tmp_path):
"""Test error handling during encoding."""
input_file = tmp_path / "input.json"
input_file.write_text('{"invalid": broken}')
with patch("sys.stderr", new_callable=StringIO) as mock_stderr:
with patch("sys.argv", ["toon", str(input_file), "--encode"]):
result = main()
assert result == 1
assert "Error during encode" in mock_stderr.getvalue()
def test_error_reading_input(self):
"""Test error when reading input fails."""
mock_stdin = MagicMock()
mock_stdin.read.side_effect = OSError("Read failed")
with patch("sys.stdin", mock_stdin):
with patch("sys.stderr", new_callable=StringIO) as mock_stderr:
with patch("sys.argv", ["toon", "-", "--encode"]):
result = main()
assert result == 1
assert "Error reading input" in mock_stderr.getvalue()
def test_error_writing_output(self, tmp_path):
"""Test error when writing output fails."""
input_file = tmp_path / "input.json"
input_file.write_text('{"test": true}')
# Create a read-only directory to cause write failure
output_file = tmp_path / "readonly" / "output.toon"
with patch("sys.stderr", new_callable=StringIO) as mock_stderr:
with patch("sys.argv", ["toon", str(input_file), "-o", str(output_file), "--encode"]):
result = main()
assert result == 1
assert "Error writing output" in mock_stderr.getvalue()