test_csv_data_node.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 time import sleep
  16. import numpy as np
  17. import pandas as pd
  18. import pytest
  19. from pandas.testing import assert_frame_equal
  20. from taipy.config.common.scope import Scope
  21. from taipy.config.config import Config
  22. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  23. from taipy.core.data._data_manager import _DataManager
  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. class TestCSVDataNode:
  34. def test_create(self):
  35. path = "data/node/path"
  36. dn = CSVDataNode(
  37. "foo_bar", Scope.SCENARIO, properties={"path": path, "has_header": False, "name": "super name"}
  38. )
  39. assert isinstance(dn, CSVDataNode)
  40. assert dn.storage_type() == "csv"
  41. assert dn.config_id == "foo_bar"
  42. assert dn.name == "super name"
  43. assert dn.scope == Scope.SCENARIO
  44. assert dn.id is not None
  45. assert dn.owner_id is None
  46. assert dn.last_edit_date is None
  47. assert dn.job_ids == []
  48. assert not dn.is_ready_for_reading
  49. assert dn.path == path
  50. assert dn.has_header is False
  51. assert dn.exposed_type == "pandas"
  52. with pytest.raises(InvalidConfigurationId):
  53. CSVDataNode("foo bar", Scope.SCENARIO, properties={"path": path, "has_header": False, "name": "super name"})
  54. def test_modin_deprecated_in_favor_of_pandas(self):
  55. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  56. # Create CSVDataNode with modin exposed_type
  57. csv_data_node_as_modin = CSVDataNode("bar", Scope.SCENARIO, properties={"path": path, "exposed_type": "modin"})
  58. assert csv_data_node_as_modin.properties["exposed_type"] == "pandas"
  59. data_modin = csv_data_node_as_modin.read()
  60. assert isinstance(data_modin, pd.DataFrame)
  61. def test_get_user_properties(self, csv_file):
  62. dn_1 = CSVDataNode("dn_1", Scope.SCENARIO, properties={"path": "data/node/path"})
  63. assert dn_1._get_user_properties() == {}
  64. dn_2 = CSVDataNode(
  65. "dn_2",
  66. Scope.SCENARIO,
  67. properties={
  68. "exposed_type": "numpy",
  69. "default_data": "foo",
  70. "default_path": csv_file,
  71. "has_header": False,
  72. "foo": "bar",
  73. },
  74. )
  75. # exposed_type, default_data, default_path, path, has_header, sheet_name are filtered out
  76. assert dn_2._get_user_properties() == {"foo": "bar"}
  77. def test_new_csv_data_node_with_existing_file_is_ready_for_reading(self):
  78. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "csv", path="NOT_EXISTING.csv")
  79. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  80. assert not not_ready_dn.is_ready_for_reading
  81. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  82. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "csv", path=path)
  83. ready_dn = _DataManager._bulk_get_or_create([ready_dn_cfg])[ready_dn_cfg]
  84. assert ready_dn.is_ready_for_reading
  85. @pytest.mark.parametrize(
  86. ["properties", "exists"],
  87. [
  88. ({}, False),
  89. ({"default_data": ["foo", "bar"]}, True),
  90. ],
  91. )
  92. def test_create_with_default_data(self, properties, exists):
  93. dn = CSVDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  94. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "csvs", dn.id + ".csv")
  95. assert os.path.exists(dn.path) is exists
  96. def test_set_path(self):
  97. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.csv"})
  98. assert dn.path == "foo.csv"
  99. dn.path = "bar.csv"
  100. assert dn.path == "bar.csv"
  101. def test_read_write_after_modify_path(self):
  102. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  103. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.csv")
  104. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  105. read_data = dn.read()
  106. assert read_data is not None
  107. dn.path = new_path
  108. with pytest.raises(FileNotFoundError):
  109. dn.read()
  110. dn.write(read_data)
  111. assert dn.read().equals(read_data)
  112. def test_pandas_exposed_type(self):
  113. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  114. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  115. assert isinstance(dn.read(), pd.DataFrame)
  116. def test_raise_error_invalid_exposed_type(self):
  117. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  118. with pytest.raises(InvalidExposedType):
  119. CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "foo"})
  120. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  121. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.csv"))
  122. pd.DataFrame([]).to_csv(temp_file_path)
  123. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  124. dn.write(pd.DataFrame([1, 2, 3]))
  125. previous_edit_date = dn.last_edit_date
  126. sleep(0.1)
  127. pd.DataFrame([4, 5, 6]).to_csv(temp_file_path)
  128. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  129. assert previous_edit_date < dn.last_edit_date
  130. assert new_edit_date == dn.last_edit_date
  131. sleep(0.1)
  132. dn.write(pd.DataFrame([7, 8, 9]))
  133. assert new_edit_date < dn.last_edit_date
  134. os.unlink(temp_file_path)
  135. def test_migrate_to_new_path(self, tmp_path):
  136. _base_path = os.path.join(tmp_path, ".data")
  137. path = os.path.join(_base_path, "test.csv")
  138. # create a file on old path
  139. os.mkdir(_base_path)
  140. with open(path, "w"):
  141. pass
  142. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  143. assert ".data" not in dn.path
  144. assert os.path.exists(dn.path)
  145. def test_get_downloadable_path(self):
  146. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  147. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  148. assert dn._get_downloadable_path() == path
  149. def test_get_downloadable_path_with_not_existing_file(self):
  150. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTING.csv", "exposed_type": "pandas"})
  151. assert dn._get_downloadable_path() == ""
  152. def test_upload(self, csv_file, tmpdir_factory):
  153. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  154. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  155. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "pandas"})
  156. dn.write(old_data)
  157. old_last_edit_date = dn.last_edit_date
  158. upload_content = pd.read_csv(csv_file)
  159. sleep(0.1)
  160. dn._upload(csv_file)
  161. assert_frame_equal(dn.read(), upload_content) # The content of the dn should change to the uploaded content
  162. assert dn.last_edit_date > old_last_edit_date
  163. assert dn.path == old_csv_path # The path of the dn should not change
  164. def test_upload_with_upload_check_pandas(self, csv_file, tmpdir_factory):
  165. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  166. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  167. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "pandas"})
  168. dn.write(old_data)
  169. old_last_edit_date = dn.last_edit_date
  170. def check_data_column(upload_path, upload_data):
  171. return upload_path.endswith(".csv") and upload_data.columns.tolist() == ["a", "b", "c"]
  172. wrong_format_not_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_csv").strpath
  173. old_data.to_csv(wrong_format_not_csv_path, index=False)
  174. wrong_format_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.csv").strpath
  175. pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]).to_csv(wrong_format_csv_path, index=False)
  176. # The upload should fail when the file is not a csv
  177. assert not dn._upload(wrong_format_not_csv_path, upload_checker=check_data_column)
  178. # The upload should fail when check_data_column() return False
  179. assert not dn._upload(wrong_format_csv_path, upload_checker=check_data_column)
  180. assert_frame_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  181. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  182. assert dn.path == old_csv_path # The path of the dn should not change
  183. # The upload should succeed when check_data_column() return True
  184. assert dn._upload(csv_file, upload_checker=check_data_column)
  185. def test_upload_with_upload_check_numpy(self, tmpdir_factory):
  186. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  187. old_data = np.array([[1, 2, 3], [4, 5, 6]])
  188. new_csv_path = tmpdir_factory.mktemp("data").join("new_upload_data.csv").strpath
  189. new_data = np.array([[1, 2, 3], [4, 5, 6]])
  190. pd.DataFrame(new_data).to_csv(new_csv_path, index=False)
  191. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "numpy"})
  192. dn.write(old_data)
  193. old_last_edit_date = dn.last_edit_date
  194. def check_data_is_positive(upload_path, upload_data):
  195. return upload_path.endswith(".csv") and np.all(upload_data > 0)
  196. wrong_format_not_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_csv").strpath
  197. pd.DataFrame(old_data).to_csv(wrong_format_not_csv_path, index=False)
  198. wrong_format_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.csv").strpath
  199. pd.DataFrame(np.array([[-1, 2, 3], [-4, -5, -6]])).to_csv(wrong_format_csv_path, index=False)
  200. # The upload should fail when the file is not a csv
  201. assert not dn._upload(wrong_format_not_csv_path, upload_checker=check_data_is_positive)
  202. # The upload should fail when check_data_is_positive() return False
  203. assert not dn._upload(wrong_format_csv_path, upload_checker=check_data_is_positive)
  204. np.array_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  205. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  206. assert dn.path == old_csv_path # The path of the dn should not change
  207. # The upload should succeed when check_data_is_positive() return True
  208. assert dn._upload(new_csv_path, upload_checker=check_data_is_positive)