test_excel_data_node.py 24 KB

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