test_excel_data_node.py 19 KB

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