test_pickle_data_node.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. import pickle
  14. from datetime import datetime
  15. from time import sleep
  16. import pandas as pd
  17. import pytest
  18. from pandas.testing import assert_frame_equal
  19. from taipy.config.common.scope import Scope
  20. from taipy.config.config import Config
  21. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  22. from taipy.core.data._data_manager import _DataManager
  23. from taipy.core.data.pickle import PickleDataNode
  24. from taipy.core.exceptions.exceptions import NoData
  25. @pytest.fixture(scope="function", autouse=True)
  26. def cleanup():
  27. yield
  28. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.p")
  29. if os.path.isfile(path):
  30. os.remove(path)
  31. class TestPickleDataNodeEntity:
  32. @pytest.fixture(scope="function", autouse=True)
  33. def remove_pickle_files(self):
  34. yield
  35. import glob
  36. for f in glob.glob("*.p"):
  37. os.remove(f)
  38. def test_create(self):
  39. dn = PickleDataNode("foobar_bazxyxea", Scope.SCENARIO, properties={"default_data": "Data"})
  40. assert os.path.isfile(os.path.join(Config.core.storage_folder.strip("/"), "pickles", dn.id + ".p"))
  41. assert isinstance(dn, PickleDataNode)
  42. assert dn.storage_type() == "pickle"
  43. assert dn.config_id == "foobar_bazxyxea"
  44. assert dn.scope == Scope.SCENARIO
  45. assert dn.id is not None
  46. assert dn.name is None
  47. assert dn.owner_id is None
  48. assert dn.last_edit_date is not None
  49. assert dn.job_ids == []
  50. assert dn.is_ready_for_reading
  51. assert dn.read() == "Data"
  52. assert dn.last_edit_date is not None
  53. assert dn.job_ids == []
  54. with pytest.raises(InvalidConfigurationId):
  55. PickleDataNode("foobar bazxyxea", Scope.SCENARIO, properties={"default_data": "Data"})
  56. def test_get_user_properties(self, pickle_file_path):
  57. dn_1 = PickleDataNode("dn_1", Scope.SCENARIO, properties={"path": pickle_file_path})
  58. assert dn_1._get_user_properties() == {}
  59. dn_2 = PickleDataNode(
  60. "dn_2",
  61. Scope.SCENARIO,
  62. properties={
  63. "default_data": "foo",
  64. "default_path": pickle_file_path,
  65. "foo": "bar",
  66. },
  67. )
  68. # default_data, default_path, path, is_generated are filtered out
  69. assert dn_2._get_user_properties() == {"foo": "bar"}
  70. def test_new_pickle_data_node_with_existing_file_is_ready_for_reading(self):
  71. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "pickle", path="NOT_EXISTING.p")
  72. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  73. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "pickle", path=path)
  74. dns = _DataManager._bulk_get_or_create([not_ready_dn_cfg, ready_dn_cfg])
  75. assert not dns[not_ready_dn_cfg].is_ready_for_reading
  76. assert dns[ready_dn_cfg].is_ready_for_reading
  77. def test_create_with_file_name(self):
  78. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar", "path": "foo.FILE.p"})
  79. assert os.path.isfile("foo.FILE.p")
  80. assert dn.read() == "bar"
  81. dn.write("qux")
  82. assert dn.read() == "qux"
  83. dn.write(1998)
  84. assert dn.read() == 1998
  85. def test_read_and_write(self):
  86. no_data_dn = PickleDataNode("foo", Scope.SCENARIO)
  87. with pytest.raises(NoData):
  88. assert no_data_dn.read() is None
  89. no_data_dn.read_or_raise()
  90. pickle_str = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar"})
  91. assert isinstance(pickle_str.read(), str)
  92. assert pickle_str.read() == "bar"
  93. pickle_str.properties["default_data"] = "baz" # this modifies the default data value but not the data itself
  94. assert pickle_str.read() == "bar"
  95. pickle_str.write("qux")
  96. assert pickle_str.read() == "qux"
  97. pickle_str.write(1998)
  98. assert pickle_str.read() == 1998
  99. assert isinstance(pickle_str.read(), int)
  100. pickle_int = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": 197})
  101. assert isinstance(pickle_int.read(), int)
  102. assert pickle_int.read() == 197
  103. pickle_dict = PickleDataNode(
  104. "foo", Scope.SCENARIO, properties={"default_data": {"bar": 12, "baz": "qux", "quux": [13]}}
  105. )
  106. assert isinstance(pickle_dict.read(), dict)
  107. assert pickle_dict.read() == {"bar": 12, "baz": "qux", "quux": [13]}
  108. def test_path_overrides_default_path(self):
  109. dn = PickleDataNode(
  110. "foo",
  111. Scope.SCENARIO,
  112. properties={
  113. "default_data": "bar",
  114. "default_path": "foo.FILE.p",
  115. "path": "bar.FILE.p",
  116. },
  117. )
  118. assert dn.path == "bar.FILE.p"
  119. def test_set_path(self):
  120. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.p"})
  121. assert dn.path == "foo.p"
  122. dn.path = "bar.p"
  123. assert dn.path == "bar.p"
  124. def test_is_generated(self):
  125. dn = PickleDataNode("foo", Scope.SCENARIO, properties={})
  126. assert dn.is_generated
  127. dn.path = "bar.p"
  128. assert not dn.is_generated
  129. def test_read_write_after_modify_path(self):
  130. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  131. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.p")
  132. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  133. read_data = dn.read()
  134. assert read_data is not None
  135. dn.path = new_path
  136. with pytest.raises(FileNotFoundError):
  137. dn.read()
  138. dn.write({"other": "stuff"})
  139. assert dn.read() == {"other": "stuff"}
  140. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  141. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.pickle"))
  142. pd.DataFrame([]).to_pickle(temp_file_path)
  143. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  144. dn.write(pd.DataFrame([1, 2, 3]))
  145. previous_edit_date = dn.last_edit_date
  146. sleep(0.1)
  147. pd.DataFrame([4, 5, 6]).to_pickle(temp_file_path)
  148. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  149. assert previous_edit_date < dn.last_edit_date
  150. assert new_edit_date == dn.last_edit_date
  151. sleep(0.1)
  152. dn.write(pd.DataFrame([7, 8, 9]))
  153. assert new_edit_date < dn.last_edit_date
  154. os.unlink(temp_file_path)
  155. def test_migrate_to_new_path(self, tmp_path):
  156. _base_path = os.path.join(tmp_path, ".data")
  157. path = os.path.join(_base_path, "test.p")
  158. # create a file on old path
  159. os.mkdir(_base_path)
  160. with open(path, "w"):
  161. pass
  162. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar", "path": path})
  163. assert ".data" not in dn.path
  164. assert os.path.exists(dn.path)
  165. def test_get_download_path(self):
  166. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  167. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": path})
  168. assert dn._get_downloadable_path() == path
  169. def test_get_download_path_with_not_existed_file(self):
  170. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTED.p"})
  171. assert dn._get_downloadable_path() == ""
  172. def test_upload(self, pickle_file_path, tmpdir_factory):
  173. old_pickle_path = tmpdir_factory.mktemp("data").join("df.p").strpath
  174. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  175. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": old_pickle_path})
  176. dn.write(old_data)
  177. old_last_edit_date = dn.last_edit_date
  178. upload_content = pd.read_pickle(pickle_file_path)
  179. dn._upload(pickle_file_path)
  180. assert_frame_equal(dn.read(), upload_content) # The content of the dn should change to the uploaded content
  181. assert dn.last_edit_date > old_last_edit_date
  182. assert dn.path == old_pickle_path # The path of the dn should not change
  183. def test_upload_with_upload_check(self, pickle_file_path, tmpdir_factory):
  184. old_pickle_path = tmpdir_factory.mktemp("data").join("df.p").strpath
  185. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  186. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": old_pickle_path})
  187. dn.write(old_data)
  188. old_last_edit_date = dn.last_edit_date
  189. def check_data_column(upload_path, upload_data):
  190. return upload_path.endswith(".p") and upload_data.columns.tolist() == ["a", "b", "c"]
  191. wrong_format_not_pickle_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_pickle").strpath
  192. wrong_format_pickle_path = tmpdir_factory.mktemp("data").join("wrong_format_df.p").strpath
  193. with open(str(wrong_format_pickle_path), "wb") as f:
  194. pickle.dump(pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]), f)
  195. # The upload should fail when the file is not a pickle
  196. assert not dn._upload(wrong_format_not_pickle_path, upload_checker=check_data_column)
  197. # The upload should fail when check_data_column() return False
  198. assert not dn._upload(wrong_format_pickle_path, upload_checker=check_data_column)
  199. assert_frame_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  200. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  201. assert dn.path == old_pickle_path # The path of the dn should not change
  202. # The upload should succeed when check_data_column() return True
  203. assert dn._upload(pickle_file_path, upload_checker=check_data_column)