test_pickle_data_node.py 11 KB

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