test_pickle_data_node.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 os
  12. import pathlib
  13. from datetime import datetime
  14. from time import sleep
  15. import pandas as pd
  16. import pytest
  17. from taipy.config.common.scope import Scope
  18. from taipy.config.config import Config
  19. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  20. from taipy.core.data._data_manager import _DataManager
  21. from taipy.core.data._data_manager_factory import _DataManagerFactory
  22. from taipy.core.data.pickle import PickleDataNode
  23. from taipy.core.exceptions.exceptions import NoData
  24. @pytest.fixture(scope="function", autouse=True)
  25. def cleanup():
  26. yield
  27. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.p")
  28. if os.path.isfile(path):
  29. os.remove(path)
  30. class TestPickleDataNodeEntity:
  31. @pytest.fixture(scope="function", autouse=True)
  32. def remove_pickle_files(self):
  33. yield
  34. import glob
  35. for f in glob.glob("*.p"):
  36. os.remove(f)
  37. def test_create_with_manager(self, pickle_file_path):
  38. parquet_dn_config = Config.configure_pickle_data_node(id="baz", default_path=pickle_file_path)
  39. parquet_dn = _DataManagerFactory._build_manager()._create_and_set(parquet_dn_config, None, None)
  40. assert isinstance(parquet_dn, PickleDataNode)
  41. def test_create(self):
  42. pickle_dn_config = Config.configure_pickle_data_node(
  43. id="foobar_bazxyxea", default_path="Data", default_data="Data"
  44. )
  45. dn = _DataManagerFactory._build_manager()._create_and_set(pickle_dn_config, None, None)
  46. assert isinstance(dn, PickleDataNode)
  47. assert dn.storage_type() == "pickle"
  48. assert dn.config_id == "foobar_bazxyxea"
  49. assert dn.scope == Scope.SCENARIO
  50. assert dn.id is not None
  51. assert dn.name is None
  52. assert dn.owner_id is None
  53. assert dn.last_edit_date is not None
  54. assert dn.job_ids == []
  55. assert dn.is_ready_for_reading
  56. assert dn.read() == "Data"
  57. assert dn.last_edit_date is not None
  58. assert dn.job_ids == []
  59. with pytest.raises(InvalidConfigurationId):
  60. PickleDataNode("foobar bazxyxea", Scope.SCENARIO, properties={"default_data": "Data"})
  61. def test_get_user_properties(self, pickle_file_path):
  62. dn_1 = PickleDataNode("dn_1", Scope.SCENARIO, properties={"path": pickle_file_path})
  63. assert dn_1._get_user_properties() == {}
  64. dn_2 = PickleDataNode(
  65. "dn_2",
  66. Scope.SCENARIO,
  67. properties={
  68. "default_data": "foo",
  69. "default_path": pickle_file_path,
  70. "foo": "bar",
  71. },
  72. )
  73. # default_data, default_path, path, is_generated are filtered out
  74. assert dn_2._get_user_properties() == {"foo": "bar"}
  75. def test_new_pickle_data_node_with_existing_file_is_ready_for_reading(self):
  76. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "pickle", path="NOT_EXISTING.p")
  77. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  78. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "pickle", path=path)
  79. dns = _DataManager._bulk_get_or_create([not_ready_dn_cfg, ready_dn_cfg])
  80. assert not dns[not_ready_dn_cfg].is_ready_for_reading
  81. assert dns[ready_dn_cfg].is_ready_for_reading
  82. def test_create_with_file_name(self):
  83. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar", "path": "foo.FILE.p"})
  84. assert os.path.isfile("foo.FILE.p")
  85. assert dn.read() == "bar"
  86. dn.write("qux")
  87. assert dn.read() == "qux"
  88. dn.write(1998)
  89. assert dn.read() == 1998
  90. def test_read_and_write(self):
  91. no_data_dn = PickleDataNode("foo", Scope.SCENARIO)
  92. with pytest.raises(NoData):
  93. assert no_data_dn.read() is None
  94. no_data_dn.read_or_raise()
  95. pickle_str = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar"})
  96. assert isinstance(pickle_str.read(), str)
  97. assert pickle_str.read() == "bar"
  98. pickle_str.properties["default_data"] = "baz" # this modifies the default data value but not the data itself
  99. assert pickle_str.read() == "bar"
  100. pickle_str.write("qux")
  101. assert pickle_str.read() == "qux"
  102. pickle_str.write(1998)
  103. assert pickle_str.read() == 1998
  104. assert isinstance(pickle_str.read(), int)
  105. pickle_int = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": 197})
  106. assert isinstance(pickle_int.read(), int)
  107. assert pickle_int.read() == 197
  108. pickle_dict = PickleDataNode(
  109. "foo", Scope.SCENARIO, properties={"default_data": {"bar": 12, "baz": "qux", "quux": [13]}}
  110. )
  111. assert isinstance(pickle_dict.read(), dict)
  112. assert pickle_dict.read() == {"bar": 12, "baz": "qux", "quux": [13]}
  113. def test_path_overrides_default_path(self):
  114. dn = PickleDataNode(
  115. "foo",
  116. Scope.SCENARIO,
  117. properties={
  118. "default_data": "bar",
  119. "default_path": "foo.FILE.p",
  120. "path": "bar.FILE.p",
  121. },
  122. )
  123. assert dn.path == "bar.FILE.p"
  124. def test_set_path(self):
  125. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.p"})
  126. assert dn.path == "foo.p"
  127. dn.path = "bar.p"
  128. assert dn.path == "bar.p"
  129. def test_is_generated(self):
  130. dn = PickleDataNode("foo", Scope.SCENARIO, properties={})
  131. assert dn.is_generated
  132. dn.path = "bar.p"
  133. assert not dn.is_generated
  134. def test_read_write_after_modify_path(self):
  135. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  136. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.p")
  137. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  138. read_data = dn.read()
  139. assert read_data is not None
  140. dn.path = new_path
  141. with pytest.raises(FileNotFoundError):
  142. dn.read()
  143. dn.write({"other": "stuff"})
  144. assert dn.read() == {"other": "stuff"}
  145. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  146. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.pickle"))
  147. pd.DataFrame([]).to_pickle(temp_file_path)
  148. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  149. dn.write(pd.DataFrame([1, 2, 3]))
  150. previous_edit_date = dn.last_edit_date
  151. sleep(0.1)
  152. pd.DataFrame([4, 5, 6]).to_pickle(temp_file_path)
  153. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  154. assert previous_edit_date < dn.last_edit_date
  155. assert new_edit_date == dn.last_edit_date
  156. sleep(0.1)
  157. dn.write(pd.DataFrame([7, 8, 9]))
  158. assert new_edit_date < dn.last_edit_date
  159. os.unlink(temp_file_path)
  160. def test_migrate_to_new_path(self, tmp_path):
  161. _base_path = os.path.join(tmp_path, ".data")
  162. path = os.path.join(_base_path, "test.p")
  163. # create a file on old path
  164. os.mkdir(_base_path)
  165. with open(path, "w"):
  166. pass
  167. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar", "path": path})
  168. assert ".data" not in dn.path
  169. assert os.path.exists(dn.path)