mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
116 lines
2.2 KiB
Python
116 lines
2.2 KiB
Python
import pytest
|
|
|
|
import pydantic
|
|
from pydantic import ValidationError
|
|
|
|
|
|
def test_simple():
|
|
@pydantic.dataclasses.dataclass
|
|
class MyDataclass:
|
|
a: int
|
|
b: float
|
|
|
|
d = MyDataclass('1', '2.5')
|
|
assert d.a == 1
|
|
assert d.b == 2.5
|
|
d = MyDataclass(b=10, a=20)
|
|
assert d.a == 20
|
|
assert d.b == 10
|
|
|
|
|
|
def test_value_error():
|
|
@pydantic.dataclasses.dataclass
|
|
class MyDataclass:
|
|
a: int
|
|
b: int
|
|
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
MyDataclass(1, 'wrong')
|
|
|
|
assert exc_info.value.errors() == [
|
|
{'loc': ('b',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
|
|
]
|
|
|
|
|
|
def test_frozen():
|
|
@pydantic.dataclasses.dataclass(frozen=True)
|
|
class MyDataclass:
|
|
a: int
|
|
|
|
d = MyDataclass(1)
|
|
assert d.a == 1
|
|
|
|
with pytest.raises(AttributeError):
|
|
d.a = 7
|
|
|
|
|
|
def test_validate_assignment():
|
|
@pydantic.dataclasses.dataclass(validate_assignment=True)
|
|
class MyDataclass:
|
|
a: int
|
|
|
|
d = MyDataclass(1)
|
|
assert d.a == 1
|
|
|
|
d.a = '7'
|
|
assert d.a == 7
|
|
|
|
|
|
def test_validate_assignment_error():
|
|
@pydantic.dataclasses.dataclass(validate_assignment=True)
|
|
class MyDataclass:
|
|
a: int
|
|
|
|
d = MyDataclass(1)
|
|
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
d.a = 'xxx'
|
|
assert exc_info.value.errors() == [
|
|
{'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
|
|
]
|
|
|
|
|
|
def test_not_validate_assignment():
|
|
@pydantic.dataclasses.dataclass
|
|
class MyDataclass:
|
|
a: int
|
|
|
|
d = MyDataclass(1)
|
|
assert d.a == 1
|
|
|
|
d.a = '7'
|
|
assert d.a == '7'
|
|
|
|
|
|
def test_post_init():
|
|
post_init_called = False
|
|
|
|
@pydantic.dataclasses.dataclass
|
|
class MyDataclass:
|
|
a: int
|
|
|
|
def __post_init__(self):
|
|
nonlocal post_init_called
|
|
post_init_called = True
|
|
|
|
d = MyDataclass('1')
|
|
assert d.a == 1
|
|
assert post_init_called
|
|
|
|
|
|
def test_inheritance():
|
|
@pydantic.dataclasses.dataclass
|
|
class A:
|
|
a: str = None
|
|
|
|
@pydantic.dataclasses.dataclass
|
|
class B(A):
|
|
b: int = None
|
|
|
|
b = B(a='a', b=12)
|
|
assert b.a == 'a'
|
|
assert b.b == 12
|
|
|
|
with pytest.raises(ValidationError):
|
|
B(a='a', b='b')
|