test_csv_data_node.py 6.9 KB

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