PlanOpticon

planopticon / tests / test_json_parsing.py
Blame History Raw 71 lines
1
"""Tests for robust JSON parsing from LLM responses."""
2
3
from video_processor.utils.json_parsing import parse_json_from_response
4
5
6
class TestParseJsonFromResponse:
7
def test_direct_dict(self):
8
assert parse_json_from_response('{"key": "value"}') == {"key": "value"}
9
10
def test_direct_array(self):
11
assert parse_json_from_response("[1, 2, 3]") == [1, 2, 3]
12
13
def test_markdown_fenced_json(self):
14
text = '```json\n{"key": "value"}\n```'
15
assert parse_json_from_response(text) == {"key": "value"}
16
17
def test_markdown_fenced_no_lang(self):
18
text = "```\n[1, 2]\n```"
19
assert parse_json_from_response(text) == [1, 2]
20
21
def test_json_embedded_in_text(self):
22
text = 'Here is the result:\n{"name": "test", "value": 42}\nEnd of result.'
23
result = parse_json_from_response(text)
24
assert result == {"name": "test", "value": 42}
25
26
def test_array_embedded_in_text(self):
27
text = 'The entities are:\n[{"name": "Alice"}, {"name": "Bob"}]\nThat is all.'
28
result = parse_json_from_response(text)
29
assert len(result) == 2
30
assert result[0]["name"] == "Alice"
31
32
def test_nested_json(self):
33
text = '{"outer": {"inner": [1, 2, 3]}}'
34
result = parse_json_from_response(text)
35
assert result["outer"]["inner"] == [1, 2, 3]
36
37
def test_empty_string(self):
38
assert parse_json_from_response("") is None
39
40
def test_none_input(self):
41
assert parse_json_from_response(None) is None
42
43
def test_whitespace_only(self):
44
assert parse_json_from_response(" \n ") is None
45
46
def test_no_json(self):
47
assert parse_json_from_response("This is just plain text.") is None
48
49
def test_invalid_json(self):
50
assert parse_json_from_response("{invalid json}") is None
51
52
def test_multiple_json_objects_picks_first(self):
53
text = '{"a": 1} and {"b": 2}'
54
result = parse_json_from_response(text)
55
assert result == {"a": 1}
56
57
def test_complex_fenced(self):
58
text = """Here is the analysis:
59
60
```json
61
[
62
{"point": "Architecture uses microservices", "topic": "Architecture"},
63
{"point": "Deployment is automated", "topic": "DevOps"}
64
]
65
```
66
67
I hope this helps!"""
68
result = parse_json_from_response(text)
69
assert len(result) == 2
70
assert result[0]["topic"] == "Architecture"
71

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button