Debian Codegraph @

test/test_json_utils.py

raw symbols SCIP
1 from __future__ import annotations
2 import json
3 from pathlib import Path
4 import pytest
5 from con_duct._constants import SUFFIXES
6 from con_duct.json_utils import (
7 JSONL_SUFFIXES,
8 is_info_file,
9 is_jsonl_file,
10 load_info_file,
11 load_usage_file,
12 )
13
14
15 class TestIsJsonlFile:
16 def test_usage_jsonl(self) -> None:
17 assert is_jsonl_file(f"prefix_{SUFFIXES['usage']}")
18
19 def test_usage_legacy(self) -> None:
20 assert is_jsonl_file(f"prefix_{SUFFIXES['usage_legacy']}")
21
22 def test_generic_jsonl(self) -> None:
23 assert is_jsonl_file("anything.jsonl")
24
25 def test_info_json_is_not_jsonl(self) -> None:
26 assert not is_jsonl_file(f"prefix_{SUFFIXES['info']}")
27
28 def test_random_json_is_not_jsonl(self) -> None:
29 assert not is_jsonl_file("something.json")
30
31
32 class TestIsInfoFile:
33 def test_info_file(self) -> None:
34 assert is_info_file(f"prefix_{SUFFIXES['info']}")
35
36 def test_usage_is_not_info(self) -> None:
37 assert not is_info_file(f"prefix_{SUFFIXES['usage']}")
38
39 def test_random_json_is_not_info(self) -> None:
40 assert not is_info_file("something.json")
41
42
43 class TestLoadUsageFile:
44 def test_load_usage_file(self, tmp_path: Path) -> None:
45 usage_file = tmp_path / SUFFIXES["usage"]
46 usage_file.write_text(
47 '{"timestamp": "2024-01-01", "totals": {"rss": 100}}\n'
48 '{"timestamp": "2024-01-02", "totals": {"rss": 200}}\n'
49 )
50 data = load_usage_file(str(usage_file))
51 assert len(data) == 2
52 assert data[0]["totals"]["rss"] == 100
53 assert data[1]["totals"]["rss"] == 200
54
55 def test_load_empty_usage_file(self, tmp_path: Path) -> None:
56 usage_file = tmp_path / SUFFIXES["usage"]
57 usage_file.write_text("")
58 data = load_usage_file(str(usage_file))
59 assert data == []
60
61 def test_load_usage_file_skips_blank_lines(self, tmp_path: Path) -> None:
62 usage_file = tmp_path / SUFFIXES["usage"]
63 usage_file.write_text('{"a": 1}\n\n{"b": 2}\n')
64 data = load_usage_file(str(usage_file))
65 assert len(data) == 2
66
67
68 class TestLoadInfoFile:
69 def test_load_info_file(self, tmp_path: Path) -> None:
70 info_file = tmp_path / SUFFIXES["info"]
71 info_file.write_text('{"command": "sleep 1", "exit_code": 0}')
72 data = load_info_file(str(info_file))
73 assert data["command"] == "sleep 1"
74 assert data["exit_code"] == 0
75
76 def test_load_info_file_not_found(self, tmp_path: Path) -> None:
77 with pytest.raises(FileNotFoundError):
78 load_info_file(str(tmp_path / "nonexistent.json"))
79
80 def test_load_info_file_invalid_json(self, tmp_path: Path) -> None:
81 info_file = tmp_path / SUFFIXES["info"]
82 info_file.write_text("not valid json")
83 with pytest.raises(json.JSONDecodeError):
84 load_info_file(str(info_file))
85
86
87 class TestJsonlSuffixes:
88 def test_contains_current_and_legacy(self) -> None:
89 assert SUFFIXES["usage"] in JSONL_SUFFIXES
90 assert SUFFIXES["usage_legacy"] in JSONL_SUFFIXES