test_excel_data_node.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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(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(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(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(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(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. _DataManagerFactory._build_manager()._repository._save(dn)
  151. assert dn.path == "foo.xlsx"
  152. dn.path = "bar.xlsx"
  153. assert dn.path == "bar.xlsx"
  154. @pytest.mark.parametrize(
  155. ["properties", "exists"],
  156. [
  157. ({"default_data": {"a": ["foo", "bar"]}}, True),
  158. ({}, False),
  159. ],
  160. )
  161. def test_create_with_default_data(self, properties, exists):
  162. dn = ExcelDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  163. assert dn.path == f"{Config.core.storage_folder}excels/{dn.id}.xlsx"
  164. assert os.path.exists(dn.path) is exists
  165. def test_read_write_after_modify_path(self):
  166. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  167. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.xlsx")
  168. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  169. _DataManagerFactory._build_manager()._repository._save(dn)
  170. read_data = dn.read()
  171. assert read_data is not None
  172. dn.path = new_path
  173. with pytest.raises(FileNotFoundError):
  174. dn.read()
  175. dn.write(read_data)
  176. for sheet, df in dn.read().items():
  177. assert np.array_equal(df.values, read_data[sheet].values)
  178. def test_exposed_type_custom_class_after_modify_path(self):
  179. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  180. new_path = os.path.join(
  181. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  182. ) # ["Sheet1", "Sheet2", "Sheet3"]
  183. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": MyCustomObject1})
  184. _DataManagerFactory._build_manager()._repository._save(dn)
  185. assert dn.properties["exposed_type"] == MyCustomObject1
  186. dn.read()
  187. dn.path = new_path
  188. dn.read()
  189. dn = ExcelDataNode(
  190. "foo",
  191. Scope.SCENARIO,
  192. properties={"default_path": path, "exposed_type": MyCustomObject1, "sheet_name": ["Sheet4"]},
  193. )
  194. assert dn.properties["exposed_type"] == MyCustomObject1
  195. with pytest.raises(NonExistingExcelSheet):
  196. dn.read()
  197. def test_exposed_type_dict(self):
  198. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  199. dn = ExcelDataNode(
  200. "foo",
  201. Scope.SCENARIO,
  202. properties={
  203. "default_path": path,
  204. "exposed_type": {
  205. "Sheet1": MyCustomObject1,
  206. "Sheet2": MyCustomObject2,
  207. "Sheet3": MyCustomObject1,
  208. },
  209. },
  210. )
  211. data = dn.read()
  212. assert isinstance(data, Dict)
  213. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  214. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  215. def test_exposed_type_list(self):
  216. path_1 = os.path.join(
  217. pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx"
  218. ) # ["Sheet1", "Sheet2"]
  219. path_2 = os.path.join(
  220. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  221. ) # ["Sheet1", "Sheet2", "Sheet3"]
  222. dn = ExcelDataNode(
  223. "foo",
  224. Scope.SCENARIO,
  225. properties={"default_path": path_1, "exposed_type": [MyCustomObject1, MyCustomObject2]},
  226. )
  227. _DataManagerFactory._build_manager()._repository._save(dn)
  228. data = dn.read()
  229. assert isinstance(data, Dict)
  230. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  231. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  232. dn.path = path_2
  233. with pytest.raises(ExposedTypeLengthMismatch):
  234. dn.read()
  235. def test_not_trying_to_read_sheet_names_when_exposed_type_is_set(self):
  236. dn = ExcelDataNode(
  237. "foo", Scope.SCENARIO, properties={"default_path": "notexistyet.xlsx", "exposed_type": MyCustomObject1}
  238. )
  239. assert dn.path == "notexistyet.xlsx"
  240. assert dn.properties["exposed_type"] == MyCustomObject1
  241. dn = ExcelDataNode(
  242. "foo",
  243. Scope.SCENARIO,
  244. properties={"default_path": "notexistyet.xlsx", "exposed_type": [MyCustomObject1, MyCustomObject2]},
  245. )
  246. assert dn.path == "notexistyet.xlsx"
  247. assert dn.properties["exposed_type"] == [MyCustomObject1, MyCustomObject2]
  248. dn = ExcelDataNode(
  249. "foo",
  250. Scope.SCENARIO,
  251. properties={
  252. "default_path": "notexistyet.xlsx",
  253. "exposed_type": {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2},
  254. },
  255. )
  256. assert dn.path == "notexistyet.xlsx"
  257. assert dn.properties["exposed_type"] == {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2}
  258. def test_exposed_type_default(self):
  259. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  260. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "sheet_name": "Sheet1"})
  261. assert dn.properties["exposed_type"] == "pandas"
  262. data = dn.read()
  263. assert isinstance(data, pd.DataFrame)
  264. def test_pandas_exposed_type(self):
  265. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  266. dn = ExcelDataNode(
  267. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": "pandas", "sheet_name": "Sheet1"}
  268. )
  269. assert dn.properties["exposed_type"] == "pandas"
  270. data = dn.read()
  271. assert isinstance(data, pd.DataFrame)
  272. def test_pandas_dataframe_exposed_type(self):
  273. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  274. dn = ExcelDataNode(
  275. "foo",
  276. Scope.SCENARIO,
  277. properties={"default_path": path, "exposed_type": pd.DataFrame, "sheet_name": "Sheet1"},
  278. )
  279. assert dn.properties["exposed_type"] == pd.DataFrame
  280. data = dn.read()
  281. assert isinstance(data, pd.DataFrame)
  282. def test_pandas_dataframe_exposed_type_a(self):
  283. import pandas
  284. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  285. dn = ExcelDataNode(
  286. "foo",
  287. Scope.SCENARIO,
  288. properties={"default_path": path, "exposed_type": pandas.DataFrame, "sheet_name": "Sheet1"},
  289. )
  290. assert dn.properties["exposed_type"] == pandas.DataFrame
  291. data = dn.read()
  292. assert isinstance(data, pandas.DataFrame)
  293. def test_pandas_dataframe_exposed_type_b(self):
  294. from pandas import DataFrame
  295. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  296. dn = ExcelDataNode(
  297. "foo",
  298. Scope.SCENARIO,
  299. properties={"default_path": path, "exposed_type": DataFrame, "sheet_name": "Sheet1"},
  300. )
  301. assert dn.properties["exposed_type"] == DataFrame
  302. data = dn.read()
  303. assert isinstance(data, DataFrame)
  304. def test_pandas_dataframe_exposed_type_c(self):
  305. from pandas import DataFrame as DF
  306. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  307. dn = ExcelDataNode(
  308. "foo",
  309. Scope.SCENARIO,
  310. properties={"default_path": path, "exposed_type": DF, "sheet_name": "Sheet1"},
  311. )
  312. assert dn.properties["exposed_type"] == DF
  313. data = dn.read()
  314. assert isinstance(data, DF)
  315. def test_numpy_ndarray_exposed_type(self):
  316. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  317. dn = ExcelDataNode(
  318. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": np.ndarray, "sheet_name": "Sheet1"}
  319. )
  320. assert dn.properties["exposed_type"] == np.ndarray
  321. data = dn.read()
  322. assert isinstance(data, np.ndarray)
  323. def test_numpy_ndarray_exposed_type_a(self):
  324. import numpy
  325. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  326. dn = ExcelDataNode(
  327. "foo",
  328. Scope.SCENARIO,
  329. properties={"default_path": path, "exposed_type": numpy.ndarray, "sheet_name": "Sheet1"},
  330. )
  331. assert dn.properties["exposed_type"] == numpy.ndarray
  332. data = dn.read()
  333. assert isinstance(data, numpy.ndarray)
  334. def test_numpy_ndarray_exposed_type_b(self):
  335. from numpy import ndarray
  336. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  337. dn = ExcelDataNode(
  338. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": ndarray, "sheet_name": "Sheet1"}
  339. )
  340. assert dn.properties["exposed_type"] == ndarray
  341. data = dn.read()
  342. assert isinstance(data, ndarray)
  343. def test_numpy_ndarray_exposed_type_c(self):
  344. from numpy import ndarray as nd_array
  345. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  346. dn = ExcelDataNode(
  347. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": nd_array, "sheet_name": "Sheet1"}
  348. )
  349. assert dn.properties["exposed_type"] == nd_array
  350. data = dn.read()
  351. assert isinstance(data, nd_array)
  352. def test_complex_exposed_type_dict(self):
  353. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5"]
  354. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  355. dn = ExcelDataNode(
  356. "foo",
  357. Scope.SCENARIO,
  358. properties={
  359. "default_path": path,
  360. "exposed_type": {
  361. "Sheet1": MyCustomObject1,
  362. "Sheet2": "numpy",
  363. "Sheet3": "pandas",
  364. },
  365. "sheet_name": ["Sheet1", "Sheet2", "Sheet3", "Sheet4"],
  366. },
  367. )
  368. data = dn.read()
  369. assert isinstance(data, dict)
  370. assert isinstance(data["Sheet1"], list)
  371. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  372. assert isinstance(data["Sheet2"], np.ndarray)
  373. assert isinstance(data["Sheet3"], pd.DataFrame)
  374. assert isinstance(data["Sheet4"], pd.DataFrame)
  375. assert data.get("Sheet5") is None
  376. def test_complex_exposed_type_list(self):
  377. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4","Sheet5"]
  378. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  379. dn = ExcelDataNode(
  380. "foo",
  381. Scope.SCENARIO,
  382. properties={
  383. "default_path": path,
  384. "exposed_type": [MyCustomObject1, "numpy", "pandas"],
  385. "sheet_name": ["Sheet1", "Sheet2", "Sheet3"],
  386. },
  387. )
  388. data = dn.read()
  389. assert isinstance(data, dict)
  390. assert isinstance(data["Sheet1"], list)
  391. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  392. assert isinstance(data["Sheet2"], np.ndarray)
  393. assert isinstance(data["Sheet3"], pd.DataFrame)
  394. def test_invalid_exposed_type(self):
  395. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  396. with pytest.raises(InvalidExposedType):
  397. ExcelDataNode(
  398. "foo",
  399. Scope.SCENARIO,
  400. properties={"default_path": path, "exposed_type": "invalid", "sheet_name": "Sheet1"},
  401. )
  402. with pytest.raises(InvalidExposedType):
  403. ExcelDataNode(
  404. "foo",
  405. Scope.SCENARIO,
  406. properties={
  407. "default_path": path,
  408. "exposed_type": ["numpy", "invalid", "pandas"],
  409. "sheet_name": "Sheet1",
  410. },
  411. )
  412. with pytest.raises(InvalidExposedType):
  413. ExcelDataNode(
  414. "foo",
  415. Scope.SCENARIO,
  416. properties={
  417. "default_path": path,
  418. "exposed_type": {"Sheet1": "pandas", "Sheet2": "invalid"},
  419. "sheet_name": "Sheet1",
  420. },
  421. )
  422. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  423. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.xlsx"))
  424. pd.DataFrame([]).to_excel(temp_file_path)
  425. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  426. _DataManagerFactory._build_manager()._repository._save(dn)
  427. dn.write(pd.DataFrame([1, 2, 3]))
  428. previous_edit_date = dn.last_edit_date
  429. sleep(0.1)
  430. pd.DataFrame([4, 5, 6]).to_excel(temp_file_path)
  431. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  432. assert previous_edit_date < dn.last_edit_date
  433. assert new_edit_date == dn.last_edit_date
  434. sleep(0.1)
  435. dn.write(pd.DataFrame([7, 8, 9]))
  436. assert new_edit_date < dn.last_edit_date
  437. os.unlink(temp_file_path)
  438. def test_migrate_to_new_path(self, tmp_path):
  439. _base_path = os.path.join(tmp_path, ".data")
  440. path = os.path.join(_base_path, "test.xlsx")
  441. # create a file on old path
  442. os.mkdir(_base_path)
  443. with open(path, "w"):
  444. pass
  445. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  446. assert ".data" not in dn.path
  447. assert os.path.exists(dn.path)
  448. def test_is_downloadable(self):
  449. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  450. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  451. reasons = dn.is_downloadable()
  452. assert reasons
  453. assert reasons.reasons == ""
  454. def test_is_not_downloadable_no_file(self):
  455. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/wrong_path.xlsx")
  456. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  457. reasons = dn.is_downloadable()
  458. assert not reasons
  459. assert len(reasons._reasons) == 1
  460. assert str(NoFileToDownload(_normalize_path(path), dn.id)) in reasons.reasons
  461. def test_is_not_downloadable_not_a_file(self):
  462. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample")
  463. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  464. reasons = dn.is_downloadable()
  465. assert not reasons
  466. assert len(reasons._reasons) == 1
  467. assert str(NotAFile(_normalize_path(path), dn.id)) in reasons.reasons
  468. def test_get_download_path(self):
  469. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  470. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  471. assert re.split(r"[\\/]", dn._get_downloadable_path()) == re.split(r"[\\/]", path)
  472. def test_get_downloadable_path_with_not_existing_file(self):
  473. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTING.xlsx", "exposed_type": "pandas"})
  474. assert dn._get_downloadable_path() == ""
  475. def test_upload(self, excel_file, tmpdir_factory):
  476. old_xlsx_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  477. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  478. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_xlsx_path, "exposed_type": "pandas"})
  479. _DataManagerFactory._build_manager()._repository._save(dn)
  480. dn.write(old_data)
  481. old_last_edit_date = dn.last_edit_date
  482. upload_content = pd.read_excel(excel_file)
  483. with freezegun.freeze_time(old_last_edit_date + timedelta(seconds=1)):
  484. dn._upload(excel_file)
  485. assert_frame_equal(dn.read()["Sheet1"], upload_content) # The data of dn should change to the uploaded content
  486. assert dn.last_edit_date > old_last_edit_date
  487. assert dn.path == _normalize_path(old_xlsx_path) # The path of the dn should not change
  488. def test_upload_with_upload_check_pandas(self, excel_file, tmpdir_factory):
  489. old_xlsx_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  490. old_data = pd.DataFrame([{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}])
  491. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_xlsx_path, "exposed_type": "pandas"})
  492. _DataManagerFactory._build_manager()._repository._save(dn)
  493. dn.write(old_data)
  494. old_last_edit_date = dn.last_edit_date
  495. def check_data_column(upload_path, upload_data):
  496. """Check if the uploaded data has the correct file format and
  497. the sheet named "Sheet1" has the correct columns.
  498. """
  499. return upload_path.endswith(".xlsx") and upload_data["Sheet1"].columns.tolist() == ["a", "b", "c"]
  500. not_exists_xlsx_path = tmpdir_factory.mktemp("data").join("not_exists.xlsx").strpath
  501. reasons = dn._upload(not_exists_xlsx_path, upload_checker=check_data_column)
  502. assert bool(reasons) is False
  503. assert (
  504. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file 'not_exists.xlsx' can not be read,"
  505. f" therefore is not a valid data file for data node '{dn.id}'"
  506. )
  507. not_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsm").strpath
  508. old_data.to_excel(not_xlsx_path, index=False)
  509. # The upload should fail when the file is not a xlsx
  510. reasons = dn._upload(not_xlsx_path, upload_checker=check_data_column)
  511. assert bool(reasons) is False
  512. assert (
  513. str(list(reasons._reasons[dn.id])[0])
  514. == f"The uploaded file 'wrong_format_df.xlsm' has invalid data for data node '{dn.id}'"
  515. )
  516. wrong_format_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsx").strpath
  517. pd.DataFrame([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}]).to_excel(wrong_format_xlsx_path, index=False)
  518. # The upload should fail when check_data_column() return False
  519. reasons = dn._upload(wrong_format_xlsx_path, upload_checker=check_data_column)
  520. assert bool(reasons) is False
  521. assert (
  522. str(list(reasons._reasons[dn.id])[0])
  523. == f"The uploaded file 'wrong_format_df.xlsx' has invalid data for data node '{dn.id}'"
  524. )
  525. assert_frame_equal(dn.read()["Sheet1"], old_data) # The content of the dn should not change when upload fails
  526. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  527. assert dn.path == _normalize_path(old_xlsx_path) # The path of the dn should not change
  528. # The upload should succeed when check_data_column() return True
  529. assert dn._upload(excel_file, upload_checker=check_data_column)
  530. def test_upload_with_upload_check_numpy(self, tmpdir_factory):
  531. old_excel_path = tmpdir_factory.mktemp("data").join("df.xlsx").strpath
  532. old_data = np.array([[1, 2, 3], [4, 5, 6]])
  533. new_excel_path = tmpdir_factory.mktemp("data").join("new_upload_data.xlsx").strpath
  534. new_data = np.array([[1, 2, 3], [4, 5, 6]])
  535. pd.DataFrame(new_data).to_excel(new_excel_path, index=False)
  536. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": old_excel_path, "exposed_type": "numpy"})
  537. _DataManagerFactory._build_manager()._repository._save(dn)
  538. dn.write(old_data)
  539. old_last_edit_date = dn.last_edit_date
  540. def check_data_is_positive(upload_path, upload_data):
  541. return upload_path.endswith(".xlsx") and np.all(upload_data["Sheet1"] > 0)
  542. not_exists_xlsx_path = tmpdir_factory.mktemp("data").join("not_exists.xlsx").strpath
  543. reasons = dn._upload(not_exists_xlsx_path, upload_checker=check_data_is_positive)
  544. assert bool(reasons) is False
  545. assert (
  546. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file 'not_exists.xlsx' can not be read,"
  547. f" therefore is not a valid data file for data node '{dn.id}'"
  548. )
  549. wrong_format_not_excel_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsm").strpath
  550. pd.DataFrame(old_data).to_excel(wrong_format_not_excel_path, index=False)
  551. # The upload should fail when the file is not an Excel
  552. reasons = dn._upload(wrong_format_not_excel_path, upload_checker=check_data_is_positive)
  553. assert bool(reasons) is False
  554. assert (
  555. str(list(reasons._reasons[dn.id])[0])
  556. == f"The uploaded file 'wrong_format_df.xlsm' has invalid data for data node '{dn.id}'"
  557. )
  558. not_xlsx_path = tmpdir_factory.mktemp("data").join("wrong_format_df.xlsx").strpath
  559. pd.DataFrame(np.array([[-1, 2, 3], [-4, -5, -6]])).to_excel(not_xlsx_path, index=False)
  560. # The upload should fail when check_data_is_positive() return False
  561. reasons = dn._upload(not_xlsx_path, upload_checker=check_data_is_positive)
  562. assert (
  563. str(list(reasons._reasons[dn.id])[0])
  564. == f"The uploaded file 'wrong_format_df.xlsx' has invalid data for data node '{dn.id}'"
  565. )
  566. np.array_equal(dn.read()["Sheet1"], old_data) # The content of the dn should not change when upload fails
  567. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  568. assert dn.path == _normalize_path(old_excel_path) # The path of the dn should not change
  569. # The upload should succeed when check_data_is_positive() return True
  570. assert dn._upload(new_excel_path, upload_checker=check_data_is_positive)