test_excel_data_node.py 25 KB

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