test_csv_data_node.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. import numpy as np
  16. import pandas as pd
  17. import pytest
  18. from pandas.testing import assert_frame_equal
  19. from taipy.config.common.scope import Scope
  20. from taipy.config.config import Config
  21. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  22. from taipy.core.data._data_manager import _DataManager
  23. from taipy.core.data.csv import CSVDataNode
  24. from taipy.core.data.data_node_id import DataNodeId
  25. from taipy.core.data.operator import JoinOperator, Operator
  26. from taipy.core.exceptions.exceptions import InvalidExposedType, NoData
  27. @pytest.fixture(scope="function", autouse=True)
  28. def cleanup():
  29. yield
  30. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.csv")
  31. if os.path.isfile(path):
  32. os.remove(path)
  33. class MyCustomObject:
  34. def __init__(self, id, integer, text):
  35. self.id = id
  36. self.integer = integer
  37. self.text = text
  38. class TestCSVDataNode:
  39. def test_create(self):
  40. path = "data/node/path"
  41. dn = CSVDataNode(
  42. "foo_bar", Scope.SCENARIO, properties={"path": path, "has_header": False, "name": "super name"}
  43. )
  44. assert isinstance(dn, CSVDataNode)
  45. assert dn.storage_type() == "csv"
  46. assert dn.config_id == "foo_bar"
  47. assert dn.name == "super name"
  48. assert dn.scope == Scope.SCENARIO
  49. assert dn.id is not None
  50. assert dn.owner_id is None
  51. assert dn.last_edit_date is None
  52. assert dn.job_ids == []
  53. assert not dn.is_ready_for_reading
  54. assert dn.path == path
  55. assert dn.has_header is False
  56. assert dn.exposed_type == "pandas"
  57. with pytest.raises(InvalidConfigurationId):
  58. dn = CSVDataNode(
  59. "foo bar", Scope.SCENARIO, properties={"path": path, "has_header": False, "name": "super name"}
  60. )
  61. def test_modin_deprecated_in_favor_of_pandas(self):
  62. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  63. # Create CSVDataNode with modin exposed_type
  64. csv_data_node_as_modin = CSVDataNode("bar", Scope.SCENARIO, properties={"path": path, "exposed_type": "modin"})
  65. assert csv_data_node_as_modin.properties["exposed_type"] == "pandas"
  66. data_modin = csv_data_node_as_modin.read()
  67. assert isinstance(data_modin, pd.DataFrame)
  68. def test_get_user_properties(self, csv_file):
  69. dn_1 = CSVDataNode("dn_1", Scope.SCENARIO, properties={"path": "data/node/path"})
  70. assert dn_1._get_user_properties() == {}
  71. dn_2 = CSVDataNode(
  72. "dn_2",
  73. Scope.SCENARIO,
  74. properties={
  75. "exposed_type": "numpy",
  76. "default_data": "foo",
  77. "default_path": csv_file,
  78. "has_header": False,
  79. "foo": "bar",
  80. },
  81. )
  82. # exposed_type, default_data, default_path, path, has_header, sheet_name are filtered out
  83. assert dn_2._get_user_properties() == {"foo": "bar"}
  84. def test_new_csv_data_node_with_existing_file_is_ready_for_reading(self):
  85. not_ready_dn_cfg = Config.configure_data_node("not_ready_data_node_config_id", "csv", path="NOT_EXISTING.csv")
  86. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  87. assert not not_ready_dn.is_ready_for_reading
  88. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  89. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "csv", path=path)
  90. ready_dn = _DataManager._bulk_get_or_create([ready_dn_cfg])[ready_dn_cfg]
  91. assert ready_dn.is_ready_for_reading
  92. @pytest.mark.parametrize(
  93. ["properties", "exists"],
  94. [
  95. ({}, False),
  96. ({"default_data": ["foo", "bar"]}, True),
  97. ],
  98. )
  99. def test_create_with_default_data(self, properties, exists):
  100. dn = CSVDataNode("foo", Scope.SCENARIO, DataNodeId("dn_id"), properties=properties)
  101. assert os.path.exists(dn.path) is exists
  102. def test_read_with_header_pandas(self):
  103. not_existing_csv = CSVDataNode("foo", Scope.SCENARIO, properties={"path": "WRONG.csv", "has_header": True})
  104. with pytest.raises(NoData):
  105. assert not_existing_csv.read() is None
  106. not_existing_csv.read_or_raise()
  107. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  108. # # Create CSVDataNode without exposed_type (Default is pandas.DataFrame)
  109. csv_data_node_as_pandas = CSVDataNode("bar", Scope.SCENARIO, properties={"path": path})
  110. data_pandas = csv_data_node_as_pandas.read()
  111. assert isinstance(data_pandas, pd.DataFrame)
  112. assert len(data_pandas) == 10
  113. assert np.array_equal(data_pandas.to_numpy(), pd.read_csv(path).to_numpy())
  114. def test_read_with_header_numpy(self):
  115. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  116. # Create CSVDataNode with numpy exposed_type
  117. csv_data_node_as_numpy = CSVDataNode(
  118. "bar", Scope.SCENARIO, properties={"path": path, "has_header": True, "exposed_type": "numpy"}
  119. )
  120. data_numpy = csv_data_node_as_numpy.read()
  121. assert isinstance(data_numpy, np.ndarray)
  122. assert len(data_numpy) == 10
  123. assert np.array_equal(data_numpy, pd.read_csv(path).to_numpy())
  124. def test_read_with_header_custom_exposed_type(self):
  125. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  126. csv_data_node_as_pandas = CSVDataNode("bar", Scope.SCENARIO, properties={"path": path})
  127. data_pandas = csv_data_node_as_pandas.read()
  128. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  129. # Create the same CSVDataNode but with custom exposed_type
  130. csv_data_node_as_custom_object = CSVDataNode(
  131. "bar", Scope.SCENARIO, properties={"path": path, "exposed_type": MyCustomObject}
  132. )
  133. data_custom = csv_data_node_as_custom_object.read()
  134. assert isinstance(data_custom, list)
  135. assert len(data_custom) == 10
  136. for (_, row_pandas), row_custom in zip(data_pandas.iterrows(), data_custom):
  137. assert isinstance(row_custom, MyCustomObject)
  138. assert row_pandas["id"] == row_custom.id
  139. assert str(row_pandas["integer"]) == row_custom.integer
  140. assert row_pandas["text"] == row_custom.text
  141. def test_read_without_header(self):
  142. not_existing_csv = CSVDataNode("foo", Scope.SCENARIO, properties={"path": "WRONG.csv", "has_header": False})
  143. with pytest.raises(NoData):
  144. assert not_existing_csv.read() is None
  145. not_existing_csv.read_or_raise()
  146. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  147. # Create CSVDataNode without exposed_type (Default is pandas.DataFrame)
  148. csv_data_node_as_pandas = CSVDataNode("bar", Scope.SCENARIO, properties={"path": path, "has_header": False})
  149. data_pandas = csv_data_node_as_pandas.read()
  150. assert isinstance(data_pandas, pd.DataFrame)
  151. assert len(data_pandas) == 11
  152. assert np.array_equal(data_pandas.to_numpy(), pd.read_csv(path, header=None).to_numpy())
  153. # Create CSVDataNode with numpy exposed_type
  154. csv_data_node_as_numpy = CSVDataNode(
  155. "qux", Scope.SCENARIO, properties={"path": path, "has_header": False, "exposed_type": "numpy"}
  156. )
  157. data_numpy = csv_data_node_as_numpy.read()
  158. assert isinstance(data_numpy, np.ndarray)
  159. assert len(data_numpy) == 11
  160. assert np.array_equal(data_numpy, pd.read_csv(path, header=None).to_numpy())
  161. # Create the same CSVDataNode but with custom exposed_type
  162. csv_data_node_as_custom_object = CSVDataNode(
  163. "quux", Scope.SCENARIO, properties={"path": path, "has_header": False, "exposed_type": MyCustomObject}
  164. )
  165. data_custom = csv_data_node_as_custom_object.read()
  166. assert isinstance(data_custom, list)
  167. assert len(data_custom) == 11
  168. for (_, row_pandas), row_custom in zip(data_pandas.iterrows(), data_custom):
  169. assert isinstance(row_custom, MyCustomObject)
  170. assert row_pandas[0] == row_custom.id
  171. assert str(row_pandas[1]) == row_custom.integer
  172. assert row_pandas[2] == row_custom.text
  173. @pytest.mark.parametrize(
  174. "content",
  175. [
  176. ([{"a": 11, "b": 22, "c": 33}, {"a": 44, "b": 55, "c": 66}]),
  177. (pd.DataFrame([{"a": 11, "b": 22, "c": 33}, {"a": 44, "b": 55, "c": 66}])),
  178. ([[11, 22, 33], [44, 55, 66]]),
  179. ],
  180. )
  181. def test_append(self, csv_file, default_data_frame, content):
  182. csv_dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": csv_file})
  183. assert_frame_equal(csv_dn.read(), default_data_frame)
  184. csv_dn.append(content)
  185. assert_frame_equal(
  186. csv_dn.read(),
  187. pd.concat([default_data_frame, pd.DataFrame(content, columns=["a", "b", "c"])]).reset_index(drop=True),
  188. )
  189. @pytest.mark.parametrize(
  190. "content,columns",
  191. [
  192. ([{"a": 11, "b": 22, "c": 33}, {"a": 44, "b": 55, "c": 66}], None),
  193. ([[11, 22, 33], [44, 55, 66]], None),
  194. ([[11, 22, 33], [44, 55, 66]], ["e", "f", "g"]),
  195. ],
  196. )
  197. def test_write(self, csv_file, default_data_frame, content, columns):
  198. csv_dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": csv_file})
  199. assert np.array_equal(csv_dn.read().values, default_data_frame.values)
  200. if not columns:
  201. csv_dn.write(content)
  202. df = pd.DataFrame(content)
  203. else:
  204. csv_dn.write_with_column_names(content, columns)
  205. df = pd.DataFrame(content, columns=columns)
  206. assert np.array_equal(csv_dn.read().values, df.values)
  207. csv_dn.write(None)
  208. assert len(csv_dn.read()) == 0
  209. def test_write_with_different_encoding(self, csv_file):
  210. data = pd.DataFrame([{"≥a": 1, "b": 2}])
  211. utf8_dn = CSVDataNode("utf8_dn", Scope.SCENARIO, properties={"default_path": csv_file})
  212. utf16_dn = CSVDataNode("utf16_dn", Scope.SCENARIO, properties={"default_path": csv_file, "encoding": "utf-16"})
  213. # If a file is written with utf-8 encoding, it can only be read with utf-8, not utf-16 encoding
  214. utf8_dn.write(data)
  215. assert np.array_equal(utf8_dn.read(), data)
  216. with pytest.raises(UnicodeError):
  217. utf16_dn.read()
  218. # If a file is written with utf-16 encoding, it can only be read with utf-16, not utf-8 encoding
  219. utf16_dn.write(data)
  220. assert np.array_equal(utf16_dn.read(), data)
  221. with pytest.raises(UnicodeError):
  222. utf8_dn.read()
  223. def test_set_path(self):
  224. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.csv"})
  225. assert dn.path == "foo.csv"
  226. dn.path = "bar.csv"
  227. assert dn.path == "bar.csv"
  228. def test_read_write_after_modify_path(self):
  229. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  230. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.csv")
  231. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  232. read_data = dn.read()
  233. assert read_data is not None
  234. dn.path = new_path
  235. with pytest.raises(FileNotFoundError):
  236. dn.read()
  237. dn.write(read_data)
  238. assert dn.read().equals(read_data)
  239. def test_pandas_exposed_type(self):
  240. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  241. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "pandas"})
  242. assert isinstance(dn.read(), pd.DataFrame)
  243. def test_filter_pandas_exposed_type(self, csv_file):
  244. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": csv_file, "exposed_type": "pandas"})
  245. dn.write(
  246. [
  247. {"foo": 1, "bar": 1},
  248. {"foo": 1, "bar": 2},
  249. {"foo": 1},
  250. {"foo": 2, "bar": 2},
  251. {"bar": 2},
  252. ]
  253. )
  254. # Test datanode indexing and slicing
  255. assert dn["foo"].equals(pd.Series([1, 1, 1, 2, None]))
  256. assert dn["bar"].equals(pd.Series([1, 2, None, 2, 2]))
  257. assert dn[:2].equals(pd.DataFrame([{"foo": 1.0, "bar": 1.0}, {"foo": 1.0, "bar": 2.0}]))
  258. # Test filter data
  259. filtered_by_filter_method = dn.filter(("foo", 1, Operator.EQUAL))
  260. filtered_by_indexing = dn[dn["foo"] == 1]
  261. expected_data = pd.DataFrame([{"foo": 1.0, "bar": 1.0}, {"foo": 1.0, "bar": 2.0}, {"foo": 1.0}])
  262. assert_frame_equal(filtered_by_filter_method.reset_index(drop=True), expected_data)
  263. assert_frame_equal(filtered_by_indexing.reset_index(drop=True), expected_data)
  264. filtered_by_filter_method = dn.filter(("foo", 1, Operator.NOT_EQUAL))
  265. filtered_by_indexing = dn[dn["foo"] != 1]
  266. expected_data = pd.DataFrame([{"foo": 2.0, "bar": 2.0}, {"bar": 2.0}])
  267. assert_frame_equal(filtered_by_filter_method.reset_index(drop=True), expected_data)
  268. assert_frame_equal(filtered_by_indexing.reset_index(drop=True), expected_data)
  269. filtered_by_filter_method = dn.filter(("bar", 2, Operator.EQUAL))
  270. filtered_by_indexing = dn[dn["bar"] == 2]
  271. expected_data = pd.DataFrame([{"foo": 1.0, "bar": 2.0}, {"foo": 2.0, "bar": 2.0}, {"bar": 2.0}])
  272. assert_frame_equal(filtered_by_filter_method.reset_index(drop=True), expected_data)
  273. assert_frame_equal(filtered_by_indexing.reset_index(drop=True), expected_data)
  274. filtered_by_filter_method = dn.filter([("bar", 1, Operator.EQUAL), ("bar", 2, Operator.EQUAL)], JoinOperator.OR)
  275. filtered_by_indexing = dn[(dn["bar"] == 1) | (dn["bar"] == 2)]
  276. expected_data = pd.DataFrame(
  277. [
  278. {"foo": 1.0, "bar": 1.0},
  279. {"foo": 1.0, "bar": 2.0},
  280. {"foo": 2.0, "bar": 2.0},
  281. {"bar": 2.0},
  282. ]
  283. )
  284. assert_frame_equal(filtered_by_filter_method.reset_index(drop=True), expected_data)
  285. assert_frame_equal(filtered_by_indexing.reset_index(drop=True), expected_data)
  286. def test_filter_numpy_exposed_type(self, csv_file):
  287. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": csv_file, "exposed_type": "numpy"})
  288. dn.write(
  289. [
  290. [1, 1],
  291. [1, 2],
  292. [1, 3],
  293. [2, 1],
  294. [2, 2],
  295. [2, 3],
  296. ]
  297. )
  298. # Test datanode indexing and slicing
  299. assert np.array_equal(dn[0], np.array([1, 1]))
  300. assert np.array_equal(dn[1], np.array([1, 2]))
  301. assert np.array_equal(dn[:3], np.array([[1, 1], [1, 2], [1, 3]]))
  302. assert np.array_equal(dn[:, 0], np.array([1, 1, 1, 2, 2, 2]))
  303. assert np.array_equal(dn[1:4, :1], np.array([[1], [1], [2]]))
  304. # Test filter data
  305. assert np.array_equal(dn.filter((0, 1, Operator.EQUAL)), np.array([[1, 1], [1, 2], [1, 3]]))
  306. assert np.array_equal(dn[dn[:, 0] == 1], np.array([[1, 1], [1, 2], [1, 3]]))
  307. assert np.array_equal(dn.filter((0, 1, Operator.NOT_EQUAL)), np.array([[2, 1], [2, 2], [2, 3]]))
  308. assert np.array_equal(dn[dn[:, 0] != 1], np.array([[2, 1], [2, 2], [2, 3]]))
  309. assert np.array_equal(dn.filter((1, 2, Operator.EQUAL)), np.array([[1, 2], [2, 2]]))
  310. assert np.array_equal(dn[dn[:, 1] == 2], np.array([[1, 2], [2, 2]]))
  311. assert np.array_equal(
  312. dn.filter([(1, 1, Operator.EQUAL), (1, 2, Operator.EQUAL)], JoinOperator.OR),
  313. np.array([[1, 1], [1, 2], [2, 1], [2, 2]]),
  314. )
  315. assert np.array_equal(dn[(dn[:, 1] == 1) | (dn[:, 1] == 2)], np.array([[1, 1], [1, 2], [2, 1], [2, 2]]))
  316. def test_raise_error_invalid_exposed_type(self):
  317. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/example.csv")
  318. with pytest.raises(InvalidExposedType):
  319. CSVDataNode("foo", Scope.SCENARIO, properties={"path": path, "exposed_type": "foo"})
  320. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  321. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.csv"))
  322. pd.DataFrame([]).to_csv(temp_file_path)
  323. dn = CSVDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path, "exposed_type": "pandas"})
  324. dn.write(pd.DataFrame([1, 2, 3]))
  325. previous_edit_date = dn.last_edit_date
  326. sleep(0.1)
  327. pd.DataFrame([4, 5, 6]).to_csv(temp_file_path)
  328. new_edit_date = datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  329. assert previous_edit_date < dn.last_edit_date
  330. assert new_edit_date == dn.last_edit_date
  331. sleep(0.1)
  332. dn.write(pd.DataFrame([7, 8, 9]))
  333. assert new_edit_date < dn.last_edit_date
  334. os.unlink(temp_file_path)