File: test_decimal.py

package info (click to toggle)
pydantic-core 2.41.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,828 kB
  • sloc: python: 35,564; javascript: 211; makefile: 128
file content (63 lines) | stat: -rw-r--r-- 2,267 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from decimal import Decimal

import pytest

from pydantic_core import SchemaSerializer, core_schema


def test_decimal():
    v = SchemaSerializer(core_schema.decimal_schema())
    assert v.to_python(Decimal('123.456')) == Decimal('123.456')

    assert v.to_python(Decimal('123.456'), mode='json') == '123.456'
    assert v.to_json(Decimal('123.456')) == b'"123.456"'

    assert v.to_python(Decimal('123456789123456789123456789.123456789123456789123456789')) == Decimal(
        '123456789123456789123456789.123456789123456789123456789'
    )
    assert (
        v.to_json(Decimal('123456789123456789123456789.123456789123456789123456789'))
        == b'"123456789123456789123456789.123456789123456789123456789"'
    )

    with pytest.warns(
        UserWarning,
        match=r'Expected `decimal` - serialized value may not be as expected \[input_value=123, input_type=int\]',
    ):
        assert v.to_python(123, mode='json') == 123

    with pytest.warns(
        UserWarning,
        match=r'Expected `decimal` - serialized value may not be as expected \[input_value=123, input_type=int\]',
    ):
        assert v.to_json(123) == b'123'


def test_decimal_key():
    v = SchemaSerializer(core_schema.dict_schema(core_schema.decimal_schema(), core_schema.decimal_schema()))
    assert v.to_python({Decimal('123.456'): Decimal('123.456')}) == {Decimal('123.456'): Decimal('123.456')}
    assert v.to_python({Decimal('123.456'): Decimal('123.456')}, mode='json') == {'123.456': '123.456'}
    assert v.to_json({Decimal('123.456'): Decimal('123.456')}) == b'{"123.456":"123.456"}'


@pytest.mark.parametrize(
    'value,expected',
    [
        (Decimal('123.456'), '123.456'),
        (Decimal('Infinity'), 'Infinity'),
        (Decimal('-Infinity'), '-Infinity'),
        (Decimal('NaN'), 'NaN'),
    ],
)
def test_decimal_json(value, expected):
    v = SchemaSerializer(core_schema.decimal_schema())
    assert v.to_python(value, mode='json') == expected
    assert v.to_json(value).decode() == f'"{expected}"'


def test_any_decimal_key():
    v = SchemaSerializer(core_schema.dict_schema())
    input_value = {Decimal('123.456'): 1}

    assert v.to_python(input_value, mode='json') == {'123.456': 1}
    assert v.to_json(input_value) == b'{"123.456":1}'