test_csv_data_node.py 14 KB

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