test_parquet_data_node.py 8.8 KB

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