test_excel_data_node.py 23 KB

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