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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
"""Test parser functions that converts the incoming json from API into dataclass models."""
import datetime
from dataclasses import dataclass
import pytest
from aiohue.util import dataclass_from_dict
@dataclass
class BasicModelChild:
"""Basic test model."""
a: int
b: str
c: str
d: int | None
@dataclass
class BasicModel:
"""Basic test model."""
a: int
b: float
c: str
d: int | None
e: BasicModelChild
f: datetime.datetime
g: str = "default"
def test_dataclass_from_dict():
"""Test dataclass from dict parsing."""
raw = {
"a": 1,
"b": 1.0,
"c": "hello",
"d": 1,
"e": {"a": 2, "b": "test", "c": "test", "d": None},
"f": "2022-12-09T06:58:00Z",
}
res = dataclass_from_dict(BasicModel, raw)
# test the basic values
assert isinstance(res, BasicModel)
assert res.a == 1
assert res.b == 1.0
assert res.d == 1
# test recursive parsing
assert isinstance(res.e, BasicModelChild)
# test default value
assert res.g == "default"
# test int gets converted to float
raw["b"] = 2
res = dataclass_from_dict(BasicModel, raw)
assert res.b == 2.0
# test datetime string
assert isinstance(res.f, datetime.datetime)
assert res.f.month == 12
assert res.f.day == 9
# test string doesn't match int
with pytest.raises(TypeError):
raw2 = {**raw}
raw2["a"] = "blah"
dataclass_from_dict(BasicModel, raw2)
# test missing key result in keyerror
with pytest.raises(KeyError):
raw2 = {**raw}
del raw2["a"]
dataclass_from_dict(BasicModel, raw2)
# test extra keys silently ignored in non-strict mode
raw2 = {**raw}
raw2["extrakey"] = "something"
dataclass_from_dict(BasicModel, raw2, strict=False)
# test extra keys not silently ignored in strict mode
with pytest.raises(KeyError):
dataclass_from_dict(BasicModel, raw2, strict=True)
|