test_base_model.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import dataclasses
  12. import enum
  13. import json
  14. import pytest
  15. from taipy.core._repository._base_taipy_model import _BaseModel, _Encoder
  16. class SampleEnum(enum.Enum):
  17. VALUE1 = "value1"
  18. VALUE2 = "value2"
  19. @dataclasses.dataclass
  20. class SampleModel(_BaseModel):
  21. attr1: int
  22. attr2: str
  23. attr3: SampleEnum
  24. @pytest.fixture
  25. def sample_model():
  26. return SampleModel(attr1=1, attr2="test", attr3=SampleEnum.VALUE1)
  27. def test_iter(sample_model):
  28. items = dict(sample_model)
  29. expected_items = {"attr1": 1, "attr2": "test", "attr3": SampleEnum.VALUE1}
  30. assert items == expected_items
  31. def test_to_dict(sample_model):
  32. model_dict = sample_model.to_dict()
  33. expected_dict = {"attr1": 1, "attr2": "test", "attr3": repr(SampleEnum.VALUE1)}
  34. assert model_dict == expected_dict
  35. def test_serialize_attribute(sample_model):
  36. serialized = _BaseModel._serialize_attribute(sample_model.attr2)
  37. expected_serialized = json.dumps(sample_model.attr2, ensure_ascii=False, cls=_Encoder)
  38. assert serialized == expected_serialized
  39. def test_deserialize_attribute(sample_model):
  40. serialized = json.dumps(sample_model.attr2, ensure_ascii=False, cls=_Encoder)
  41. deserialized = _BaseModel._deserialize_attribute(serialized)
  42. assert deserialized == sample_model.attr2