test_csv_data_node.py 6.6 KB

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