test_parquet_data_node.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 uuid
  14. from datetime import datetime, timedelta
  15. from importlib import util
  16. from time import sleep
  17. import freezegun
  18. import numpy as np
  19. import pandas as pd
  20. import pytest
  21. from pandas.testing import assert_frame_equal
  22. from taipy.config.common.scope import Scope
  23. from taipy.config.config import Config
  24. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  25. from taipy.core.data._data_manager import _DataManager
  26. from taipy.core.data._data_manager_factory import _DataManagerFactory
  27. from taipy.core.data.data_node_id import DataNodeId
  28. from taipy.core.data.parquet import ParquetDataNode
  29. from taipy.core.exceptions.exceptions import (
  30. InvalidExposedType,
  31. UnknownCompressionAlgorithm,
  32. UnknownParquetEngine,
  33. )
  34. from taipy.core.reason import NoFileToDownload, NotAFile
  35. @pytest.fixture(scope="function", autouse=True)
  36. def cleanup():
  37. yield
  38. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.parquet")
  39. if os.path.isfile(path):
  40. os.remove(path)
  41. class MyCustomObject:
  42. def __init__(self, id, integer, text):
  43. self.id = id
  44. self.integer = integer
  45. self.text = text
  46. class MyOtherCustomObject:
  47. def __init__(self, id, sentence):
  48. self.id = id
  49. self.sentence = sentence
  50. def create_custom_class(**kwargs):
  51. return MyOtherCustomObject(id=kwargs["id"], sentence=kwargs["text"])
  52. class TestParquetDataNode:
  53. __engine = ["pyarrow"]
  54. if util.find_spec("fastparquet"):
  55. __engine.append("fastparquet")
  56. def test_create(self):
  57. path = "data/node/path"
  58. compression = "snappy"
  59. parquet_dn_config = Config.configure_parquet_data_node(
  60. id="foo_bar", default_path=path, compression=compression, name="super name"
  61. )
  62. dn = _DataManagerFactory._build_manager()._create_and_set(parquet_dn_config, None, None)
  63. assert isinstance(dn, ParquetDataNode)
  64. assert dn.storage_type() == "parquet"
  65. assert dn.config_id == "foo_bar"
  66. assert dn.name == "super name"
  67. assert dn.scope == Scope.SCENARIO
  68. assert dn.id is not None
  69. assert dn.owner_id is None
  70. assert dn.last_edit_date is None
  71. assert dn.job_ids == []
  72. assert not dn.is_ready_for_reading
  73. assert dn.path == path
  74. assert dn.properties["exposed_type"] == "pandas"
  75. assert dn.properties["compression"] == "snappy"
  76. assert dn.properties["engine"] == "pyarrow"
  77. parquet_dn_config_1 = Config.configure_parquet_data_node(
  78. id="bar", default_path=path, compression=compression, exposed_type=MyCustomObject
  79. )
  80. dn_1 = _DataManagerFactory._build_manager()._create_and_set(parquet_dn_config_1, None, None)
  81. assert isinstance(dn_1, ParquetDataNode)
  82. assert dn_1.properties["exposed_type"] == MyCustomObject
  83. with pytest.raises(InvalidConfigurationId):
  84. dn = ParquetDataNode("foo bar", Scope.SCENARIO, properties={"path": path, "name": "super name"})
  85. def test_get_user_properties(self, parquet_file_path):
  86. dn_1 = ParquetDataNode("dn_1", Scope.SCENARIO, properties={"path": parquet_file_path})
  87. assert dn_1._get_user_properties() == {}
  88. dn_2 = ParquetDataNode(
  89. "dn_2",
  90. Scope.SCENARIO,
  91. properties={
  92. "exposed_type": "numpy",
  93. "default_data": "foo",
  94. "default_path": parquet_file_path,
  95. "engine": "pyarrow",
  96. "compression": "snappy",
  97. "read_kwargs": {"columns": ["a", "b"]},
  98. "write_kwargs": {"index": False},
  99. "foo": "bar",
  100. },
  101. )
  102. # exposed_type, default_data, default_path, path, engine, compression, read_kwargs, write_kwargs
  103. # are filtered out
  104. assert dn_2._get_user_properties() == {"foo": "bar"}
  105. def test_new_parquet_data_node_with_existing_file_is_ready_for_reading(self, parquet_file_path):
  106. not_ready_dn_cfg = Config.configure_data_node(
  107. "not_ready_data_node_config_id", "parquet", path="NOT_EXISTING.parquet"
  108. )
  109. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  110. assert not not_ready_dn.is_ready_for_reading
  111. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "parquet", path=parquet_file_path)
  112. ready_dn = _DataManager._bulk_get_or_create([ready_dn_cfg])[ready_dn_cfg]
  113. assert ready_dn.is_ready_for_reading
  114. @pytest.mark.parametrize(
  115. ["properties", "exists"],
  116. [
  117. ({}, False),
  118. ({"default_data": {"a": ["foo", "bar"]}}, True),
  119. ],
  120. )
  121. def test_create_with_default_data(self, properties, exists):
  122. dn = ParquetDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  123. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "parquets", dn.id + ".parquet")
  124. assert os.path.exists(dn.path) is exists
  125. @pytest.mark.parametrize("engine", __engine)
  126. def test_modin_deprecated_in_favor_of_pandas(self, engine, parquet_file_path):
  127. # Create ParquetDataNode with modin exposed_type
  128. props = {"path": parquet_file_path, "exposed_type": "modin", "engine": engine}
  129. parquet_data_node_as_modin = ParquetDataNode("bar", Scope.SCENARIO, properties=props)
  130. assert parquet_data_node_as_modin.properties["exposed_type"] == "pandas"
  131. data_modin = parquet_data_node_as_modin.read()
  132. assert isinstance(data_modin, pd.DataFrame)
  133. def test_set_path(self):
  134. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": "foo.parquet"})
  135. assert dn.path == "foo.parquet"
  136. dn.path = "bar.parquet"
  137. assert dn.path == "bar.parquet"
  138. def test_raise_error_unknown_parquet_engine(self):
  139. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  140. with pytest.raises(UnknownParquetEngine):
  141. ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "engine": "foo"})
  142. def test_raise_error_unknown_compression_algorithm(self):
  143. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  144. with pytest.raises(UnknownCompressionAlgorithm):
  145. ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "compression": "foo"})
  146. def test_raise_error_invalid_exposed_type(self):
  147. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  148. with pytest.raises(InvalidExposedType):
  149. ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "foo"})
  150. def test_get_system_file_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  151. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.parquet"))
  152. pd.DataFrame([]).to_parquet(temp_file_path)
  153. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  154. dn.write(pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}))
  155. previous_edit_date = dn.last_edit_date
  156. sleep(0.1)
  157. pd.DataFrame(pd.DataFrame(data={"col1": [5, 6], "col2": [7, 8]})).to_parquet(temp_file_path)
  158. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  159. assert previous_edit_date < dn.last_edit_date
  160. assert new_edit_date == dn.last_edit_date
  161. sleep(0.1)
  162. dn.write(pd.DataFrame(data={"col1": [9, 10], "col2": [10, 12]}))
  163. assert new_edit_date < dn.last_edit_date
  164. os.unlink(temp_file_path)
  165. def test_get_system_folder_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  166. temp_folder_path = tmpdir_factory.mktemp("data").strpath
  167. temp_file_path = os.path.join(temp_folder_path, "temp.parquet")
  168. pd.DataFrame([]).to_parquet(temp_file_path)
  169. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": temp_folder_path})
  170. initial_edit_date = dn.last_edit_date
  171. # Sleep so that the file can be created successfully on Ubuntu
  172. sleep(0.1)
  173. pd.DataFrame(pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})).to_parquet(temp_file_path)
  174. first_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  175. assert dn.last_edit_date > initial_edit_date
  176. assert dn.last_edit_date == first_edit_date
  177. sleep(0.1)
  178. pd.DataFrame(pd.DataFrame(data={"col1": [5, 6], "col2": [7, 8]})).to_parquet(temp_file_path)
  179. second_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  180. assert dn.last_edit_date > first_edit_date
  181. assert dn.last_edit_date == second_edit_date
  182. os.unlink(temp_file_path)
  183. def test_migrate_to_new_path(self, tmp_path):
  184. _base_path = os.path.join(tmp_path, ".data")
  185. path = os.path.join(_base_path, "test.parquet")
  186. # create a file on old path
  187. os.mkdir(_base_path)
  188. with open(path, "w"):
  189. pass
  190. dn = ParquetDataNode("foo_bar", Scope.SCENARIO, properties={"path": path, "name": "super name"})
  191. assert ".data" not in dn.path
  192. assert os.path.exists(dn.path)
  193. def test_is_downloadable(self):
  194. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  195. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  196. reasons = dn.is_downloadable()
  197. assert reasons
  198. assert reasons.reasons == ""
  199. def test_is_not_downloadable_no_file(self):
  200. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/wrong_path.parquet")
  201. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  202. reasons = dn.is_downloadable()
  203. assert not reasons
  204. assert len(reasons._reasons) == 1
  205. assert str(NoFileToDownload(path, dn.id)) in reasons.reasons
  206. def test_is_not_downloadable_not_a_file(self):
  207. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample")
  208. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  209. reasons = dn.is_downloadable()
  210. assert not reasons
  211. assert len(reasons._reasons) == 1
  212. assert str(NotAFile(path, dn.id)) in reasons.reasons
  213. def test_get_downloadable_path(self):
  214. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  215. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  216. assert dn._get_downloadable_path() == path
  217. def test_get_downloadable_path_with_not_existing_file(self):
  218. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTING.parquet"})
  219. assert dn._get_downloadable_path() == ""
  220. def test_get_downloadable_path_as_directory_should_return_nothing(self):
  221. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/parquet_example")
  222. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path})
  223. assert dn._get_downloadable_path() == ""
  224. def test_upload(self, parquet_file_path, tmpdir_factory):
  225. old_parquet_path = tmpdir_factory.mktemp("data").join("df.parquet").strpath
  226. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  227. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": old_parquet_path, "exposed_type": "pandas"})
  228. dn.write(old_data)
  229. old_last_edit_date = dn.last_edit_date
  230. upload_content = pd.read_parquet(parquet_file_path)
  231. with freezegun.freeze_time(old_last_edit_date + timedelta(seconds=1)):
  232. dn._upload(parquet_file_path)
  233. assert_frame_equal(dn.read(), upload_content) # The content of the dn should change to the uploaded content
  234. assert dn.last_edit_date > old_last_edit_date
  235. assert dn.path == old_parquet_path # The path of the dn should not change
  236. def test_upload_with_upload_check_pandas(self, parquet_file_path, tmpdir_factory):
  237. old_parquet_path = tmpdir_factory.mktemp("data").join("df.parquet").strpath
  238. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  239. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": old_parquet_path, "exposed_type": "pandas"})
  240. dn.write(old_data)
  241. old_last_edit_date = dn.last_edit_date
  242. def check_data_column(upload_path, upload_data):
  243. return upload_path.endswith(".parquet") and upload_data.columns.tolist() == ["a", "b", "c"]
  244. not_exists_parquet_path = tmpdir_factory.mktemp("data").join("not_exists.parquet").strpath
  245. reasons = dn._upload(not_exists_parquet_path, upload_checker=check_data_column)
  246. assert bool(reasons) is False
  247. assert (
  248. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.parquet can not be read,"
  249. f' therefore is not a valid data file for data node "{dn.id}"'
  250. )
  251. not_parquet_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_parquet").strpath
  252. old_data.to_parquet(not_parquet_path, index=False)
  253. # The upload should fail when the file is not a parquet
  254. reasons = dn._upload(not_parquet_path, upload_checker=check_data_column)
  255. assert bool(reasons) is False
  256. assert (
  257. str(list(reasons._reasons[dn.id])[0])
  258. == f'The uploaded file wrong_format_df.not_parquet has invalid data for data node "{dn.id}"'
  259. )
  260. wrong_format_parquet_path = tmpdir_factory.mktemp("data").join("wrong_format_df.parquet").strpath
  261. pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]).to_parquet(
  262. wrong_format_parquet_path, index=False
  263. )
  264. # The upload should fail when check_data_column() return False
  265. reasons = dn._upload(wrong_format_parquet_path, upload_checker=check_data_column)
  266. assert bool(reasons) is False
  267. assert (
  268. str(list(reasons._reasons[dn.id])[0])
  269. == f'The uploaded file wrong_format_df.parquet has invalid data for data node "{dn.id}"'
  270. )
  271. assert_frame_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  272. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  273. assert dn.path == old_parquet_path # The path of the dn should not change
  274. # The upload should succeed when check_data_column() return True
  275. assert dn._upload(parquet_file_path, upload_checker=check_data_column)
  276. def test_upload_with_upload_check_numpy(self, tmpdir_factory):
  277. old_parquet_path = tmpdir_factory.mktemp("data").join("df.parquet").strpath
  278. old_data = np.array([[1, 2, 3], [4, 5, 6]])
  279. new_parquet_path = tmpdir_factory.mktemp("data").join("new_upload_data.parquet").strpath
  280. new_data = np.array([[1, 2, 3], [4, 5, 6]])
  281. pd.DataFrame(new_data, columns=["a", "b", "c"]).to_parquet(new_parquet_path, index=False)
  282. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": old_parquet_path, "exposed_type": "numpy"})
  283. dn.write(old_data)
  284. old_last_edit_date = dn.last_edit_date
  285. def check_data_is_positive(upload_path, upload_data):
  286. return upload_path.endswith(".parquet") and np.all(upload_data > 0)
  287. not_exists_parquet_path = tmpdir_factory.mktemp("data").join("not_exists.parquet").strpath
  288. reasons = dn._upload(not_exists_parquet_path, upload_checker=check_data_is_positive)
  289. assert bool(reasons) is False
  290. assert (
  291. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.parquet can not be read,"
  292. f' therefore is not a valid data file for data node "{dn.id}"'
  293. )
  294. not_parquet_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_parquet").strpath
  295. pd.DataFrame(old_data, columns=["a", "b", "c"]).to_parquet(not_parquet_path, index=False)
  296. # The upload should fail when the file is not a parquet
  297. reasons = dn._upload(not_parquet_path, upload_checker=check_data_is_positive)
  298. assert (
  299. str(list(reasons._reasons[dn.id])[0])
  300. == f'The uploaded file wrong_format_df.not_parquet has invalid data for data node "{dn.id}"'
  301. )
  302. wrong_format_parquet_path = tmpdir_factory.mktemp("data").join("wrong_format_df.parquet").strpath
  303. pd.DataFrame(np.array([[-1, 2, 3], [-4, -5, -6]]), columns=["a", "b", "c"]).to_parquet(
  304. wrong_format_parquet_path, index=False
  305. )
  306. # The upload should fail when check_data_is_positive() return False
  307. reasons = dn._upload(wrong_format_parquet_path, upload_checker=check_data_is_positive)
  308. assert (
  309. str(list(reasons._reasons[dn.id])[0])
  310. == f'The uploaded file wrong_format_df.parquet has invalid data for data node "{dn.id}"'
  311. )
  312. np.array_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  313. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  314. assert dn.path == old_parquet_path # The path of the dn should not change
  315. # The upload should succeed when check_data_is_positive() return True
  316. assert dn._upload(new_parquet_path, upload_checker=check_data_is_positive)