1
0

test_excel_data_node.py 28 KB

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