test_csv_data_node.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 dataclasses
  12. import os
  13. import pathlib
  14. import uuid
  15. from datetime import datetime
  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_manager_factory import _DataManagerFactory
  24. from taipy.core.data.csv import CSVDataNode
  25. from taipy.core.data.data_node_id import DataNodeId
  26. from taipy.core.exceptions.exceptions import InvalidExposedType
  27. @pytest.fixture(scope="function", autouse=True)
  28. def cleanup():
  29. yield
  30. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.csv")
  31. if os.path.isfile(path):
  32. os.remove(path)
  33. @dataclasses.dataclass
  34. class MyCustomObject:
  35. id: int
  36. integer: int
  37. text: str
  38. class TestCSVDataNode:
  39. def test_create(self):
  40. default_path = "data/node/path"
  41. csv_dn_config = Config.configure_csv_data_node(
  42. id="foo_bar", default_path=default_path, has_header=False, name="super name"
  43. )
  44. dn = _DataManagerFactory._build_manager()._create_and_set(csv_dn_config, None, None)
  45. assert isinstance(dn, CSVDataNode)
  46. assert dn.storage_type() == "csv"
  47. assert dn.config_id == "foo_bar"
  48. assert dn.name == "super name"
  49. assert dn.scope == Scope.SCENARIO
  50. assert dn.id is not None
  51. assert dn.owner_id is None
  52. assert dn.last_edit_date is None
  53. assert dn.job_ids == []
  54. assert not dn.is_ready_for_reading
  55. assert dn.path == default_path
  56. assert dn.has_header is False
  57. assert dn.exposed_type == "pandas"
  58. csv_dn_config = Config.configure_csv_data_node(
  59. id="foo", default_path=default_path, has_header=True, exposed_type=MyCustomObject
  60. )
  61. dn = _DataManagerFactory._build_manager()._create_and_set(csv_dn_config, None, None)
  62. assert dn.storage_type() == "csv"
  63. assert dn.config_id == "foo"
  64. assert dn.has_header is True
  65. assert dn.exposed_type == MyCustomObject
  66. with pytest.raises(InvalidConfigurationId):
  67. CSVDataNode(
  68. "foo bar", Scope.SCENARIO, properties={"path": default_path, "has_header": False, "name": "super name"}
  69. )
  70. def test_modin_deprecated_in_favor_of_pandas(self):
  71. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  72. # Create CSVDataNode with modin exposed_type
  73. csv_data_node_as_modin = CSVDataNode("bar", Scope.SCENARIO, properties={"path": path, "exposed_type": "modin"})
  74. assert csv_data_node_as_modin.properties["exposed_type"] == "pandas"
  75. data_modin = csv_data_node_as_modin.read()
  76. assert isinstance(data_modin, pd.DataFrame)
  77. def test_get_user_properties(self, csv_file):
  78. dn_1 = CSVDataNode("dn_1", Scope.SCENARIO, properties={"path": "data/node/path"})
  79. assert dn_1._get_user_properties() == {}
  80. dn_2 = CSVDataNode(
  81. "dn_2",
  82. Scope.SCENARIO,
  83. properties={
  84. "exposed_type": "numpy",
  85. "default_data": "foo",
  86. "default_path": csv_file,
  87. "has_header": False,
  88. "foo": "bar",
  89. },
  90. )
  91. # exposed_type, default_data, default_path, path, has_header, sheet_name are filtered out
  92. assert dn_2._get_user_properties() == {"foo": "bar"}
  93. def test_new_csv_data_node_with_existing_file_is_ready_for_reading(self):
  94. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "csv", path="NOT_EXISTING.csv")
  95. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  96. assert not not_ready_dn.is_ready_for_reading
  97. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  98. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "csv", path=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": ["foo", "bar"]}, True),
  106. ],
  107. )
  108. def test_create_with_default_data(self, properties, exists):
  109. dn = CSVDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  110. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "csvs", dn.id + ".csv")
  111. assert os.path.exists(dn.path) is exists
  112. def test_set_path(self):
  113. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.csv"})
  114. assert dn.path == "foo.csv"
  115. dn.path = "bar.csv"
  116. assert dn.path == "bar.csv"
  117. def test_read_write_after_modify_path(self):
  118. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  119. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.csv")
  120. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  121. read_data = dn.read()
  122. assert read_data is not None
  123. dn.path = new_path
  124. with pytest.raises(FileNotFoundError):
  125. dn.read()
  126. dn.write(read_data)
  127. assert dn.read().equals(read_data)
  128. def test_pandas_exposed_type(self):
  129. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  130. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  131. assert isinstance(dn.read(), pd.DataFrame)
  132. def test_raise_error_invalid_exposed_type(self):
  133. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  134. with pytest.raises(InvalidExposedType):
  135. CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "foo"})
  136. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  137. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.csv"))
  138. pd.DataFrame([]).to_csv(temp_file_path)
  139. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  140. dn.write(pd.DataFrame([1, 2, 3]))
  141. previous_edit_date = dn.last_edit_date
  142. sleep(0.1)
  143. pd.DataFrame([4, 5, 6]).to_csv(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([7, 8, 9]))
  149. assert new_edit_date < dn.last_edit_date
  150. os.unlink(temp_file_path)
  151. def test_migrate_to_new_path(self, tmp_path):
  152. _base_path = os.path.join(tmp_path, ".data")
  153. path = os.path.join(_base_path, "test.csv")
  154. # create a file on old path
  155. os.mkdir(_base_path)
  156. with open(path, "w"):
  157. pass
  158. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  159. assert ".data" not in dn.path
  160. assert os.path.exists(dn.path)