test_excel_data_node.py 24 KB

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