test_pickle_data_node.py 12 KB

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