|
| 1 | +""" test round trip (de)serialization behavior of AindGeneric models""" |
| 2 | + |
| 3 | +import unittest |
| 4 | + |
| 5 | +from pydantic import BaseModel, Field |
| 6 | + |
| 7 | +from aind_data_schema.base import AindGeneric, AindModel |
| 8 | + |
| 9 | + |
| 10 | +class GenericContainer(AindModel): |
| 11 | + """Represents a generic container""" |
| 12 | + |
| 13 | + contains_model: AindGeneric |
| 14 | + contains_dict: AindGeneric |
| 15 | + |
| 16 | + |
| 17 | +class Bar(BaseModel): |
| 18 | + """Represents a mock model""" |
| 19 | + |
| 20 | + bar: str = Field(default="bar") |
| 21 | + foo: int = Field(default=1) |
| 22 | + |
| 23 | + |
| 24 | +class SubGenericContainer(GenericContainer): |
| 25 | + """Represents a subclass of GenericContainer where contains_model is typed to Bar""" |
| 26 | + |
| 27 | + contains_model: Bar |
| 28 | + |
| 29 | + |
| 30 | +class AindGenericTests(unittest.TestCase): |
| 31 | + """tests device schemas""" |
| 32 | + |
| 33 | + def test_sub_generic_container_round_trip(self): |
| 34 | + """tests a round trip (de)serialization of the SubGenericContainer""" |
| 35 | + |
| 36 | + sub_generic_container = SubGenericContainer( |
| 37 | + contains_model=Bar(bar="baz", foo=2), |
| 38 | + contains_dict={"foodict": 1, "bardict": "bar"}, |
| 39 | + ) |
| 40 | + deserialized = SubGenericContainer.model_validate_json(sub_generic_container.model_dump_json()) |
| 41 | + self.assertEqual(sub_generic_container, deserialized) |
| 42 | + |
| 43 | + def test_sub_generic_container_from_parent_round_trip(self): |
| 44 | + """tests a round trip (de)serialization of the SubGenericContainer from the parent""" |
| 45 | + sub_generic_container = SubGenericContainer( |
| 46 | + contains_model=Bar(bar="baz", foo=2), |
| 47 | + contains_dict={"foodict": 1, "bardict": "bar"}, |
| 48 | + ) |
| 49 | + deserialized_parent = GenericContainer.model_validate_json(sub_generic_container.model_dump_json()) |
| 50 | + deserialized = SubGenericContainer.model_validate_json(deserialized_parent.model_dump_json()) |
| 51 | + self.assertEqual(sub_generic_container, deserialized) |
| 52 | + |
| 53 | + def test_sub_container_from_container(self): |
| 54 | + """tests if a model created directly from GenericContainer can be deserialized from the SubGenericContainer""" |
| 55 | + |
| 56 | + sub_generic_container = SubGenericContainer( |
| 57 | + contains_model=Bar(bar="baz", foo=2), |
| 58 | + contains_dict={"foodict": 1, "bardict": "bar"}, |
| 59 | + ) |
| 60 | + parent_container = GenericContainer( |
| 61 | + contains_model=Bar(bar="baz", foo=2).model_dump(), |
| 62 | + contains_dict={"foodict": 1, "bardict": "bar"}, |
| 63 | + ) |
| 64 | + deserialized = SubGenericContainer.model_validate_json(parent_container.model_dump_json()) |
| 65 | + self.assertEqual(sub_generic_container, deserialized) |
0 commit comments