test_pickle_data_node.py 13 KB

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