|
| 1 | +# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. |
| 2 | +# |
| 3 | +# Copyright (C) 2026 Tencent. All rights reserved. |
| 4 | +# |
| 5 | +# tRPC-Agent-Python is licensed under Apache-2.0. |
| 6 | +"""Unit tests for trpc_agent_sdk.utils._json_repair. |
| 7 | +
|
| 8 | +Covers: |
| 9 | +- json_loads_repair: parses valid JSON, repairs malformed JSON, decodes bytes, |
| 10 | + forwards kwargs, raises JSONDecodeError when unrecoverable. |
| 11 | +- json_repair_string: returns a valid JSON string for valid/malformed inputs, |
| 12 | + decodes bytes, forwards kwargs, raises JSONDecodeError when unrecoverable. |
| 13 | +""" |
| 14 | + |
| 15 | +import json |
| 16 | + |
| 17 | +import pytest |
| 18 | + |
| 19 | +from trpc_agent_sdk.utils import json_loads_repair |
| 20 | +from trpc_agent_sdk.utils import json_repair_string |
| 21 | + |
| 22 | + |
| 23 | +class TestJsonLoadsRepair: |
| 24 | + """Test suite for json_loads_repair.""" |
| 25 | + |
| 26 | + def test_valid_json_object(self): |
| 27 | + assert json_loads_repair('{"a": 1, "b": "x"}') == {"a": 1, "b": "x"} |
| 28 | + |
| 29 | + def test_valid_json_array(self): |
| 30 | + assert json_loads_repair("[1, 2, 3]") == [1, 2, 3] |
| 31 | + |
| 32 | + def test_valid_json_scalar(self): |
| 33 | + assert json_loads_repair("true") is True |
| 34 | + assert json_loads_repair("null") is None |
| 35 | + assert json_loads_repair("123") == 123 |
| 36 | + |
| 37 | + def test_missing_comma_repaired(self): |
| 38 | + result = json_loads_repair('{"city": "Beijing" "unit": "celsius"}') |
| 39 | + assert result == {"city": "Beijing", "unit": "celsius"} |
| 40 | + |
| 41 | + def test_trailing_comma_repaired(self): |
| 42 | + result = json_loads_repair('{"a": 1, "b": 2,}') |
| 43 | + assert result == {"a": 1, "b": 2} |
| 44 | + |
| 45 | + def test_single_quoted_keys_repaired(self): |
| 46 | + result = json_loads_repair("{'a': 'b'}") |
| 47 | + assert result == {"a": "b"} |
| 48 | + |
| 49 | + def test_unclosed_object_repaired(self): |
| 50 | + result = json_loads_repair('{"a": 1, "b": 2') |
| 51 | + assert result == {"a": 1, "b": 2} |
| 52 | + |
| 53 | + def test_code_fence_wrapped_json_repaired(self): |
| 54 | + payload = '```json\n{"a": 1}\n```' |
| 55 | + result = json_loads_repair(payload) |
| 56 | + assert result == {"a": 1} |
| 57 | + |
| 58 | + def test_bytes_input_decoded_and_parsed(self): |
| 59 | + result = json_loads_repair(b'{"a": 1}') |
| 60 | + assert result == {"a": 1} |
| 61 | + |
| 62 | + def test_bytearray_input_decoded_and_repaired(self): |
| 63 | + result = json_loads_repair(bytearray(b'{"a": 1 "b": 2}')) |
| 64 | + assert result == {"a": 1, "b": 2} |
| 65 | + |
| 66 | + def test_non_utf8_bytes_replaced_not_raised(self): |
| 67 | + # decode(errors="replace") should keep us off the exception path for |
| 68 | + # invalid utf-8 bytes; the repaired result is still a usable JSON value. |
| 69 | + result = json_loads_repair(b'\xff{"a": 1}') |
| 70 | + assert isinstance(result, (dict, list, str, int, float, bool)) or result is None |
| 71 | + |
| 72 | + def test_unicode_preserved(self): |
| 73 | + assert json_loads_repair('{"name": "北京"}') == {"name": "北京"} |
| 74 | + |
| 75 | + def test_unrecoverable_input_raises_json_decode_error(self, monkeypatch): |
| 76 | + import trpc_agent_sdk.utils._json_repair as module |
| 77 | + |
| 78 | + def _boom(*_args, **_kwargs): |
| 79 | + raise RuntimeError("unrecoverable") |
| 80 | + |
| 81 | + monkeypatch.setattr(module.json_repair, "loads", _boom) |
| 82 | + |
| 83 | + with pytest.raises(json.JSONDecodeError): |
| 84 | + json_loads_repair('{"oops"') |
| 85 | + |
| 86 | + def test_kwargs_forwarded_to_json_repair(self, monkeypatch): |
| 87 | + import trpc_agent_sdk.utils._json_repair as module |
| 88 | + |
| 89 | + captured = {} |
| 90 | + |
| 91 | + def _fake_loads(value, **kwargs): |
| 92 | + captured["value"] = value |
| 93 | + captured["kwargs"] = kwargs |
| 94 | + return {"ok": True} |
| 95 | + |
| 96 | + monkeypatch.setattr(module.json_repair, "loads", _fake_loads) |
| 97 | + |
| 98 | + result = json_loads_repair('{"x": 1}', skip_json_loads=True, logging=False) |
| 99 | + |
| 100 | + assert result == {"ok": True} |
| 101 | + assert captured["value"] == '{"x": 1}' |
| 102 | + assert captured["kwargs"] == {"skip_json_loads": True, "logging": False} |
| 103 | + |
| 104 | + |
| 105 | +class TestJsonRepairString: |
| 106 | + """Test suite for json_repair_string.""" |
| 107 | + |
| 108 | + def test_valid_json_returns_canonical_string(self): |
| 109 | + repaired = json_repair_string('{"a": 1, "b": "x"}') |
| 110 | + assert json.loads(repaired) == {"a": 1, "b": "x"} |
| 111 | + |
| 112 | + def test_missing_comma_repaired(self): |
| 113 | + repaired = json_repair_string('{"city": "Beijing" "unit": "celsius"}') |
| 114 | + assert json.loads(repaired) == {"city": "Beijing", "unit": "celsius"} |
| 115 | + |
| 116 | + def test_single_quoted_keys_repaired(self): |
| 117 | + repaired = json_repair_string("{'a': 'b'}") |
| 118 | + assert json.loads(repaired) == {"a": "b"} |
| 119 | + |
| 120 | + def test_unclosed_object_repaired(self): |
| 121 | + repaired = json_repair_string('{"a": 1, "b": 2') |
| 122 | + assert json.loads(repaired) == {"a": 1, "b": 2} |
| 123 | + |
| 124 | + def test_array_repaired(self): |
| 125 | + repaired = json_repair_string("[1, 2 3,]") |
| 126 | + assert json.loads(repaired) == [1, 2, 3] |
| 127 | + |
| 128 | + def test_bytes_input_decoded(self): |
| 129 | + repaired = json_repair_string(b'{"a": 1}') |
| 130 | + assert json.loads(repaired) == {"a": 1} |
| 131 | + |
| 132 | + def test_bytearray_input_decoded_and_repaired(self): |
| 133 | + repaired = json_repair_string(bytearray(b'{"a": 1 "b": 2}')) |
| 134 | + assert json.loads(repaired) == {"a": 1, "b": 2} |
| 135 | + |
| 136 | + def test_ensure_ascii_passthrough_default_preserves_unicode(self): |
| 137 | + repaired = json_repair_string('{"name": "北京"}', ensure_ascii=False) |
| 138 | + assert "北京" in repaired |
| 139 | + assert json.loads(repaired) == {"name": "北京"} |
| 140 | + |
| 141 | + def test_ensure_ascii_true_escapes_unicode(self): |
| 142 | + repaired = json_repair_string('{"name": "北京"}', ensure_ascii=True) |
| 143 | + assert "北京" not in repaired |
| 144 | + assert json.loads(repaired) == {"name": "北京"} |
| 145 | + |
| 146 | + def test_return_type_is_string(self): |
| 147 | + assert isinstance(json_repair_string('{"a": 1}'), str) |
| 148 | + |
| 149 | + def test_unrecoverable_input_raises_json_decode_error(self, monkeypatch): |
| 150 | + import trpc_agent_sdk.utils._json_repair as module |
| 151 | + |
| 152 | + def _boom(*_args, **_kwargs): |
| 153 | + raise RuntimeError("unrecoverable") |
| 154 | + |
| 155 | + monkeypatch.setattr(module.json_repair, "repair_json", _boom) |
| 156 | + |
| 157 | + with pytest.raises(json.JSONDecodeError): |
| 158 | + json_repair_string('{"oops"') |
| 159 | + |
| 160 | + def test_kwargs_forwarded_to_json_repair(self, monkeypatch): |
| 161 | + import trpc_agent_sdk.utils._json_repair as module |
| 162 | + |
| 163 | + captured = {} |
| 164 | + |
| 165 | + def _fake_repair_json(value, **kwargs): |
| 166 | + captured["value"] = value |
| 167 | + captured["kwargs"] = kwargs |
| 168 | + return '{"ok": true}' |
| 169 | + |
| 170 | + monkeypatch.setattr(module.json_repair, "repair_json", _fake_repair_json) |
| 171 | + |
| 172 | + repaired = json_repair_string('{"x": 1}', ensure_ascii=False, logging=False) |
| 173 | + |
| 174 | + assert repaired == '{"ok": true}' |
| 175 | + assert captured["value"] == '{"x": 1}' |
| 176 | + assert captured["kwargs"] == {"ensure_ascii": False, "logging": False} |
0 commit comments