test_pickle_data_node.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # Copyright 2021-2025 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. import re
  15. from datetime import datetime, timedelta
  16. from time import sleep
  17. import freezegun
  18. import pandas as pd
  19. import pytest
  20. from pandas.testing import assert_frame_equal
  21. from taipy import Scope
  22. from taipy.common.config import Config
  23. from taipy.common.config.exceptions.exceptions import InvalidConfigurationId
  24. from taipy.core.common._utils import _normalize_path
  25. from taipy.core.data._data_manager import _DataManager
  26. from taipy.core.data._data_manager_factory import _DataManagerFactory
  27. from taipy.core.data.pickle import PickleDataNode
  28. from taipy.core.exceptions.exceptions import NoData
  29. from taipy.core.reason import NoFileToDownload, NotAFile
  30. @pytest.fixture(scope="function", autouse=True)
  31. def cleanup():
  32. yield
  33. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.p")
  34. if os.path.isfile(path):
  35. os.remove(path)
  36. class TestPickleDataNodeEntity:
  37. @pytest.fixture(scope="function", autouse=True)
  38. def remove_pickle_files(self):
  39. yield
  40. import glob
  41. for f in glob.glob("*.p"):
  42. os.remove(f)
  43. def test_create_with_manager(self, pickle_file_path):
  44. parquet_dn_config = Config.configure_pickle_data_node(id="baz", default_path=pickle_file_path)
  45. parquet_dn = _DataManagerFactory._build_manager()._create(parquet_dn_config, None, None)
  46. assert isinstance(parquet_dn, PickleDataNode)
  47. def test_create(self):
  48. pickle_dn_config = Config.configure_pickle_data_node(
  49. id="foobar_bazxyxea", default_path="Data", default_data="Data"
  50. )
  51. dn = _DataManagerFactory._build_manager()._create(pickle_dn_config, None, None)
  52. assert isinstance(dn, PickleDataNode)
  53. assert dn.storage_type() == "pickle"
  54. assert dn.config_id == "foobar_bazxyxea"
  55. assert dn.scope == Scope.SCENARIO
  56. assert dn.id is not None
  57. assert dn.name is None
  58. assert dn.owner_id is None
  59. assert dn.last_edit_date is not None
  60. assert dn.job_ids == []
  61. assert dn.is_ready_for_reading
  62. assert dn.read() == "Data"
  63. assert dn.last_edit_date is not None
  64. assert dn.job_ids == []
  65. with pytest.raises(InvalidConfigurationId):
  66. PickleDataNode("foobar bazxyxea", Scope.SCENARIO, properties={"default_data": "Data"})
  67. def test_get_user_properties(self, pickle_file_path):
  68. dn_1 = PickleDataNode("dn_1", Scope.SCENARIO, properties={"path": pickle_file_path})
  69. assert dn_1._get_user_properties() == {}
  70. dn_2 = PickleDataNode(
  71. "dn_2",
  72. Scope.SCENARIO,
  73. properties={
  74. "default_data": "foo",
  75. "default_path": pickle_file_path,
  76. "foo": "bar",
  77. },
  78. )
  79. # default_data, default_path, path, is_generated are filtered out
  80. assert dn_2._get_user_properties() == {"foo": "bar"}
  81. def test_new_pickle_data_node_with_existing_file_is_ready_for_reading(self):
  82. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "pickle", path="NOT_EXISTING.p")
  83. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  84. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "pickle", path=path)
  85. dns = _DataManager._bulk_get_or_create([not_ready_dn_cfg, ready_dn_cfg])
  86. assert not dns[not_ready_dn_cfg].is_ready_for_reading
  87. assert dns[ready_dn_cfg].is_ready_for_reading
  88. def test_create_with_file_name(self):
  89. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar", "path": "foo.FILE.p"})
  90. _DataManagerFactory._build_manager()._repository._save(dn)
  91. assert os.path.isfile("foo.FILE.p")
  92. assert dn.read() == "bar"
  93. dn.write("qux")
  94. assert dn.read() == "qux"
  95. dn.write(1998)
  96. assert dn.read() == 1998
  97. def test_read_and_write(self):
  98. no_data_dn = PickleDataNode("foo", Scope.SCENARIO)
  99. _DataManagerFactory._build_manager()._repository._save(no_data_dn)
  100. with pytest.raises(NoData):
  101. assert no_data_dn.read() is None
  102. no_data_dn.read_or_raise()
  103. pickle_str = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar"})
  104. _DataManagerFactory._build_manager()._repository._save(pickle_str)
  105. assert isinstance(pickle_str.read(), str)
  106. assert pickle_str.read() == "bar"
  107. pickle_str.properties["default_data"] = "baz" # this modifies the default data value but not the data itself
  108. assert pickle_str.read() == "bar"
  109. pickle_str.write("qux")
  110. assert pickle_str.read() == "qux"
  111. pickle_str.write(1998)
  112. assert pickle_str.read() == 1998
  113. assert isinstance(pickle_str.read(), int)
  114. pickle_int = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": 197})
  115. assert isinstance(pickle_int.read(), int)
  116. assert pickle_int.read() == 197
  117. pickle_dict = PickleDataNode(
  118. "foo", Scope.SCENARIO, properties={"default_data": {"bar": 12, "baz": "qux", "quux": [13]}}
  119. )
  120. assert isinstance(pickle_dict.read(), dict)
  121. assert pickle_dict.read() == {"bar": 12, "baz": "qux", "quux": [13]}
  122. def test_path_overrides_default_path(self):
  123. dn = PickleDataNode(
  124. "foo",
  125. Scope.SCENARIO,
  126. properties={
  127. "default_data": "bar",
  128. "default_path": "foo.FILE.p",
  129. "path": "bar.FILE.p",
  130. },
  131. )
  132. _DataManagerFactory._build_manager()._repository._save(dn)
  133. assert dn.path == "bar.FILE.p"
  134. def test_set_path(self):
  135. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.p"})
  136. _DataManagerFactory._build_manager()._repository._save(dn)
  137. assert dn.path == "foo.p"
  138. dn.path = "bar.p"
  139. assert dn.path == "bar.p"
  140. def test_is_generated(self):
  141. dn = PickleDataNode("foo", Scope.SCENARIO, properties={})
  142. _DataManagerFactory._build_manager()._repository._save(dn)
  143. assert dn.is_generated
  144. dn.path = "bar.p"
  145. assert not dn.is_generated
  146. def test_read_write_after_modify_path(self):
  147. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  148. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.p")
  149. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  150. _DataManagerFactory._build_manager()._repository._save(dn)
  151. read_data = dn.read()
  152. assert read_data is not None
  153. dn.path = new_path
  154. with pytest.raises(FileNotFoundError):
  155. dn.read()
  156. dn.write({"other": "stuff"})
  157. assert dn.read() == {"other": "stuff"}
  158. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  159. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.pickle"))
  160. pd.DataFrame([]).to_pickle(temp_file_path)
  161. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  162. _DataManagerFactory._build_manager()._repository._save(dn)
  163. dn.write(pd.DataFrame([1, 2, 3]))
  164. previous_edit_date = dn.last_edit_date
  165. sleep(0.1)
  166. pd.DataFrame([4, 5, 6]).to_pickle(temp_file_path)
  167. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  168. assert previous_edit_date < dn.last_edit_date
  169. assert new_edit_date == dn.last_edit_date
  170. sleep(0.1)
  171. dn.write(pd.DataFrame([7, 8, 9]))
  172. assert new_edit_date < dn.last_edit_date
  173. os.unlink(temp_file_path)
  174. def test_migrate_to_new_path(self, tmp_path):
  175. _base_path = os.path.join(tmp_path, ".data")
  176. path = os.path.join(_base_path, "test.p")
  177. # create a file on old path
  178. os.mkdir(_base_path)
  179. with open(path, "w"):
  180. pass
  181. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"default_data": "bar", "path": path})
  182. assert ".data" not in dn.path
  183. assert os.path.exists(dn.path)
  184. def test_is_downloadable(self):
  185. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  186. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": path})
  187. reasons = dn.is_downloadable()
  188. assert reasons
  189. assert reasons.reasons == ""
  190. def test_is_not_downloadable_no_file(self):
  191. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/wrong_path.p")
  192. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": path})
  193. reasons = dn.is_downloadable()
  194. assert not reasons
  195. assert not reasons
  196. assert len(reasons._reasons) == 1
  197. assert str(NoFileToDownload(_normalize_path(path), dn.id)) in reasons.reasons
  198. def test_is_not_downloadable_not_a_file(self):
  199. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample")
  200. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": path})
  201. reasons = dn.is_downloadable()
  202. assert not reasons
  203. assert len(reasons._reasons) == 1
  204. assert str(NotAFile(_normalize_path(path), dn.id)) in reasons.reasons
  205. def test_get_download_path(self):
  206. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.p")
  207. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": path})
  208. assert re.split(r"[\\/]", dn._get_downloadable_path()) == re.split(r"[\\/]", path)
  209. def test_get_download_path_with_not_existed_file(self):
  210. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTED.p"})
  211. assert dn._get_downloadable_path() == ""
  212. def test_upload(self, pickle_file_path, tmpdir_factory):
  213. old_pickle_path = tmpdir_factory.mktemp("data").join("df.p").strpath
  214. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  215. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": old_pickle_path})
  216. _DataManagerFactory._build_manager()._repository._save(dn)
  217. dn.write(old_data)
  218. old_last_edit_date = dn.last_edit_date
  219. upload_content = pd.read_pickle(pickle_file_path)
  220. with freezegun.freeze_time(old_last_edit_date + timedelta(seconds=1)):
  221. dn._upload(pickle_file_path)
  222. assert_frame_equal(dn.read(), upload_content) # The content of the dn should change to the uploaded content
  223. assert dn.last_edit_date > old_last_edit_date
  224. assert dn.path == _normalize_path(old_pickle_path) # The path of the dn should not change
  225. def test_upload_with_upload_check(self, pickle_file_path, tmpdir_factory):
  226. old_pickle_path = tmpdir_factory.mktemp("data").join("df.p").strpath
  227. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  228. dn = PickleDataNode("foo", Scope.SCENARIO, properties={"path": old_pickle_path})
  229. _DataManagerFactory._build_manager()._repository._save(dn)
  230. dn.write(old_data)
  231. old_last_edit_date = dn.last_edit_date
  232. def check_data_column(upload_path, upload_data):
  233. return upload_path.endswith(".p") and upload_data.columns.tolist() == ["a", "b", "c"]
  234. not_exists_json_path = tmpdir_factory.mktemp("data").join("not_exists.json").strpath
  235. reasons = dn._upload(not_exists_json_path, upload_checker=check_data_column)
  236. assert bool(reasons) is False
  237. assert (
  238. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file 'not_exists.json' can not be read,"
  239. f" therefore is not a valid data file for data node '{dn.id}'"
  240. )
  241. not_pickle_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_pickle").strpath
  242. with open(str(not_pickle_path), "wb") as f:
  243. pickle.dump(pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]), f)
  244. # The upload should fail when the file is not a pickle
  245. reasons = dn._upload(not_pickle_path, upload_checker=check_data_column)
  246. assert bool(reasons) is False
  247. assert (
  248. str(list(reasons._reasons[dn.id])[0])
  249. == f"The uploaded file 'wrong_format_df.not_pickle' has invalid data for data node '{dn.id}'"
  250. )
  251. wrong_format_pickle_path = tmpdir_factory.mktemp("data").join("wrong_format_df.p").strpath
  252. with open(str(wrong_format_pickle_path), "wb") as f:
  253. pickle.dump(pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]), f)
  254. # The upload should fail when check_data_column() return False
  255. reasons = dn._upload(wrong_format_pickle_path, upload_checker=check_data_column)
  256. assert bool(reasons) is False
  257. assert (
  258. str(list(reasons._reasons[dn.id])[0])
  259. == f"The uploaded file 'wrong_format_df.p' has invalid data for data node '{dn.id}'"
  260. )
  261. assert_frame_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  262. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  263. assert dn.path == _normalize_path(old_pickle_path) # The path of the dn should not change
  264. # The upload should succeed when check_data_column() return True
  265. assert dn._upload(pickle_file_path, upload_checker=check_data_column)