test_parquet_data_node.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 pandas as pd
  18. import pytest
  19. from taipy.config.common.scope import Scope
  20. from taipy.config.config import Config
  21. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  22. from taipy.core.data._data_manager import _DataManager
  23. from taipy.core.data.data_node_id import DataNodeId
  24. from taipy.core.data.parquet import ParquetDataNode
  25. from taipy.core.exceptions.exceptions import (
  26. InvalidExposedType,
  27. UnknownCompressionAlgorithm,
  28. UnknownParquetEngine,
  29. )
  30. @pytest.fixture(scope="function", autouse=True)
  31. def cleanup():
  32. yield
  33. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.parquet")
  34. if os.path.isfile(path):
  35. os.remove(path)
  36. class MyCustomObject:
  37. def __init__(self, id, integer, text):
  38. self.id = id
  39. self.integer = integer
  40. self.text = text
  41. class MyOtherCustomObject:
  42. def __init__(self, id, sentence):
  43. self.id = id
  44. self.sentence = sentence
  45. def create_custom_class(**kwargs):
  46. return MyOtherCustomObject(id=kwargs["id"], sentence=kwargs["text"])
  47. class TestParquetDataNode:
  48. __engine = ["pyarrow"]
  49. if util.find_spec("fastparquet"):
  50. __engine.append("fastparquet")
  51. def test_create(self):
  52. path = "data/node/path"
  53. compression = "snappy"
  54. dn = ParquetDataNode(
  55. "foo_bar", Scope.SCENARIO, properties={"path": path, "compression": compression, "name": "super name"}
  56. )
  57. assert isinstance(dn, ParquetDataNode)
  58. assert dn.storage_type() == "parquet"
  59. assert dn.config_id == "foo_bar"
  60. assert dn.name == "super name"
  61. assert dn.scope == Scope.SCENARIO
  62. assert dn.id is not None
  63. assert dn.owner_id is None
  64. assert dn.last_edit_date is None
  65. assert dn.job_ids == []
  66. assert not dn.is_ready_for_reading
  67. assert dn.path == path
  68. assert dn.exposed_type == "pandas"
  69. assert dn.compression == "snappy"
  70. assert dn.engine == "pyarrow"
  71. with pytest.raises(InvalidConfigurationId):
  72. dn = ParquetDataNode("foo bar", Scope.SCENARIO, properties={"path": path, "name": "super name"})
  73. def test_get_user_properties(self, parquet_file_path):
  74. dn_1 = ParquetDataNode("dn_1", Scope.SCENARIO, properties={"path": parquet_file_path})
  75. assert dn_1._get_user_properties() == {}
  76. dn_2 = ParquetDataNode(
  77. "dn_2",
  78. Scope.SCENARIO,
  79. properties={
  80. "exposed_type": "numpy",
  81. "default_data": "foo",
  82. "default_path": parquet_file_path,
  83. "engine": "pyarrow",
  84. "compression": "snappy",
  85. "read_kwargs": {"columns": ["a", "b"]},
  86. "write_kwargs": {"index": False},
  87. "foo": "bar",
  88. },
  89. )
  90. # exposed_type, default_data, default_path, path, engine, compression, read_kwargs, write_kwargs
  91. # are filtered out
  92. assert dn_2._get_user_properties() == {"foo": "bar"}
  93. def test_new_parquet_data_node_with_existing_file_is_ready_for_reading(self, parquet_file_path):
  94. not_ready_dn_cfg = Config.configure_data_node(
  95. "not_ready_data_node_config_id", "parquet", path="NOT_EXISTING.parquet"
  96. )
  97. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  98. assert not not_ready_dn.is_ready_for_reading
  99. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "parquet", path=parquet_file_path)
  100. ready_dn = _DataManager._bulk_get_or_create([ready_dn_cfg])[ready_dn_cfg]
  101. assert ready_dn.is_ready_for_reading
  102. @pytest.mark.parametrize(
  103. ["properties", "exists"],
  104. [
  105. ({}, False),
  106. ({"default_data": {"a": ["foo", "bar"]}}, True),
  107. ],
  108. )
  109. def test_create_with_default_data(self, properties, exists):
  110. dn = ParquetDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  111. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "parquets", dn.id + ".parquet")
  112. assert os.path.exists(dn.path) is exists
  113. @pytest.mark.parametrize("engine", __engine)
  114. def test_modin_deprecated_in_favor_of_pandas(self, engine, parquet_file_path):
  115. # Create ParquetDataNode with modin exposed_type
  116. props = {"path": parquet_file_path, "exposed_type": "modin", "engine": engine}
  117. parquet_data_node_as_modin = ParquetDataNode("bar", Scope.SCENARIO, properties=props)
  118. assert parquet_data_node_as_modin.properties["exposed_type"] == "pandas"
  119. data_modin = parquet_data_node_as_modin.read()
  120. assert isinstance(data_modin, pd.DataFrame)
  121. def test_set_path(self):
  122. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": "foo.parquet"})
  123. assert dn.path == "foo.parquet"
  124. dn.path = "bar.parquet"
  125. assert dn.path == "bar.parquet"
  126. def test_raise_error_unknown_parquet_engine(self):
  127. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  128. with pytest.raises(UnknownParquetEngine):
  129. ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "engine": "foo"})
  130. def test_raise_error_unknown_compression_algorithm(self):
  131. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  132. with pytest.raises(UnknownCompressionAlgorithm):
  133. ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "compression": "foo"})
  134. def test_raise_error_invalid_exposed_type(self):
  135. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.parquet")
  136. with pytest.raises(InvalidExposedType):
  137. ParquetDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "foo"})
  138. def test_get_system_file_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  139. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.parquet"))
  140. pd.DataFrame([]).to_parquet(temp_file_path)
  141. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  142. dn.write(pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}))
  143. previous_edit_date = dn.last_edit_date
  144. sleep(0.1)
  145. pd.DataFrame(pd.DataFrame(data={"col1": [5, 6], "col2": [7, 8]})).to_parquet(temp_file_path)
  146. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  147. assert previous_edit_date < dn.last_edit_date
  148. assert new_edit_date == dn.last_edit_date
  149. sleep(0.1)
  150. dn.write(pd.DataFrame(data={"col1": [9, 10], "col2": [10, 12]}))
  151. assert new_edit_date < dn.last_edit_date
  152. os.unlink(temp_file_path)
  153. def test_get_system_folder_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  154. temp_folder_path = tmpdir_factory.mktemp("data").strpath
  155. temp_file_path = os.path.join(temp_folder_path, "temp.parquet")
  156. pd.DataFrame([]).to_parquet(temp_file_path)
  157. dn = ParquetDataNode("foo", Scope.SCENARIO, properties={"path": temp_folder_path})
  158. initial_edit_date = dn.last_edit_date
  159. # Sleep so that the file can be created successfully on Ubuntu
  160. sleep(0.1)
  161. pd.DataFrame(pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})).to_parquet(temp_file_path)
  162. first_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  163. assert dn.last_edit_date > initial_edit_date
  164. assert dn.last_edit_date == first_edit_date
  165. sleep(0.1)
  166. pd.DataFrame(pd.DataFrame(data={"col1": [5, 6], "col2": [7, 8]})).to_parquet(temp_file_path)
  167. second_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  168. assert dn.last_edit_date > first_edit_date
  169. assert dn.last_edit_date == second_edit_date
  170. os.unlink(temp_file_path)
  171. def test_migrate_to_new_path(self, tmp_path):
  172. _base_path = os.path.join(tmp_path, ".data")
  173. path = os.path.join(_base_path, "test.parquet")
  174. # create a file on old path
  175. os.mkdir(_base_path)
  176. with open(path, "w"):
  177. pass
  178. dn = ParquetDataNode("foo_bar", Scope.SCENARIO, properties={"path": path, "name": "super name"})
  179. assert ".data" not in dn.path
  180. assert os.path.exists(dn.path)