test_excel_data_node.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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.common.config import Config
  23. from taipy.common.config.common.scope import Scope
  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_pandas_dataframe_exposed_type(self):
  267. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  268. dn = ExcelDataNode(
  269. "foo",
  270. Scope.SCENARIO,
  271. properties={"default_path": path, "exposed_type": pd.DataFrame, "sheet_name": "Sheet1"},
  272. )
  273. assert dn.properties["exposed_type"] == pd.DataFrame
  274. data = dn.read()
  275. assert isinstance(data, pd.DataFrame)
  276. def test_numpy_ndarray_exposed_type(self):
  277. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  278. dn = ExcelDataNode(
  279. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": np.ndarray, "sheet_name": "Sheet1"}
  280. )
  281. assert dn.properties["exposed_type"] == np.ndarray
  282. data = dn.read()
  283. assert isinstance(data, np.ndarray)
  284. def test_complex_exposed_type_dict(self):
  285. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5"]
  286. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  287. dn = ExcelDataNode(
  288. "foo",
  289. Scope.SCENARIO,
  290. properties={
  291. "default_path": path,
  292. "exposed_type": {
  293. "Sheet1": MyCustomObject1,
  294. "Sheet2": "numpy",
  295. "Sheet3": "pandas",
  296. },
  297. "sheet_name": ["Sheet1", "Sheet2", "Sheet3", "Sheet4"],
  298. },
  299. )
  300. data = dn.read()
  301. assert isinstance(data, dict)
  302. assert isinstance(data["Sheet1"], list)
  303. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  304. assert isinstance(data["Sheet2"], np.ndarray)
  305. assert isinstance(data["Sheet3"], pd.DataFrame)
  306. assert isinstance(data["Sheet4"], pd.DataFrame)
  307. assert data.get("Sheet5") is None
  308. def test_complex_exposed_type_list(self):
  309. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4","Sheet5"]
  310. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  311. dn = ExcelDataNode(
  312. "foo",
  313. Scope.SCENARIO,
  314. properties={
  315. "default_path": path,
  316. "exposed_type": [MyCustomObject1, "numpy", "pandas"],
  317. "sheet_name": ["Sheet1", "Sheet2", "Sheet3"],
  318. },
  319. )
  320. data = dn.read()
  321. assert isinstance(data, dict)
  322. assert isinstance(data["Sheet1"], list)
  323. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  324. assert isinstance(data["Sheet2"], np.ndarray)
  325. assert isinstance(data["Sheet3"], pd.DataFrame)
  326. def test_invalid_exposed_type(self):
  327. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  328. with pytest.raises(InvalidExposedType):
  329. ExcelDataNode(
  330. "foo",
  331. Scope.SCENARIO,
  332. properties={"default_path": path, "exposed_type": "invalid", "sheet_name": "Sheet1"},
  333. )
  334. with pytest.raises(InvalidExposedType):
  335. ExcelDataNode(
  336. "foo",
  337. Scope.SCENARIO,
  338. properties={
  339. "default_path": path,
  340. "exposed_type": ["numpy", "invalid", "pandas"],
  341. "sheet_name": "Sheet1",
  342. },
  343. )
  344. with pytest.raises(InvalidExposedType):
  345. ExcelDataNode(
  346. "foo",
  347. Scope.SCENARIO,
  348. properties={
  349. "default_path": path,
  350. "exposed_type": {"Sheet1": "pandas", "Sheet2": "invalid"},
  351. "sheet_name": "Sheet1",
  352. },
  353. )
  354. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  355. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.xlsx"))
  356. pd.DataFrame([]).to_excel(temp_file_path)
  357. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  358. dn.write(pd.DataFrame([1, 2, 3]))
  359. previous_edit_date = dn.last_edit_date
  360. sleep(0.1)
  361. pd.DataFrame([4, 5, 6]).to_excel(temp_file_path)
  362. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  363. assert previous_edit_date < dn.last_edit_date
  364. assert new_edit_date == dn.last_edit_date
  365. sleep(0.1)
  366. dn.write(pd.DataFrame([7, 8, 9]))
  367. assert new_edit_date < dn.last_edit_date
  368. os.unlink(temp_file_path)
  369. def test_migrate_to_new_path(self, tmp_path):
  370. _base_path = os.path.join(tmp_path, ".data")
  371. path = os.path.join(_base_path, "test.xlsx")
  372. # create a file on old path
  373. os.mkdir(_base_path)
  374. with open(path, "w"):
  375. pass
  376. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  377. assert ".data" not in dn.path
  378. assert os.path.exists(dn.path)
  379. def test_is_downloadable(self):
  380. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  381. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  382. reasons = dn.is_downloadable()
  383. assert reasons
  384. assert reasons.reasons == ""
  385. def test_is_not_downloadable_no_file(self):
  386. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/wrong_path.xlsx")
  387. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  388. reasons = dn.is_downloadable()
  389. assert not reasons
  390. assert len(reasons._reasons) == 1
  391. assert str(NoFileToDownload(path, dn.id)) in reasons.reasons
  392. def test_is_not_downloadable_not_a_file(self):
  393. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample")
  394. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  395. reasons = dn.is_downloadable()
  396. assert not reasons
  397. assert len(reasons._reasons) == 1
  398. assert str(NotAFile(path, dn.id)) in reasons.reasons
  399. def test_get_download_path(self):
  400. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  401. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  402. assert dn._get_downloadable_path() == path
  403. def test_get_downloadable_path_with_not_existing_file(self):
  404. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTING.xlsx", "exposed_type": "pandas"})
  405. assert dn._get_downloadable_path() == ""
  406. def test_upload(self, excel_file, tmpdir_factory):
  407. old_xlsx_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  408. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  409. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_xlsx_path, "exposed_type": "pandas"})
  410. dn.write(old_data)
  411. old_last_edit_date = dn.last_edit_date
  412. upload_content = pd.read_excel(excel_file)
  413. with freezegun.freeze_time(old_last_edit_date + timedelta(seconds=1)):
  414. dn._upload(excel_file)
  415. assert_frame_equal(dn.read()["Sheet1"], upload_content) # The data of dn should change to the uploaded content
  416. assert dn.last_edit_date > old_last_edit_date
  417. assert dn.path == old_xlsx_path # The path of the dn should not change
  418. def test_upload_with_upload_check_pandas(self, excel_file, tmpdir_factory):
  419. old_xlsx_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  420. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  421. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_xlsx_path, "exposed_type": "pandas"})
  422. dn.write(old_data)
  423. old_last_edit_date = dn.last_edit_date
  424. def check_data_column(upload_path, upload_data):
  425. """Check if the uploaded data has the correct file format and
  426. the sheet named "Sheet1" has the correct columns.
  427. """
  428. return upload_path.endswith(".xlsx") and upload_data["Sheet1"].columns.tolist() == ["a", "b", "c"]
  429. not_exists_xlsx_path = tmpdir_factory.mktemp("data").join("not_exists.xlsx").strpath
  430. reasons = dn._upload(not_exists_xlsx_path, upload_checker=check_data_column)
  431. assert bool(reasons) is False
  432. assert (
  433. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.xlsx can not be read,"
  434. f' therefore is not a valid data file for data node "{dn.id}"'
  435. )
  436. not_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsm").strpath
  437. old_data.to_excel(not_xlsx_path, index=False)
  438. # The upload should fail when the file is not a xlsx
  439. reasons = dn._upload(not_xlsx_path, upload_checker=check_data_column)
  440. assert bool(reasons) is False
  441. assert (
  442. str(list(reasons._reasons[dn.id])[0])
  443. == f'The uploaded file wrong_format_df.xlsm has invalid data for data node "{dn.id}"'
  444. )
  445. wrong_format_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsx").strpath
  446. pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]).to_excel(wrong_format_xlsx_path, index=False)
  447. # The upload should fail when check_data_column() return False
  448. reasons = dn._upload(wrong_format_xlsx_path, upload_checker=check_data_column)
  449. assert bool(reasons) is False
  450. assert (
  451. str(list(reasons._reasons[dn.id])[0])
  452. == f'The uploaded file wrong_format_df.xlsx has invalid data for data node "{dn.id}"'
  453. )
  454. assert_frame_equal(dn.read()["Sheet1"], old_data) # The content of the dn should not change when upload fails
  455. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  456. assert dn.path == old_xlsx_path # The path of the dn should not change
  457. # The upload should succeed when check_data_column() return True
  458. assert dn._upload(excel_file, upload_checker=check_data_column)
  459. def test_upload_with_upload_check_numpy(self, tmpdir_factory):
  460. old_excel_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  461. old_data = np.array([[1, 2, 3], [4, 5, 6]])
  462. new_excel_path = tmpdir_factory.mktemp("data").join("new_upload_data.xlsx").strpath
  463. new_data = np.array([[1, 2, 3], [4, 5, 6]])
  464. pd.DataFrame(new_data).to_excel(new_excel_path, index=False)
  465. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_excel_path, "exposed_type": "numpy"})
  466. dn.write(old_data)
  467. old_last_edit_date = dn.last_edit_date
  468. def check_data_is_positive(upload_path, upload_data):
  469. return upload_path.endswith(".xlsx") and np.all(upload_data["Sheet1"] > 0)
  470. not_exists_xlsx_path = tmpdir_factory.mktemp("data").join("not_exists.xlsx").strpath
  471. reasons = dn._upload(not_exists_xlsx_path, upload_checker=check_data_is_positive)
  472. assert bool(reasons) is False
  473. assert (
  474. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.xlsx can not be read,"
  475. f' therefore is not a valid data file for data node "{dn.id}"'
  476. )
  477. wrong_format_not_excel_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsm").strpath
  478. pd.DataFrame(old_data).to_excel(wrong_format_not_excel_path, index=False)
  479. # The upload should fail when the file is not a excel
  480. reasons = dn._upload(wrong_format_not_excel_path, upload_checker=check_data_is_positive)
  481. assert bool(reasons) is False
  482. assert (
  483. str(list(reasons._reasons[dn.id])[0])
  484. == f'The uploaded file wrong_format_df.xlsm has invalid data for data node "{dn.id}"'
  485. )
  486. not_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsx").strpath
  487. pd.DataFrame(np.array([[-1, 2, 3], [-4, -5, -6]])).to_excel(not_xlsx_path, index=False)
  488. # The upload should fail when check_data_is_positive() return False
  489. reasons = dn._upload(not_xlsx_path, upload_checker=check_data_is_positive)
  490. assert (
  491. str(list(reasons._reasons[dn.id])[0])
  492. == f'The uploaded file wrong_format_df.xlsx has invalid data for data node "{dn.id}"'
  493. )
  494. np.array_equal(dn.read()["Sheet1"], old_data) # The content of the dn should not change when upload fails
  495. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  496. assert dn.path == old_excel_path # The path of the dn should not change
  497. # The upload should succeed when check_data_is_positive() return True
  498. assert dn._upload(new_excel_path, upload_checker=check_data_is_positive)