test_csv_data_node.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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, timedelta
  16. from time import sleep
  17. import freezegun
  18. import numpy as np
  19. import pandas as pd
  20. import pytest
  21. from pandas.testing import assert_frame_equal
  22. from taipy.config.common.scope import Scope
  23. from taipy.config.config import Config
  24. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  25. from taipy.core.data._data_manager import _DataManager
  26. from taipy.core.data._data_manager_factory import _DataManagerFactory
  27. from taipy.core.data.csv import CSVDataNode
  28. from taipy.core.data.data_node_id import DataNodeId
  29. from taipy.core.exceptions.exceptions import InvalidExposedType
  30. @pytest.fixture(scope="function", autouse=True)
  31. def cleanup():
  32. yield
  33. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.csv")
  34. if os.path.isfile(path):
  35. os.remove(path)
  36. @dataclasses.dataclass
  37. class MyCustomObject:
  38. id: int
  39. integer: int
  40. text: str
  41. class TestCSVDataNode:
  42. def test_create(self):
  43. default_path = "data/node/path"
  44. csv_dn_config = Config.configure_csv_data_node(
  45. id="foo_bar", default_path=default_path, has_header=False, name="super name"
  46. )
  47. dn = _DataManagerFactory._build_manager()._create_and_set(csv_dn_config, None, None)
  48. assert isinstance(dn, CSVDataNode)
  49. assert dn.storage_type() == "csv"
  50. assert dn.config_id == "foo_bar"
  51. assert dn.name == "super name"
  52. assert dn.scope == Scope.SCENARIO
  53. assert dn.id is not None
  54. assert dn.owner_id is None
  55. assert dn.last_edit_date is None
  56. assert dn.job_ids == []
  57. assert not dn.is_ready_for_reading
  58. assert dn.path == default_path
  59. assert dn.has_header is False
  60. assert dn.exposed_type == "pandas"
  61. csv_dn_config = Config.configure_csv_data_node(
  62. id="foo", default_path=default_path, has_header=True, exposed_type=MyCustomObject
  63. )
  64. dn = _DataManagerFactory._build_manager()._create_and_set(csv_dn_config, None, None)
  65. assert dn.storage_type() == "csv"
  66. assert dn.config_id == "foo"
  67. assert dn.has_header is True
  68. assert dn.exposed_type == MyCustomObject
  69. with pytest.raises(InvalidConfigurationId):
  70. CSVDataNode(
  71. "foo bar", Scope.SCENARIO, properties={"path": default_path, "has_header": False, "name": "super name"}
  72. )
  73. def test_modin_deprecated_in_favor_of_pandas(self):
  74. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  75. # Create CSVDataNode with modin exposed_type
  76. csv_data_node_as_modin = CSVDataNode("bar", Scope.SCENARIO, properties={"path": path, "exposed_type": "modin"})
  77. assert csv_data_node_as_modin.properties["exposed_type"] == "pandas"
  78. data_modin = csv_data_node_as_modin.read()
  79. assert isinstance(data_modin, pd.DataFrame)
  80. def test_get_user_properties(self, csv_file):
  81. dn_1 = CSVDataNode("dn_1", Scope.SCENARIO, properties={"path": "data/node/path"})
  82. assert dn_1._get_user_properties() == {}
  83. dn_2 = CSVDataNode(
  84. "dn_2",
  85. Scope.SCENARIO,
  86. properties={
  87. "exposed_type": "numpy",
  88. "default_data": "foo",
  89. "default_path": csv_file,
  90. "has_header": False,
  91. "foo": "bar",
  92. },
  93. )
  94. # exposed_type, default_data, default_path, path, has_header, sheet_name are filtered out
  95. assert dn_2._get_user_properties() == {"foo": "bar"}
  96. def test_new_csv_data_node_with_existing_file_is_ready_for_reading(self):
  97. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "csv", path="NOT_EXISTING.csv")
  98. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  99. assert not not_ready_dn.is_ready_for_reading
  100. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  101. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "csv", path=path)
  102. ready_dn = _DataManager._bulk_get_or_create([ready_dn_cfg])[ready_dn_cfg]
  103. assert ready_dn.is_ready_for_reading
  104. @pytest.mark.parametrize(
  105. ["properties", "exists"],
  106. [
  107. ({}, False),
  108. ({"default_data": ["foo", "bar"]}, True),
  109. ],
  110. )
  111. def test_create_with_default_data(self, properties, exists):
  112. dn = CSVDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  113. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "csvs", dn.id + ".csv")
  114. assert os.path.exists(dn.path) is exists
  115. def test_set_path(self):
  116. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.csv"})
  117. assert dn.path == "foo.csv"
  118. dn.path = "bar.csv"
  119. assert dn.path == "bar.csv"
  120. def test_read_write_after_modify_path(self):
  121. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  122. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.csv")
  123. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  124. read_data = dn.read()
  125. assert read_data is not None
  126. dn.path = new_path
  127. with pytest.raises(FileNotFoundError):
  128. dn.read()
  129. dn.write(read_data)
  130. assert dn.read().equals(read_data)
  131. def test_pandas_exposed_type(self):
  132. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  133. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  134. assert isinstance(dn.read(), pd.DataFrame)
  135. def test_raise_error_invalid_exposed_type(self):
  136. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  137. with pytest.raises(InvalidExposedType):
  138. CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "foo"})
  139. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  140. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.csv"))
  141. pd.DataFrame([]).to_csv(temp_file_path)
  142. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  143. dn.write(pd.DataFrame([1, 2, 3]))
  144. previous_edit_date = dn.last_edit_date
  145. sleep(0.1)
  146. pd.DataFrame([4, 5, 6]).to_csv(temp_file_path)
  147. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  148. assert previous_edit_date < dn.last_edit_date
  149. assert new_edit_date == dn.last_edit_date
  150. sleep(0.1)
  151. dn.write(pd.DataFrame([7, 8, 9]))
  152. assert new_edit_date < dn.last_edit_date
  153. os.unlink(temp_file_path)
  154. def test_migrate_to_new_path(self, tmp_path):
  155. _base_path = os.path.join(tmp_path, ".data")
  156. path = os.path.join(_base_path, "test.csv")
  157. # create a file on old path
  158. os.mkdir(_base_path)
  159. with open(path, "w"):
  160. pass
  161. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  162. assert ".data" not in dn.path
  163. assert os.path.exists(dn.path)
  164. def test_get_downloadable_path(self):
  165. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  166. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  167. assert dn._get_downloadable_path() == path
  168. def test_get_downloadable_path_with_not_existing_file(self):
  169. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTING.csv", "exposed_type": "pandas"})
  170. assert dn._get_downloadable_path() == ""
  171. def test_upload(self, csv_file, tmpdir_factory):
  172. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  173. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  174. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "pandas"})
  175. dn.write(old_data)
  176. old_last_edit_date = dn.last_edit_date
  177. upload_content = pd.read_csv(csv_file)
  178. with freezegun.freeze_time(old_last_edit_date + timedelta(seconds=1)):
  179. dn._upload(csv_file)
  180. assert_frame_equal(dn.read(), upload_content) # The content of the dn should change to the uploaded content
  181. assert dn.last_edit_date > old_last_edit_date
  182. assert dn.path == old_csv_path # The path of the dn should not change
  183. def test_upload_with_upload_check_pandas(self, csv_file, tmpdir_factory):
  184. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  185. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  186. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "pandas"})
  187. dn.write(old_data)
  188. old_last_edit_date = dn.last_edit_date
  189. def check_data_column(upload_path, upload_data):
  190. return upload_path.endswith(".csv") and upload_data.columns.tolist() == ["a", "b", "c"]
  191. not_exists_csv_path = tmpdir_factory.mktemp("data").join("not_exists.csv").strpath
  192. reasons = dn._upload(not_exists_csv_path, upload_checker=check_data_column)
  193. assert bool(reasons) is False
  194. assert (
  195. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.csv can not be read,"
  196. f' therefore is not a valid data file for data node "{dn.id}"'
  197. )
  198. not_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_csv").strpath
  199. old_data.to_csv(not_csv_path, index=False)
  200. # The upload should fail when the file is not a csv
  201. reasons = dn._upload(not_csv_path, upload_checker=check_data_column)
  202. assert bool(reasons) is False
  203. assert (
  204. str(list(reasons._reasons[dn.id])[0])
  205. == f'The uploaded file wrong_format_df.not_csv has invalid data for data node "{dn.id}"'
  206. )
  207. wrong_format_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.csv").strpath
  208. pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]).to_csv(wrong_format_csv_path, index=False)
  209. # The upload should fail when check_data_column() return False
  210. reasons = dn._upload(wrong_format_csv_path, upload_checker=check_data_column)
  211. assert bool(reasons) is False
  212. assert (
  213. str(list(reasons._reasons[dn.id])[0])
  214. == f'The uploaded file wrong_format_df.csv has invalid data for data node "{dn.id}"'
  215. )
  216. assert_frame_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  217. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  218. assert dn.path == old_csv_path # The path of the dn should not change
  219. # The upload should succeed when check_data_column() return True
  220. assert dn._upload(csv_file, upload_checker=check_data_column)
  221. def test_upload_with_upload_check_numpy(self, tmpdir_factory):
  222. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  223. old_data = np.array([[1, 2, 3], [4, 5, 6]])
  224. new_csv_path = tmpdir_factory.mktemp("data").join("new_upload_data.csv").strpath
  225. new_data = np.array([[1, 2, 3], [4, 5, 6]])
  226. pd.DataFrame(new_data).to_csv(new_csv_path, index=False)
  227. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "numpy"})
  228. dn.write(old_data)
  229. old_last_edit_date = dn.last_edit_date
  230. def check_data_is_positive(upload_path, upload_data):
  231. return upload_path.endswith(".csv") and np.all(upload_data > 0)
  232. not_exists_csv_path = tmpdir_factory.mktemp("data").join("not_exists.csv").strpath
  233. reasons = dn._upload(not_exists_csv_path, upload_checker=check_data_is_positive)
  234. assert bool(reasons) is False
  235. assert (
  236. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.csv can not be read"
  237. f', therefore is not a valid data file for data node "{dn.id}"'
  238. )
  239. not_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_csv").strpath
  240. pd.DataFrame(old_data).to_csv(not_csv_path, index=False)
  241. # The upload should fail when the file is not a csv
  242. reasons = dn._upload(not_csv_path, upload_checker=check_data_is_positive)
  243. assert bool(reasons) is False
  244. assert (
  245. str(list(reasons._reasons[dn.id])[0])
  246. == f'The uploaded file wrong_format_df.not_csv has invalid data for data node "{dn.id}"'
  247. )
  248. wrong_format_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.csv").strpath
  249. pd.DataFrame(np.array([[-1, 2, 3], [-4, -5, -6]])).to_csv(wrong_format_csv_path, index=False)
  250. # The upload should fail when check_data_is_positive() return False
  251. reasons = dn._upload(wrong_format_csv_path, upload_checker=check_data_is_positive)
  252. assert bool(reasons) is False
  253. assert (
  254. str(list(reasons._reasons[dn.id])[0])
  255. == f'The uploaded file wrong_format_df.csv has invalid data for data node "{dn.id}"'
  256. )
  257. np.array_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  258. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  259. assert dn.path == old_csv_path # The path of the dn should not change
  260. # The upload should succeed when check_data_is_positive() return True
  261. assert dn._upload(new_csv_path, upload_checker=check_data_is_positive)