test_parquet_data_node.py 14 KB

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