test_excel_data_node.py 14 KB

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