test_excel_data_node.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. from typing import Dict
  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.core.data._data_manager import _DataManager
  25. from taipy.core.data.data_node_id import DataNodeId
  26. from taipy.core.data.excel import ExcelDataNode
  27. from taipy.core.exceptions.exceptions import (
  28. ExposedTypeLengthMismatch,
  29. InvalidExposedType,
  30. NonExistingExcelSheet,
  31. )
  32. @pytest.fixture(scope="function", autouse=True)
  33. def cleanup():
  34. yield
  35. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.xlsx")
  36. if os.path.exists(path):
  37. os.remove(path)
  38. class MyCustomObject:
  39. def __init__(self, id, integer, text):
  40. self.id = id
  41. self.integer = integer
  42. self.text = text
  43. class MyCustomObject1:
  44. def __init__(self, id, integer, text):
  45. self.id = id
  46. self.integer = integer
  47. self.text = text
  48. class MyCustomObject2:
  49. def __init__(self, id, integer, text):
  50. self.id = id
  51. self.integer = integer
  52. self.text = text
  53. class TestExcelDataNode:
  54. def test_new_excel_data_node_with_existing_file_is_ready_for_reading(self):
  55. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "excel", path="NOT_EXISTING.csv")
  56. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  57. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "excel", path=path)
  58. dns = _DataManager._bulk_get_or_create([not_ready_dn_cfg, ready_dn_cfg])
  59. assert not dns[not_ready_dn_cfg].is_ready_for_reading
  60. assert dns[ready_dn_cfg].is_ready_for_reading
  61. def test_create(self):
  62. path = "data/node/path"
  63. sheet_names = ["sheet_name_1", "sheet_name_2"]
  64. dn = ExcelDataNode(
  65. "foo_bar",
  66. Scope.SCENARIO,
  67. properties={"path": path, "has_header": False, "sheet_name": sheet_names, "name": "super name"},
  68. )
  69. assert isinstance(dn, ExcelDataNode)
  70. assert dn.storage_type() == "excel"
  71. assert dn.config_id == "foo_bar"
  72. assert dn.name == "super name"
  73. assert dn.scope == Scope.SCENARIO
  74. assert dn.id is not None
  75. assert dn.owner_id is None
  76. assert dn.parent_ids == set()
  77. assert dn.last_edit_date is None
  78. assert dn.job_ids == []
  79. assert not dn.is_ready_for_reading
  80. assert dn.path == path
  81. assert dn.has_header is False
  82. assert dn.sheet_name == sheet_names
  83. def test_get_user_properties(self, excel_file):
  84. dn_1 = ExcelDataNode("dn_1", Scope.SCENARIO, properties={"path": "data/node/path"})
  85. assert dn_1._get_user_properties() == {}
  86. dn_2 = ExcelDataNode(
  87. "dn_2",
  88. Scope.SCENARIO,
  89. properties={
  90. "exposed_type": "numpy",
  91. "default_data": "foo",
  92. "default_path": excel_file,
  93. "has_header": False,
  94. "sheet_name": ["sheet_name_1", "sheet_name_2"],
  95. "foo": "bar",
  96. },
  97. )
  98. # exposed_type, default_data, default_path, path, has_header are filtered out
  99. assert dn_2._get_user_properties() == {"foo": "bar"}
  100. def test_modin_deprecated_in_favor_of_pandas(self):
  101. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  102. # Create ExcelDataNode with modin exposed_type
  103. props = {"path": path, "sheet_name": "Sheet1", "exposed_type": "modin"}
  104. modin_dn = ExcelDataNode("bar", Scope.SCENARIO, properties=props)
  105. assert modin_dn.properties["exposed_type"] == "pandas"
  106. data_modin = modin_dn.read()
  107. assert isinstance(data_modin, pd.DataFrame)
  108. def test_set_path(self):
  109. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.xlsx"})
  110. assert dn.path == "foo.xlsx"
  111. dn.path = "bar.xlsx"
  112. assert dn.path == "bar.xlsx"
  113. @pytest.mark.parametrize(
  114. ["properties", "exists"],
  115. [
  116. ({"default_data": {"a": ["foo", "bar"]}}, True),
  117. ({}, False),
  118. ],
  119. )
  120. def test_create_with_default_data(self, properties, exists):
  121. dn = ExcelDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  122. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "excels", dn.id + ".xlsx")
  123. assert os.path.exists(dn.path) is exists
  124. def test_read_write_after_modify_path(self):
  125. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  126. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.xlsx")
  127. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  128. read_data = dn.read()
  129. assert read_data is not None
  130. dn.path = new_path
  131. with pytest.raises(FileNotFoundError):
  132. dn.read()
  133. dn.write(read_data)
  134. for sheet, df in dn.read().items():
  135. assert np.array_equal(df.values, read_data[sheet].values)
  136. def test_exposed_type_custom_class_after_modify_path(self):
  137. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  138. new_path = os.path.join(
  139. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  140. ) # ["Sheet1", "Sheet2", "Sheet3"]
  141. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": MyCustomObject1})
  142. assert dn.exposed_type == MyCustomObject1
  143. dn.read()
  144. dn.path = new_path
  145. dn.read()
  146. dn = ExcelDataNode(
  147. "foo",
  148. Scope.SCENARIO,
  149. properties={"default_path": path, "exposed_type": MyCustomObject1, "sheet_name": ["Sheet4"]},
  150. )
  151. assert dn.exposed_type == MyCustomObject1
  152. with pytest.raises(NonExistingExcelSheet):
  153. dn.read()
  154. def test_exposed_type_dict(self):
  155. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  156. dn = ExcelDataNode(
  157. "foo",
  158. Scope.SCENARIO,
  159. properties={
  160. "default_path": path,
  161. "exposed_type": {
  162. "Sheet1": MyCustomObject1,
  163. "Sheet2": MyCustomObject2,
  164. "Sheet3": MyCustomObject1,
  165. },
  166. },
  167. )
  168. data = dn.read()
  169. assert isinstance(data, Dict)
  170. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  171. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  172. def test_exposed_type_list(self):
  173. path_1 = os.path.join(
  174. pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx"
  175. ) # ["Sheet1", "Sheet2"]
  176. path_2 = os.path.join(
  177. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  178. ) # ["Sheet1", "Sheet2", "Sheet3"]
  179. dn = ExcelDataNode(
  180. "foo",
  181. Scope.SCENARIO,
  182. properties={"default_path": path_1, "exposed_type": [MyCustomObject1, MyCustomObject2]},
  183. )
  184. data = dn.read()
  185. assert isinstance(data, Dict)
  186. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  187. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  188. dn.path = path_2
  189. with pytest.raises(ExposedTypeLengthMismatch):
  190. dn.read()
  191. def test_not_trying_to_read_sheet_names_when_exposed_type_is_set(self):
  192. dn = ExcelDataNode(
  193. "foo", Scope.SCENARIO, properties={"default_path": "notexistyet.xlsx", "exposed_type": MyCustomObject1}
  194. )
  195. assert dn.path == "notexistyet.xlsx"
  196. assert dn.exposed_type == MyCustomObject1
  197. dn = ExcelDataNode(
  198. "foo",
  199. Scope.SCENARIO,
  200. properties={"default_path": "notexistyet.xlsx", "exposed_type": [MyCustomObject1, MyCustomObject2]},
  201. )
  202. assert dn.path == "notexistyet.xlsx"
  203. assert dn.exposed_type == [MyCustomObject1, MyCustomObject2]
  204. dn = ExcelDataNode(
  205. "foo",
  206. Scope.SCENARIO,
  207. properties={
  208. "default_path": "notexistyet.xlsx",
  209. "exposed_type": {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2},
  210. },
  211. )
  212. assert dn.path == "notexistyet.xlsx"
  213. assert dn.exposed_type == {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2}
  214. def test_exposed_type_default(self):
  215. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  216. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "sheet_name": "Sheet1"})
  217. assert dn.exposed_type == "pandas"
  218. data = dn.read()
  219. assert isinstance(data, pd.DataFrame)
  220. def test_pandas_exposed_type(self):
  221. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  222. dn = ExcelDataNode(
  223. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": "pandas", "sheet_name": "Sheet1"}
  224. )
  225. assert dn.exposed_type == "pandas"
  226. data = dn.read()
  227. assert isinstance(data, pd.DataFrame)
  228. def test_complex_exposed_type_dict(self):
  229. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5"]
  230. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  231. dn = ExcelDataNode(
  232. "foo",
  233. Scope.SCENARIO,
  234. properties={
  235. "default_path": path,
  236. "exposed_type": {
  237. "Sheet1": MyCustomObject1,
  238. "Sheet2": "numpy",
  239. "Sheet3": "pandas",
  240. },
  241. "sheet_name": ["Sheet1", "Sheet2", "Sheet3", "Sheet4"],
  242. },
  243. )
  244. data = dn.read()
  245. assert isinstance(data, dict)
  246. assert isinstance(data["Sheet1"], list)
  247. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  248. assert isinstance(data["Sheet2"], np.ndarray)
  249. assert isinstance(data["Sheet3"], pd.DataFrame)
  250. assert isinstance(data["Sheet4"], pd.DataFrame)
  251. assert data.get("Sheet5") is None
  252. def test_complex_exposed_type_list(self):
  253. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4","Sheet5"]
  254. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  255. dn = ExcelDataNode(
  256. "foo",
  257. Scope.SCENARIO,
  258. properties={
  259. "default_path": path,
  260. "exposed_type": [MyCustomObject1, "numpy", "pandas"],
  261. "sheet_name": ["Sheet1", "Sheet2", "Sheet3"],
  262. },
  263. )
  264. data = dn.read()
  265. assert isinstance(data, dict)
  266. assert isinstance(data["Sheet1"], list)
  267. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  268. assert isinstance(data["Sheet2"], np.ndarray)
  269. assert isinstance(data["Sheet3"], pd.DataFrame)
  270. def test_invalid_exposed_type(self):
  271. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  272. with pytest.raises(InvalidExposedType):
  273. ExcelDataNode(
  274. "foo",
  275. Scope.SCENARIO,
  276. properties={"default_path": path, "exposed_type": "invalid", "sheet_name": "Sheet1"},
  277. )
  278. with pytest.raises(InvalidExposedType):
  279. ExcelDataNode(
  280. "foo",
  281. Scope.SCENARIO,
  282. properties={
  283. "default_path": path,
  284. "exposed_type": ["numpy", "invalid", "pandas"],
  285. "sheet_name": "Sheet1",
  286. },
  287. )
  288. with pytest.raises(InvalidExposedType):
  289. ExcelDataNode(
  290. "foo",
  291. Scope.SCENARIO,
  292. properties={
  293. "default_path": path,
  294. "exposed_type": {"Sheet1": "pandas", "Sheet2": "invalid"},
  295. "sheet_name": "Sheet1",
  296. },
  297. )
  298. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  299. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.xlsx"))
  300. pd.DataFrame([]).to_excel(temp_file_path)
  301. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  302. dn.write(pd.DataFrame([1, 2, 3]))
  303. previous_edit_date = dn.last_edit_date
  304. sleep(0.1)
  305. pd.DataFrame([4, 5, 6]).to_excel(temp_file_path)
  306. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  307. assert previous_edit_date < dn.last_edit_date
  308. assert new_edit_date == dn.last_edit_date
  309. sleep(0.1)
  310. dn.write(pd.DataFrame([7, 8, 9]))
  311. assert new_edit_date < dn.last_edit_date
  312. os.unlink(temp_file_path)
  313. def test_migrate_to_new_path(self, tmp_path):
  314. _base_path = os.path.join(tmp_path, ".data")
  315. path = os.path.join(_base_path, "test.xlsx")
  316. # create a file on old path
  317. os.mkdir(_base_path)
  318. with open(path, "w"):
  319. pass
  320. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  321. assert ".data" not in dn.path
  322. assert os.path.exists(dn.path)
  323. def test_get_download_path(self):
  324. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  325. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  326. assert dn._get_downloadable_path() == path
  327. def test_get_downloadable_path_with_not_existing_file(self):
  328. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTING.xlsx", "exposed_type": "pandas"})
  329. assert dn._get_downloadable_path() == ""
  330. def test_upload(self, excel_file, tmpdir_factory):
  331. old_xlsx_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  332. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  333. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_xlsx_path, "exposed_type": "pandas"})
  334. dn.write(old_data)
  335. old_last_edit_date = dn.last_edit_date
  336. upload_content = pd.read_excel(excel_file)
  337. with freezegun.freeze_time(old_last_edit_date + timedelta(seconds=1)):
  338. dn._upload(excel_file)
  339. assert_frame_equal(dn.read()["Sheet1"], upload_content) # The data of dn should change to the uploaded content
  340. assert dn.last_edit_date > old_last_edit_date
  341. assert dn.path == old_xlsx_path # The path of the dn should not change
  342. def test_upload_with_upload_check_pandas(self, excel_file, tmpdir_factory):
  343. old_xlsx_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  344. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  345. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_xlsx_path, "exposed_type": "pandas"})
  346. dn.write(old_data)
  347. old_last_edit_date = dn.last_edit_date
  348. def check_data_column(upload_path, upload_data):
  349. """Check if the uploaded data has the correct file format and
  350. the sheet named "Sheet1" has the correct columns.
  351. """
  352. return upload_path.endswith(".xlsx") and upload_data["Sheet1"].columns.tolist() == ["a", "b", "c"]
  353. not_exists_xlsx_path = tmpdir_factory.mktemp("data").join("not_exists.xlsx").strpath
  354. reasons = dn._upload(not_exists_xlsx_path, upload_checker=check_data_column)
  355. assert bool(reasons) is False
  356. assert (
  357. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.xlsx can not be read,"
  358. f' therefore is not a valid data file for data node "{dn.id}"'
  359. )
  360. not_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsm").strpath
  361. old_data.to_excel(not_xlsx_path, index=False)
  362. # The upload should fail when the file is not a xlsx
  363. reasons = dn._upload(not_xlsx_path, upload_checker=check_data_column)
  364. assert bool(reasons) is False
  365. assert (
  366. str(list(reasons._reasons[dn.id])[0])
  367. == f'The uploaded file wrong_format_df.xlsm has invalid data for data node "{dn.id}"'
  368. )
  369. wrong_format_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsx").strpath
  370. pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]).to_excel(wrong_format_xlsx_path, index=False)
  371. # The upload should fail when check_data_column() return False
  372. reasons = dn._upload(wrong_format_xlsx_path, upload_checker=check_data_column)
  373. assert bool(reasons) is False
  374. assert (
  375. str(list(reasons._reasons[dn.id])[0])
  376. == f'The uploaded file wrong_format_df.xlsx has invalid data for data node "{dn.id}"'
  377. )
  378. assert_frame_equal(dn.read()["Sheet1"], old_data) # The content of the dn should not change when upload fails
  379. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  380. assert dn.path == old_xlsx_path # The path of the dn should not change
  381. # The upload should succeed when check_data_column() return True
  382. assert dn._upload(excel_file, upload_checker=check_data_column)
  383. def test_upload_with_upload_check_numpy(self, tmpdir_factory):
  384. old_excel_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  385. old_data = np.array([[1, 2, 3], [4, 5, 6]])
  386. new_excel_path = tmpdir_factory.mktemp("data").join("new_upload_data.xlsx").strpath
  387. new_data = np.array([[1, 2, 3], [4, 5, 6]])
  388. pd.DataFrame(new_data).to_excel(new_excel_path, index=False)
  389. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_excel_path, "exposed_type": "numpy"})
  390. dn.write(old_data)
  391. old_last_edit_date = dn.last_edit_date
  392. def check_data_is_positive(upload_path, upload_data):
  393. return upload_path.endswith(".xlsx") and np.all(upload_data["Sheet1"] > 0)
  394. not_exists_xlsx_path = tmpdir_factory.mktemp("data").join("not_exists.xlsx").strpath
  395. reasons = dn._upload(not_exists_xlsx_path, upload_checker=check_data_is_positive)
  396. assert bool(reasons) is False
  397. assert (
  398. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.xlsx can not be read,"
  399. f' therefore is not a valid data file for data node "{dn.id}"'
  400. )
  401. wrong_format_not_excel_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsm").strpath
  402. pd.DataFrame(old_data).to_excel(wrong_format_not_excel_path, index=False)
  403. # The upload should fail when the file is not a excel
  404. reasons = dn._upload(wrong_format_not_excel_path, upload_checker=check_data_is_positive)
  405. assert bool(reasons) is False
  406. assert (
  407. str(list(reasons._reasons[dn.id])[0])
  408. == f'The uploaded file wrong_format_df.xlsm has invalid data for data node "{dn.id}"'
  409. )
  410. not_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsx").strpath
  411. pd.DataFrame(np.array([[-1, 2, 3], [-4, -5, -6]])).to_excel(not_xlsx_path, index=False)
  412. # The upload should fail when check_data_is_positive() return False
  413. reasons = dn._upload(not_xlsx_path, upload_checker=check_data_is_positive)
  414. assert (
  415. str(list(reasons._reasons[dn.id])[0])
  416. == f'The uploaded file wrong_format_df.xlsx has invalid data for data node "{dn.id}"'
  417. )
  418. np.array_equal(dn.read()["Sheet1"], old_data) # The content of the dn should not change when upload fails
  419. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  420. assert dn.path == old_excel_path # The path of the dn should not change
  421. # The upload should succeed when check_data_is_positive() return True
  422. assert dn._upload(new_excel_path, upload_checker=check_data_is_positive)