test_excel_data_node.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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_node_id import DataNodeId
  24. from taipy.core.data.excel import ExcelDataNode
  25. from taipy.core.exceptions.exceptions import (
  26. ExposedTypeLengthMismatch,
  27. InvalidExposedType,
  28. NonExistingExcelSheet,
  29. )
  30. @pytest.fixture(scope="function", autouse=True)
  31. def cleanup():
  32. yield
  33. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.xlsx")
  34. if os.path.exists(path):
  35. os.remove(path)
  36. class MyCustomObject:
  37. def __init__(self, id, integer, text):
  38. self.id = id
  39. self.integer = integer
  40. self.text = text
  41. class MyCustomObject1:
  42. def __init__(self, id, integer, text):
  43. self.id = id
  44. self.integer = integer
  45. self.text = text
  46. class MyCustomObject2:
  47. def __init__(self, id, integer, text):
  48. self.id = id
  49. self.integer = integer
  50. self.text = text
  51. class TestExcelDataNode:
  52. def test_new_excel_data_node_with_existing_file_is_ready_for_reading(self):
  53. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "excel", path="NOT_EXISTING.csv")
  54. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  55. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "excel", path=path)
  56. dns = _DataManager._bulk_get_or_create([not_ready_dn_cfg, ready_dn_cfg])
  57. assert not dns[not_ready_dn_cfg].is_ready_for_reading
  58. assert dns[ready_dn_cfg].is_ready_for_reading
  59. def test_create(self):
  60. path = "data/node/path"
  61. sheet_names = ["sheet_name_1", "sheet_name_2"]
  62. dn = ExcelDataNode(
  63. "foo_bar",
  64. Scope.SCENARIO,
  65. properties={"path": path, "has_header": False, "sheet_name": sheet_names, "name": "super name"},
  66. )
  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 == sheet_names
  81. def test_get_user_properties(self, excel_file):
  82. dn_1 = ExcelDataNode("dn_1", Scope.SCENARIO, properties={"path": "data/node/path"})
  83. assert dn_1._get_user_properties() == {}
  84. dn_2 = ExcelDataNode(
  85. "dn_2",
  86. Scope.SCENARIO,
  87. properties={
  88. "exposed_type": "numpy",
  89. "default_data": "foo",
  90. "default_path": excel_file,
  91. "has_header": False,
  92. "sheet_name": ["sheet_name_1", "sheet_name_2"],
  93. "foo": "bar",
  94. },
  95. )
  96. # exposed_type, default_data, default_path, path, has_header are filtered out
  97. assert dn_2._get_user_properties() == {"foo": "bar"}
  98. def test_modin_deprecated_in_favor_of_pandas(self):
  99. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  100. # Create ExcelDataNode with modin exposed_type
  101. props = {"path": path, "sheet_name": "Sheet1", "exposed_type": "modin"}
  102. modin_dn = ExcelDataNode("bar", Scope.SCENARIO, properties=props)
  103. assert modin_dn.properties["exposed_type"] == "pandas"
  104. data_modin = modin_dn.read()
  105. assert isinstance(data_modin, pd.DataFrame)
  106. def test_set_path(self):
  107. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.xlsx"})
  108. assert dn.path == "foo.xlsx"
  109. dn.path = "bar.xlsx"
  110. assert dn.path == "bar.xlsx"
  111. @pytest.mark.parametrize(
  112. ["properties", "exists"],
  113. [
  114. ({"default_data": {"a": ["foo", "bar"]}}, True),
  115. ({}, False),
  116. ],
  117. )
  118. def test_create_with_default_data(self, properties, exists):
  119. dn = ExcelDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  120. assert dn.path == os.path.join(Config.core.storage_folder, "excels", dn.id + ".xlsx")
  121. assert os.path.exists(dn.path) is exists
  122. def test_read_write_after_modify_path(self):
  123. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  124. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.xlsx")
  125. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  126. read_data = dn.read()
  127. assert read_data is not None
  128. dn.path = new_path
  129. with pytest.raises(FileNotFoundError):
  130. dn.read()
  131. dn.write(read_data)
  132. for sheet, df in dn.read().items():
  133. assert np.array_equal(df.values, read_data[sheet].values)
  134. def test_exposed_type_custom_class_after_modify_path(self):
  135. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  136. new_path = os.path.join(
  137. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  138. ) # ["Sheet1", "Sheet2", "Sheet3"]
  139. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": MyCustomObject1})
  140. assert dn.exposed_type == MyCustomObject1
  141. dn.read()
  142. dn.path = new_path
  143. dn.read()
  144. dn = ExcelDataNode(
  145. "foo",
  146. Scope.SCENARIO,
  147. properties={"default_path": path, "exposed_type": MyCustomObject1, "sheet_name": ["Sheet4"]},
  148. )
  149. assert dn.exposed_type == MyCustomObject1
  150. with pytest.raises(NonExistingExcelSheet):
  151. dn.read()
  152. def test_exposed_type_dict(self):
  153. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx") # ["Sheet1", "Sheet2"]
  154. dn = ExcelDataNode(
  155. "foo",
  156. Scope.SCENARIO,
  157. properties={
  158. "default_path": path,
  159. "exposed_type": {
  160. "Sheet1": MyCustomObject1,
  161. "Sheet2": MyCustomObject2,
  162. "Sheet3": MyCustomObject1,
  163. },
  164. },
  165. )
  166. data = dn.read()
  167. assert isinstance(data, Dict)
  168. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  169. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  170. def test_exposed_type_list(self):
  171. path_1 = os.path.join(
  172. pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx"
  173. ) # ["Sheet1", "Sheet2"]
  174. path_2 = os.path.join(
  175. pathlib.Path(__file__).parent.resolve(), "data_sample/example_2.xlsx"
  176. ) # ["Sheet1", "Sheet2", "Sheet3"]
  177. dn = ExcelDataNode(
  178. "foo",
  179. Scope.SCENARIO,
  180. properties={"default_path": path_1, "exposed_type": [MyCustomObject1, MyCustomObject2]},
  181. )
  182. data = dn.read()
  183. assert isinstance(data, Dict)
  184. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  185. assert isinstance(data["Sheet2"][0], MyCustomObject2)
  186. dn.path = path_2
  187. with pytest.raises(ExposedTypeLengthMismatch):
  188. dn.read()
  189. def test_not_trying_to_read_sheet_names_when_exposed_type_is_set(self):
  190. dn = ExcelDataNode(
  191. "foo", Scope.SCENARIO, properties={"default_path": "notexistyet.xlsx", "exposed_type": MyCustomObject1}
  192. )
  193. assert dn.path == "notexistyet.xlsx"
  194. assert dn.exposed_type == MyCustomObject1
  195. dn = ExcelDataNode(
  196. "foo",
  197. Scope.SCENARIO,
  198. properties={"default_path": "notexistyet.xlsx", "exposed_type": [MyCustomObject1, MyCustomObject2]},
  199. )
  200. assert dn.path == "notexistyet.xlsx"
  201. assert dn.exposed_type == [MyCustomObject1, MyCustomObject2]
  202. dn = ExcelDataNode(
  203. "foo",
  204. Scope.SCENARIO,
  205. properties={
  206. "default_path": "notexistyet.xlsx",
  207. "exposed_type": {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2},
  208. },
  209. )
  210. assert dn.path == "notexistyet.xlsx"
  211. assert dn.exposed_type == {"Sheet1": MyCustomObject1, "Sheet2": MyCustomObject2}
  212. def test_exposed_type_default(self):
  213. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  214. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"default_path": path, "sheet_name": "Sheet1"})
  215. assert dn.exposed_type == "pandas"
  216. data = dn.read()
  217. assert isinstance(data, pd.DataFrame)
  218. def test_pandas_exposed_type(self):
  219. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  220. dn = ExcelDataNode(
  221. "foo", Scope.SCENARIO, properties={"default_path": path, "exposed_type": "pandas", "sheet_name": "Sheet1"}
  222. )
  223. assert dn.exposed_type == "pandas"
  224. data = dn.read()
  225. assert isinstance(data, pd.DataFrame)
  226. def test_complex_exposed_type_dict(self):
  227. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5"]
  228. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  229. dn = ExcelDataNode(
  230. "foo",
  231. Scope.SCENARIO,
  232. properties={
  233. "default_path": path,
  234. "exposed_type": {
  235. "Sheet1": MyCustomObject1,
  236. "Sheet2": "numpy",
  237. "Sheet3": "pandas",
  238. },
  239. "sheet_name": ["Sheet1", "Sheet2", "Sheet3", "Sheet4"],
  240. },
  241. )
  242. data = dn.read()
  243. assert isinstance(data, dict)
  244. assert isinstance(data["Sheet1"], list)
  245. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  246. assert isinstance(data["Sheet2"], np.ndarray)
  247. assert isinstance(data["Sheet3"], pd.DataFrame)
  248. assert isinstance(data["Sheet4"], pd.DataFrame)
  249. assert data.get("Sheet5") is None
  250. def test_complex_exposed_type_list(self):
  251. # ["Sheet1", "Sheet2", "Sheet3", "Sheet4","Sheet5"]
  252. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example_4.xlsx")
  253. dn = ExcelDataNode(
  254. "foo",
  255. Scope.SCENARIO,
  256. properties={
  257. "default_path": path,
  258. "exposed_type": [MyCustomObject1, "numpy", "pandas"],
  259. "sheet_name": ["Sheet1", "Sheet2", "Sheet3"],
  260. },
  261. )
  262. data = dn.read()
  263. assert isinstance(data, dict)
  264. assert isinstance(data["Sheet1"], list)
  265. assert isinstance(data["Sheet1"][0], MyCustomObject1)
  266. assert isinstance(data["Sheet2"], np.ndarray)
  267. assert isinstance(data["Sheet3"], pd.DataFrame)
  268. def test_invalid_exposed_type(self):
  269. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.xlsx")
  270. with pytest.raises(InvalidExposedType):
  271. ExcelDataNode(
  272. "foo",
  273. Scope.SCENARIO,
  274. properties={"default_path": path, "exposed_type": "invalid", "sheet_name": "Sheet1"},
  275. )
  276. with pytest.raises(InvalidExposedType):
  277. ExcelDataNode(
  278. "foo",
  279. Scope.SCENARIO,
  280. properties={
  281. "default_path": path,
  282. "exposed_type": ["numpy", "invalid", "pandas"],
  283. "sheet_name": "Sheet1",
  284. },
  285. )
  286. with pytest.raises(InvalidExposedType):
  287. ExcelDataNode(
  288. "foo",
  289. Scope.SCENARIO,
  290. properties={
  291. "default_path": path,
  292. "exposed_type": {"Sheet1": "pandas", "Sheet2": "invalid"},
  293. "sheet_name": "Sheet1",
  294. },
  295. )
  296. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  297. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.xlsx"))
  298. pd.DataFrame([]).to_excel(temp_file_path)
  299. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  300. dn.write(pd.DataFrame([1, 2, 3]))
  301. previous_edit_date = dn.last_edit_date
  302. sleep(0.1)
  303. pd.DataFrame([4, 5, 6]).to_excel(temp_file_path)
  304. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  305. assert previous_edit_date < dn.last_edit_date
  306. assert new_edit_date == dn.last_edit_date
  307. sleep(0.1)
  308. dn.write(pd.DataFrame([7, 8, 9]))
  309. assert new_edit_date < dn.last_edit_date
  310. os.unlink(temp_file_path)
  311. def test_migrate_to_new_path(self, tmp_path):
  312. _base_path = os.path.join(tmp_path, ".data")
  313. path = os.path.join(_base_path, "test.xlsx")
  314. # create a file on old path
  315. os.mkdir(_base_path)
  316. with open(path, "w"):
  317. pass
  318. dn = ExcelDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  319. assert ".data" not in dn.path
  320. assert os.path.exists(dn.path)