Consolidate duplicate _parse_json helpers from content_editor.py /
design_director.py / kei_client.py (fuller form) and pipeline.py (simple form)
into shared src/json_utils.parse_json (strict superset). All 18 call-sites
preserved via `parse_json as _parse_json` alias import; no behavior change.
- src/json_utils.py (new): shared helper, fenced/plain-fence/bare-brace patterns
+ list-prefix cleanup fallback.
- tests/test_json_utils.py (new): 9 unit tests pinning parser semantics.
- src/content_editor.py / design_director.py: remove local helper +
unused `import json` / `import re`.
- src/kei_client.py / pipeline.py: remove local helper; `json` / `re` retained
(used elsewhere).
Targeted tests 9 passed; full pytest 374 passed (3 pre-existing scripts/
collection errors reproduce on baseline 909bf75, IMP-28 unrelated).
56 lines
1.5 KiB
Python
56 lines
1.5 KiB
Python
"""Unit tests for ``src.json_utils.parse_json``.
|
|
|
|
IMP-28 L4 — `_parse_json` dedup unit u2.
|
|
|
|
Pins the shared helper semantics that previously lived in
|
|
content_editor.py / design_director.py / kei_client.py (fuller form) and
|
|
pipeline.py (simple form). The fuller form is a strict superset of the
|
|
simple form; these tests cover both axes.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from src.json_utils import parse_json
|
|
|
|
|
|
def test_parse_json_fenced_json_block():
|
|
text = 'prefix\n```json\n{"a": 1, "b": "x"}\n```\nsuffix'
|
|
assert parse_json(text) == {"a": 1, "b": "x"}
|
|
|
|
|
|
def test_parse_json_plain_fenced_block():
|
|
text = 'prefix\n```\n{"x": 2}\n```\nsuffix'
|
|
assert parse_json(text) == {"x": 2}
|
|
|
|
|
|
def test_parse_json_bare_braces():
|
|
text = 'noise before {"y": 3, "z": [1, 2]} noise after'
|
|
assert parse_json(text) == {"y": 3, "z": [1, 2]}
|
|
|
|
|
|
def test_parse_json_list_prefix_dash_cleanup():
|
|
text = '- {"b": 4}'
|
|
assert parse_json(text) == {"b": 4}
|
|
|
|
|
|
def test_parse_json_list_prefix_star_cleanup():
|
|
text = '* {"c": 5}'
|
|
assert parse_json(text) == {"c": 5}
|
|
|
|
|
|
def test_parse_json_no_json_returns_none():
|
|
assert parse_json("no json here at all") is None
|
|
|
|
|
|
def test_parse_json_malformed_returns_none():
|
|
assert parse_json("{ invalid json") is None
|
|
|
|
|
|
def test_parse_json_prefix_free_no_op():
|
|
text = '{"d": 6}'
|
|
assert parse_json(text) == {"d": 6}
|
|
|
|
|
|
def test_parse_json_fenced_preferred_over_bare_braces():
|
|
text = 'outer {"outer": true} ```json\n{"inner": 1}\n```'
|
|
assert parse_json(text) == {"inner": 1}
|