|
| 1 | +import datetime |
| 2 | +import json |
| 3 | +from decimal import Decimal |
| 4 | +from enum import Enum |
| 5 | +from uuid import UUID |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from pydantic import BaseModel, create_model |
| 10 | +from pydantic.json import pydantic_encoder |
| 11 | + |
| 12 | + |
| 13 | +class MyEnum(Enum): |
| 14 | + foo = 'bar' |
| 15 | + snap = 'crackle' |
| 16 | + |
| 17 | + |
| 18 | +@pytest.mark.parametrize('input,output', [ |
| 19 | + (UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8'), '"ebcdab58-6eb8-46fb-a190-d07a33e9eac8"'), |
| 20 | + (datetime.datetime(2032, 1, 1, 1, 1), '"2032-01-01T01:01:00"'), |
| 21 | + (datetime.datetime(2032, 1, 1, 1, 1, tzinfo=datetime.timezone.utc), '"2032-01-01T01:01:00+00:00"'), |
| 22 | + (datetime.datetime(2032, 1, 1), '"2032-01-01T00:00:00"'), |
| 23 | + (datetime.time(12, 34, 56), '"12:34:56"'), |
| 24 | + ({1, 2, 3}, '[1, 2, 3]'), |
| 25 | + (frozenset([1, 2, 3]), '[1, 2, 3]'), |
| 26 | + ((v for v in range(4)), '[0, 1, 2, 3]'), |
| 27 | + (b'this is bytes', '"this is bytes"'), |
| 28 | + (Decimal('12.34'), '12.34'), |
| 29 | + (create_model('BarModel', a='b', c='d')(), '{"a": "b", "c": "d"}'), |
| 30 | + (MyEnum.foo, '"bar"') |
| 31 | +]) |
| 32 | +def test_encoding(input, output): |
| 33 | + assert json.dumps(input, default=pydantic_encoder) == output |
| 34 | + |
| 35 | + |
| 36 | +def test_model_encoding(): |
| 37 | + class ModelA(BaseModel): |
| 38 | + x: int |
| 39 | + y: str |
| 40 | + |
| 41 | + class Model(BaseModel): |
| 42 | + a: float |
| 43 | + b: bytes |
| 44 | + c: Decimal |
| 45 | + d: ModelA |
| 46 | + |
| 47 | + m = Model(a=10.2, b='foobar', c=10.2, d={'x': 123, 'y': '123'}) |
| 48 | + assert m.dict() == {'a': 10.2, 'b': b'foobar', 'c': Decimal('10.2'), 'd': {'x': 123, 'y': '123'}} |
| 49 | + assert m.json() == '{"a": 10.2, "b": "foobar", "c": 10.2, "d": {"x": 123, "y": "123"}}' |
| 50 | + assert m.json(exclude={'b'}) == '{"a": 10.2, "c": 10.2, "d": {"x": 123, "y": "123"}}' |
| 51 | + |
| 52 | + |
| 53 | +def test_invalid_model(): |
| 54 | + class Foo: |
| 55 | + pass |
| 56 | + |
| 57 | + with pytest.raises(TypeError): |
| 58 | + json.dumps(Foo, default=pydantic_encoder) |
0 commit comments