test_excel_data_node.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import os
  12. import pathlib
  13. import uuid
  14. from datetime import datetime
  15. from time import sleep
  16. from typing import Dict
  17. import numpy as np
  18. import pandas as pd
  19. import pytest
  20. from taipy.config.common.scope import Scope
  21. from taipy.config.config import Config
  22. from taipy.core.data._data_manager import _DataManager
  23. from taipy.core.data._data_manager_factory import _DataManagerFactory
  24. from taipy.core.data.data_node_id import DataNodeId
  25. from taipy.core.data.excel import ExcelDataNode
  26. from taipy.core.exceptions.exceptions import (
  27. ExposedTypeLengthMismatch,
  28. InvalidExposedType,
  29. NonExistingExcelSheet,
  30. )
  31. @pytest.fixture(scope="function", autouse=True)
  32. def cleanup():
  33. yield
  34. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.xlsx")
  35. if os.path.exists(path):
  36. os.remove(path)
  37. class MyCustomObject:
  38. def __init__(self, id, integer, text):
  39. self.id = id
  40. self.integer = integer
  41. self.text = text
  42. class MyCustomObject1:
  43. def __init__(self, id, integer, text):
  44. self.id = id
  45. self.integer = integer
  46. self.text = text
  47. class MyCustomObject2:
  48. def __init__(self, id, integer, text):
  49. self.id = id
  50. self.integer = integer
  51. self.text = text
  52. class TestExcelDataNode:
  53. def test_new_excel_data_node_with_existing_file_is_ready_for_reading(self):
  54. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "excel", path="NOT_EXISTING.csv")
  55. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  56. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "excel", path=path)
  57. dns = _DataManager._bulk_get_or_create([not_ready_dn_cfg, ready_dn_cfg])
  58. assert not dns[not_ready_dn_cfg].is_ready_for_reading
  59. assert dns[ready_dn_cfg].is_ready_for_reading
  60. def test_create(self):
  61. path = "data/node/path"
  62. sheet_names = ["sheet_name_1", "sheet_name_2"]
  63. excel_dn_config = Config.configure_excel_data_node(
  64. id="foo_bar", default_path=path, has_header=False, sheet_name="Sheet1", name="super name"
  65. )
  66. dn = _DataManagerFactory._build_manager()._create_and_set(excel_dn_config, None, None)
  67. assert isinstance(dn, ExcelDataNode)
  68. assert dn.storage_type() == "excel"
  69. assert dn.config_id == "foo_bar"
  70. assert dn.name == "super name"
  71. assert dn.scope == Scope.SCENARIO
  72. assert dn.id is not None
  73. assert dn.owner_id is None
  74. assert dn.parent_ids == set()
  75. assert dn.last_edit_date is None
  76. assert dn.job_ids == []
  77. assert not dn.is_ready_for_reading
  78. assert dn.path == path
  79. assert dn.has_header is False
  80. assert dn.sheet_name == "Sheet1"
  81. excel_dn_config_1 = Config.configure_excel_data_node(
  82. id="baz", default_path=path, has_header=True, sheet_name="Sheet1", exposed_type=MyCustomObject
  83. )
  84. dn_1 = _DataManagerFactory._build_manager()._create_and_set(excel_dn_config_1, None, None)
  85. assert isinstance(dn_1, ExcelDataNode)
  86. assert dn_1.has_header is True
  87. assert dn_1.sheet_name == "Sheet1"
  88. assert dn_1.exposed_type == MyCustomObject
  89. excel_dn_config_2 = Config.configure_excel_data_node(
  90. id="baz",
  91. default_path=path,
  92. has_header=True,
  93. sheet_name=sheet_names,
  94. exposed_type={"Sheet1": "pandas", "Sheet2": "numpy"},
  95. )
  96. dn_2 = _DataManagerFactory._build_manager()._create_and_set(excel_dn_config_2, None, None)
  97. assert isinstance(dn_2, ExcelDataNode)
  98. assert dn_2.sheet_name == sheet_names
  99. assert dn_2.exposed_type == {"Sheet1": "pandas", "Sheet2": "numpy"}
  100. excel_dn_config_3 = Config.configure_excel_data_node(
  101. id="baz", default_path=path, has_header=True, sheet_name=sheet_names, exposed_type=MyCustomObject
  102. )
  103. dn_3 = _DataManagerFactory._build_manager()._create_and_set(excel_dn_config_3, None, None)
  104. assert isinstance(dn_3, ExcelDataNode)
  105. assert dn_3.sheet_name == sheet_names
  106. assert dn_3.exposed_type == MyCustomObject
  107. excel_dn_config_4 = Config.configure_excel_data_node(
  108. id="baz",
  109. default_path=path,
  110. has_header=True,
  111. sheet_name=sheet_names,
  112. exposed_type={"Sheet1": MyCustomObject, "Sheet2": MyCustomObject2},
  113. )
  114. dn_4 = _DataManagerFactory._build_manager()._create_and_set(excel_dn_config_4, None, None)
  115. assert isinstance(dn_4, ExcelDataNode)
  116. assert dn_4.sheet_name == sheet_names
  117. assert dn_4.exposed_type == {"Sheet1": MyCustomObject, "Sheet2": MyCustomObject2}
  118. def test_get_user_properties(self, excel_file):
  119. dn_1 = ExcelDataNode("dn_1", Scope.SCENARIO, properties={"path": "data/node/path"})
  120. assert dn_1._get_user_properties() == {}
  121. dn_2 = ExcelDataNode(
  122. "dn_2",
  123. Scope.SCENARIO,
  124. properties={
  125. "exposed_type": "numpy",
  126. "default_data": "foo",
  127. "default_path": excel_file,
  128. "has_header": False,
  129. "sheet_name": ["sheet_name_1", "sheet_name_2"],
  130. "foo": "bar",
  131. },
  132. )
  133. # exposed_type, default_data, default_path, path, has_header are filtered out
  134. assert dn_2._get_user_properties() == {"foo": "bar"}
  135. def test_modin_deprecated_in_favor_of_pandas(self):
  136. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  137. # Create ExcelDataNode with modin exposed_type
  138. props = {"path": path, "sheet_name": "Sheet1", "exposed_type": "modin"}
  139. modin_dn = ExcelDataNode("bar", Scope.SCENARIO, properties=props)
  140. assert modin_dn.properties["exposed_type"] == "pandas"
  141. data_modin = modin_dn.read()
  142. assert isinstance(data_modin, pd.DataFrame)
  143. def test_set_path(self):
  144. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.xlsx"})
  145. assert dn.path == "foo.xlsx"
  146. dn.path = "bar.xlsx"
  147. assert dn.path == "bar.xlsx"
  148. @pytest.mark.parametrize(
  149. ["properties", "exists"],
  150. [
  151. ({"default_data": {"a": ["foo", "bar"]}}, True),
  152. ({}, False),
  153. ],
  154. )
  155. def test_create_with_default_data(self, properties, exists):
  156. dn = ExcelDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  157. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "excels", dn.id + ".xlsx")
  158. assert os.path.exists(dn.path) is exists
  159. def test_read_write_after_modify_path(self):
  160. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  161. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.xlsx")
  162. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  163. read_data = dn.read()
  164. assert read_data is not None
  165. dn.path = new_path
  166. with pytest.raises(FileNotFoundError):
  167. dn.read()
  168. dn.write(read_data)
  169. for sheet, df in dn.read().items():
  170. assert np.array_equal(df.values, read_data[sheet].values)
  171. def test_exposed_type_custom_class_after_modify_path(self):
  172. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  173. new_path = os.path.join(
  174. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  175. ) # ["Sheet1", "Sheet2", "Sheet3"]
  176. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": MyCustomObject1})
  177. assert dn.exposed_type == MyCustomObject1
  178. dn.read()
  179. dn.path = new_path
  180. dn.read()
  181. dn = ExcelDataNode(
  182. "foo",
  183. Scope.SCENARIO,
  184. properties={"default_path": path, "exposed_type": MyCustomObject1, "sheet_name": ["Sheet4"]},
  185. )
  186. assert dn.exposed_type == MyCustomObject1
  187. with pytest.raises(NonExistingExcelSheet):
  188. dn.read()
  189. def test_exposed_type_dict(self):
  190. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  191. dn = ExcelDataNode(
  192. "foo",
  193. Scope.SCENARIO,
  194. properties={
  195. "default_path": path,
  196. "exposed_type": {
  197. "Sheet1": MyCustomObject1,
  198. "Sheet2": MyCustomObject2,
  199. "Sheet3": MyCustomObject1,
  200. },
  201. },
  202. )
  203. data = dn.read()
  204. assert isinstance(data, Dict)
  205. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  206. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  207. def test_exposed_type_list(self):
  208. path_1 = os.path.join(
  209. pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx"
  210. ) # ["Sheet1", "Sheet2"]
  211. path_2 = os.path.join(
  212. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  213. ) # ["Sheet1", "Sheet2", "Sheet3"]
  214. dn = ExcelDataNode(
  215. "foo",
  216. Scope.SCENARIO,
  217. properties={"default_path": path_1, "exposed_type": [MyCustomObject1, MyCustomObject2]},
  218. )
  219. data = dn.read()
  220. assert isinstance(data, Dict)
  221. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  222. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  223. dn.path = path_2
  224. with pytest.raises(ExposedTypeLengthMismatch):
  225. dn.read()
  226. def test_not_trying_to_read_sheet_names_when_exposed_type_is_set(self):
  227. dn = ExcelDataNode(
  228. "foo", Scope.SCENARIO, properties={"default_path": "notexistyet.xlsx", "exposed_type": MyCustomObject1}
  229. )
  230. assert dn.path == "notexistyet.xlsx"
  231. assert dn.exposed_type == MyCustomObject1
  232. dn = ExcelDataNode(
  233. "foo",
  234. Scope.SCENARIO,
  235. properties={"default_path": "notexistyet.xlsx", "exposed_type": [MyCustomObject1, MyCustomObject2]},
  236. )
  237. assert dn.path == "notexistyet.xlsx"
  238. assert dn.exposed_type == [MyCustomObject1, MyCustomObject2]
  239. dn = ExcelDataNode(
  240. "foo",
  241. Scope.SCENARIO,
  242. properties={
  243. "default_path": "notexistyet.xlsx",
  244. "exposed_type": {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2},
  245. },
  246. )
  247. assert dn.path == "notexistyet.xlsx"
  248. assert dn.exposed_type == {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2}
  249. def test_exposed_type_default(self):
  250. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  251. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "sheet_name": "Sheet1"})
  252. assert dn.exposed_type == "pandas"
  253. data = dn.read()
  254. assert isinstance(data, pd.DataFrame)
  255. def test_pandas_exposed_type(self):
  256. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  257. dn = ExcelDataNode(
  258. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": "pandas", "sheet_name": "Sheet1"}
  259. )
  260. assert dn.exposed_type == "pandas"
  261. data = dn.read()
  262. assert isinstance(data, pd.DataFrame)
  263. def test_complex_exposed_type_dict(self):
  264. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5"]
  265. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  266. dn = ExcelDataNode(
  267. "foo",
  268. Scope.SCENARIO,
  269. properties={
  270. "default_path": path,
  271. "exposed_type": {
  272. "Sheet1": MyCustomObject1,
  273. "Sheet2": "numpy",
  274. "Sheet3": "pandas",
  275. },
  276. "sheet_name": ["Sheet1", "Sheet2", "Sheet3", "Sheet4"],
  277. },
  278. )
  279. data = dn.read()
  280. assert isinstance(data, dict)
  281. assert isinstance(data["Sheet1"], list)
  282. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  283. assert isinstance(data["Sheet2"], np.ndarray)
  284. assert isinstance(data["Sheet3"], pd.DataFrame)
  285. assert isinstance(data["Sheet4"], pd.DataFrame)
  286. assert data.get("Sheet5") is None
  287. def test_complex_exposed_type_list(self):
  288. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4","Sheet5"]
  289. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  290. dn = ExcelDataNode(
  291. "foo",
  292. Scope.SCENARIO,
  293. properties={
  294. "default_path": path,
  295. "exposed_type": [MyCustomObject1, "numpy", "pandas"],
  296. "sheet_name": ["Sheet1", "Sheet2", "Sheet3"],
  297. },
  298. )
  299. data = dn.read()
  300. assert isinstance(data, dict)
  301. assert isinstance(data["Sheet1"], list)
  302. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  303. assert isinstance(data["Sheet2"], np.ndarray)
  304. assert isinstance(data["Sheet3"], pd.DataFrame)
  305. def test_invalid_exposed_type(self):
  306. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  307. with pytest.raises(InvalidExposedType):
  308. ExcelDataNode(
  309. "foo",
  310. Scope.SCENARIO,
  311. properties={"default_path": path, "exposed_type": "invalid", "sheet_name": "Sheet1"},
  312. )
  313. with pytest.raises(InvalidExposedType):
  314. ExcelDataNode(
  315. "foo",
  316. Scope.SCENARIO,
  317. properties={
  318. "default_path": path,
  319. "exposed_type": ["numpy", "invalid", "pandas"],
  320. "sheet_name": "Sheet1",
  321. },
  322. )
  323. with pytest.raises(InvalidExposedType):
  324. ExcelDataNode(
  325. "foo",
  326. Scope.SCENARIO,
  327. properties={
  328. "default_path": path,
  329. "exposed_type": {"Sheet1": "pandas", "Sheet2": "invalid"},
  330. "sheet_name": "Sheet1",
  331. },
  332. )
  333. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  334. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.xlsx"))
  335. pd.DataFrame([]).to_excel(temp_file_path)
  336. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  337. dn.write(pd.DataFrame([1, 2, 3]))
  338. previous_edit_date = dn.last_edit_date
  339. sleep(0.1)
  340. pd.DataFrame([4, 5, 6]).to_excel(temp_file_path)
  341. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  342. assert previous_edit_date < dn.last_edit_date
  343. assert new_edit_date == dn.last_edit_date
  344. sleep(0.1)
  345. dn.write(pd.DataFrame([7, 8, 9]))
  346. assert new_edit_date < dn.last_edit_date
  347. os.unlink(temp_file_path)
  348. def test_migrate_to_new_path(self, tmp_path):
  349. _base_path = os.path.join(tmp_path, ".data")
  350. path = os.path.join(_base_path, "test.xlsx")
  351. # create a file on old path
  352. os.mkdir(_base_path)
  353. with open(path, "w"):
  354. pass
  355. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  356. assert ".data" not in dn.path
  357. assert os.path.exists(dn.path)