test_csv_data_node.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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.properties["has_header"] is False
  60. assert dn.properties["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.properties["has_header"] is True
  68. assert dn.properties["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_with_exception(self, csv_file, tmpdir_factory, caplog):
  184. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  185. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "pandas"})
  186. def check_with_exception(upload_path, upload_data):
  187. raise Exception("An error with check_with_exception")
  188. reasons = dn._upload(csv_file, upload_checker=check_with_exception)
  189. assert bool(reasons) is False
  190. assert (
  191. f"Error while checking if df.csv can be uploaded to data node {dn.id} using "
  192. "the upload checker check_with_exception: An error with check_with_exception" in caplog.text
  193. )
  194. def test_upload_with_upload_check_pandas(self, csv_file, tmpdir_factory):
  195. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  196. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  197. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "pandas"})
  198. dn.write(old_data)
  199. old_last_edit_date = dn.last_edit_date
  200. def check_data_column(upload_path, upload_data):
  201. return upload_path.endswith(".csv") and upload_data.columns.tolist() == ["a", "b", "c"]
  202. not_exists_csv_path = tmpdir_factory.mktemp("data").join("not_exists.csv").strpath
  203. reasons = dn._upload(not_exists_csv_path, upload_checker=check_data_column)
  204. assert bool(reasons) is False
  205. assert (
  206. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.csv can not be read,"
  207. f' therefore is not a valid data file for data node "{dn.id}"'
  208. )
  209. not_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_csv").strpath
  210. old_data.to_csv(not_csv_path, index=False)
  211. # The upload should fail when the file is not a csv
  212. reasons = dn._upload(not_csv_path, upload_checker=check_data_column)
  213. assert bool(reasons) is False
  214. assert (
  215. str(list(reasons._reasons[dn.id])[0])
  216. == f'The uploaded file wrong_format_df.not_csv has invalid data for data node "{dn.id}"'
  217. )
  218. wrong_format_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.csv").strpath
  219. pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]).to_csv(wrong_format_csv_path, index=False)
  220. # The upload should fail when check_data_column() return False
  221. reasons = dn._upload(wrong_format_csv_path, upload_checker=check_data_column)
  222. assert bool(reasons) is False
  223. assert (
  224. str(list(reasons._reasons[dn.id])[0])
  225. == f'The uploaded file wrong_format_df.csv has invalid data for data node "{dn.id}"'
  226. )
  227. assert_frame_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  228. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  229. assert dn.path == old_csv_path # The path of the dn should not change
  230. # The upload should succeed when check_data_column() return True
  231. assert dn._upload(csv_file, upload_checker=check_data_column)
  232. def test_upload_with_upload_check_numpy(self, tmpdir_factory):
  233. old_csv_path = tmpdir_factory.mktemp("data").join("df.csv").strpath
  234. old_data = np.array([[1, 2, 3], [4, 5, 6]])
  235. new_csv_path = tmpdir_factory.mktemp("data").join("new_upload_data.csv").strpath
  236. new_data = np.array([[1, 2, 3], [4, 5, 6]])
  237. pd.DataFrame(new_data).to_csv(new_csv_path, index=False)
  238. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": old_csv_path, "exposed_type": "numpy"})
  239. dn.write(old_data)
  240. old_last_edit_date = dn.last_edit_date
  241. def check_data_is_positive(upload_path, upload_data):
  242. return upload_path.endswith(".csv") and np.all(upload_data > 0)
  243. not_exists_csv_path = tmpdir_factory.mktemp("data").join("not_exists.csv").strpath
  244. reasons = dn._upload(not_exists_csv_path, upload_checker=check_data_is_positive)
  245. assert bool(reasons) is False
  246. assert (
  247. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.csv can not be read"
  248. f', therefore is not a valid data file for data node "{dn.id}"'
  249. )
  250. not_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_csv").strpath
  251. pd.DataFrame(old_data).to_csv(not_csv_path, index=False)
  252. # The upload should fail when the file is not a csv
  253. reasons = dn._upload(not_csv_path, upload_checker=check_data_is_positive)
  254. assert bool(reasons) is False
  255. assert (
  256. str(list(reasons._reasons[dn.id])[0])
  257. == f'The uploaded file wrong_format_df.not_csv has invalid data for data node "{dn.id}"'
  258. )
  259. wrong_format_csv_path = tmpdir_factory.mktemp("data").join("wrong_format_df.csv").strpath
  260. pd.DataFrame(np.array([[-1, 2, 3], [-4, -5, -6]])).to_csv(wrong_format_csv_path, index=False)
  261. # The upload should fail when check_data_is_positive() return False
  262. reasons = dn._upload(wrong_format_csv_path, upload_checker=check_data_is_positive)
  263. assert bool(reasons) is False
  264. assert (
  265. str(list(reasons._reasons[dn.id])[0])
  266. == f'The uploaded file wrong_format_df.csv has invalid data for data node "{dn.id}"'
  267. )
  268. np.array_equal(dn.read(), old_data) # The content of the dn should not change when upload fails
  269. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  270. assert dn.path == old_csv_path # The path of the dn should not change
  271. # The upload should succeed when check_data_is_positive() return True
  272. assert dn._upload(new_csv_path, upload_checker=check_data_is_positive)