1
0

test_csv_data_node.py 17 KB

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