|
1 | 1 | import re |
2 | 2 |
|
3 | 3 | import pytest |
| 4 | +from dirty_equals import IsList |
4 | 5 |
|
5 | | -from pydantic_core import SchemaValidator, ValidationError, to_json |
| 6 | +from pydantic_core import PydanticSerializationError, SchemaValidator, ValidationError, to_json, to_jsonable_python |
6 | 7 |
|
7 | 8 | from .conftest import Err |
8 | 9 |
|
@@ -184,12 +185,25 @@ def __str__(self): |
184 | 185 | def test_to_json(): |
185 | 186 | assert to_json([1, 2]) == b'[1,2]' |
186 | 187 | assert to_json([1, 2], indent=2) == b'[\n 1,\n 2\n]' |
| 188 | + assert to_json([1, b'x']) == b'[1,"x"]' |
187 | 189 |
|
188 | | - with pytest.raises(ValueError, match='Unable to serialize unknown type:'): |
| 190 | + with pytest.raises(PydanticSerializationError, match=r'Unable to serialize unknown type: <.+\.Foobar'): |
189 | 191 | to_json(Foobar()) |
190 | 192 |
|
191 | 193 | assert to_json(Foobar(), serialize_unknown=True) == b'"Foobar.__str__"' |
192 | 194 |
|
193 | 195 | # kwargs required |
194 | 196 | with pytest.raises(TypeError, match=r'to_json\(\) takes 1 positional arguments but 2 were given'): |
195 | 197 | to_json([1, 2], 2) |
| 198 | + |
| 199 | + |
| 200 | +def test_to_jsonable_python(): |
| 201 | + assert to_jsonable_python([1, 2]) == [1, 2] |
| 202 | + assert to_jsonable_python({1, 2}) == IsList(1, 2, check_order=False) |
| 203 | + assert to_jsonable_python([1, b'x']) == [1, 'x'] |
| 204 | + assert to_jsonable_python([0, 1, 2, 3, 4], exclude={1, 3}) == [0, 2, 4] |
| 205 | + |
| 206 | + with pytest.raises(PydanticSerializationError, match=r'Unable to serialize unknown type: <.+\.Foobar'): |
| 207 | + to_jsonable_python(Foobar()) |
| 208 | + |
| 209 | + assert to_jsonable_python(Foobar(), serialize_unknown=True) == 'Foobar.__str__' |
0 commit comments