test_accessors.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import typing as t
  2. from unittest.mock import Mock
  3. from taipy.gui import Gui
  4. from taipy.gui.data.data_accessor import (
  5. _DataAccessor,
  6. _DataAccessors,
  7. _InvalidDataAccessor,
  8. )
  9. from taipy.gui.data.data_format import _DataFormat
  10. from taipy.gui.utils.types import _TaipyData
  11. class MyDataAccessor(_DataAccessor):
  12. @staticmethod
  13. def get_supported_classes() -> t.List[t.Type]:
  14. return [int]
  15. def get_data(
  16. self,
  17. var_name: str,
  18. value: t.Any,
  19. payload: t.Dict[str, t.Any],
  20. data_format: _DataFormat,
  21. ) -> t.Dict[str, t.Any]:
  22. return {"value": 2 * int(value)}
  23. def get_cols_description(self, var_name: str, value: t.Any) -> t.Dict[str, t.Dict[str, str]]: # type: ignore
  24. pass
  25. def to_pandas(self, value: t.Any) -> t.Union[t.List[t.Any], t.Any]:
  26. pass
  27. def on_edit(self, value: t.Any, payload: t.Dict[str, t.Any]) -> t.Optional[t.Any]:
  28. pass
  29. def on_delete(self, value: t.Any, payload: t.Dict[str, t.Any]) -> t.Optional[t.Any]:
  30. pass
  31. def on_add(
  32. self,
  33. value: t.Any,
  34. payload: t.Dict[str, t.Any],
  35. new_row: t.Optional[t.List[t.Any]] = None,
  36. ) -> t.Optional[t.Any]:
  37. pass
  38. def to_csv(self, var_name: str, value: t.Any) -> t.Optional[str]:
  39. pass
  40. def mock_taipy_data(value):
  41. """Helper to mock _TaipyData objects."""
  42. mock_data = Mock(spec=_TaipyData)
  43. mock_data.get.return_value = value
  44. return mock_data
  45. def test_custom_accessor(gui: Gui):
  46. """Test if get_data() uses the correct accessor."""
  47. data_accessors = _DataAccessors(gui)
  48. data = mock_taipy_data(123)
  49. # Testing when accessor is not registered
  50. data_accessor = data_accessors._get_instance(mock_taipy_data) # type: ignore
  51. assert isinstance(
  52. data_accessor, _InvalidDataAccessor
  53. ), f"Expected _InvalidDataAccessor but got {type(data_accessor)}"
  54. result = data_accessors.get_data("var_name", data, {})
  55. assert result == {}
  56. # Testing when accessor is registered
  57. data_accessors._register(MyDataAccessor)
  58. result = data_accessors.get_data("var_name", data, {})
  59. assert isinstance(result, dict)
  60. assert result["value"] == 246
  61. data_accessors._unregister(MyDataAccessor)