test_json_data_node.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 datetime
  12. import json
  13. import os
  14. import pathlib
  15. from dataclasses import dataclass
  16. from enum import Enum
  17. from time import sleep
  18. import numpy as np
  19. import pandas as pd
  20. import pytest
  21. from taipy.config.common.scope import Scope
  22. from taipy.config.config import Config
  23. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  24. from taipy.core.data._data_manager import _DataManager
  25. from taipy.core.data.data_node_id import DataNodeId
  26. from taipy.core.data.json import JSONDataNode
  27. from taipy.core.data.operator import JoinOperator, Operator
  28. from taipy.core.exceptions.exceptions import NoData
  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.json")
  33. if os.path.isfile(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 MyCustomObject2:
  41. def __init__(self, id, boolean, text):
  42. self.id = id
  43. self.boolean = boolean
  44. self.text = text
  45. class MyEnum(Enum):
  46. A = 1
  47. B = 2
  48. C = 3
  49. @dataclass
  50. class CustomDataclass:
  51. integer: int
  52. string: str
  53. class MyCustomEncoder(json.JSONEncoder):
  54. def default(self, o):
  55. if isinstance(o, MyCustomObject):
  56. return {"__type__": "MyCustomObject", "id": o.id, "integer": o.integer, "text": o.text}
  57. return super().default(self, o)
  58. class MyCustomDecoder(json.JSONDecoder):
  59. def __init__(self, *args, **kwargs):
  60. super().__init__(*args, **kwargs, object_hook=self.object_hook)
  61. def object_hook(self, o):
  62. if o.get("__type__") == "MyCustomObject":
  63. return MyCustomObject(o["id"], o["integer"], o["text"])
  64. else:
  65. return o
  66. class TestJSONDataNode:
  67. def test_create(self):
  68. path = "data/node/path"
  69. dn = JSONDataNode("foo_bar", Scope.SCENARIO, properties={"default_path": path, "name": "super name"})
  70. assert isinstance(dn, JSONDataNode)
  71. assert dn.storage_type() == "json"
  72. assert dn.config_id == "foo_bar"
  73. assert dn.name == "super name"
  74. assert dn.scope == Scope.SCENARIO
  75. assert dn.id is not None
  76. assert dn.owner_id is None
  77. assert dn.last_edit_date is None
  78. assert dn.job_ids == []
  79. assert not dn.is_ready_for_reading
  80. assert dn.path == path
  81. with pytest.raises(InvalidConfigurationId):
  82. dn = JSONDataNode(
  83. "foo bar", Scope.SCENARIO, properties={"default_path": path, "has_header": False, "name": "super name"}
  84. )
  85. def test_get_user_properties(self, json_file):
  86. dn_1 = JSONDataNode("dn_1", Scope.SCENARIO, properties={"path": json_file})
  87. assert dn_1._get_user_properties() == {}
  88. dn_2 = JSONDataNode(
  89. "dn_2",
  90. Scope.SCENARIO,
  91. properties={
  92. "default_data": "foo",
  93. "default_path": json_file,
  94. "encoder": MyCustomEncoder,
  95. "decoder": MyCustomDecoder,
  96. "foo": "bar",
  97. },
  98. )
  99. # default_data, default_path, path, encoder, decoder are filtered out
  100. assert dn_2._get_user_properties() == {"foo": "bar"}
  101. def test_new_json_data_node_with_existing_file_is_ready_for_reading(self):
  102. not_ready_dn_cfg = Config.configure_data_node(
  103. "not_ready_data_node_config_id", "json", default_path="NOT_EXISTING.json"
  104. )
  105. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  106. assert not not_ready_dn.is_ready_for_reading
  107. assert not_ready_dn.path == "NOT_EXISTING.json"
  108. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_list.json")
  109. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "json", default_path=path)
  110. ready_dn = _DataManager._bulk_get_or_create([ready_dn_cfg])[ready_dn_cfg]
  111. assert ready_dn.is_ready_for_reading
  112. def test_read_non_existing_json(self):
  113. not_existing_json = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": "WRONG.json"})
  114. with pytest.raises(NoData):
  115. assert not_existing_json.read() is None
  116. not_existing_json.read_or_raise()
  117. def test_read(self):
  118. path_1 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_list.json")
  119. dn_1 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_1})
  120. data_1 = dn_1.read()
  121. assert isinstance(data_1, list)
  122. assert len(data_1) == 4
  123. path_2 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_dict.json")
  124. dn_2 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_2})
  125. data_2 = dn_2.read()
  126. assert isinstance(data_2, dict)
  127. assert data_2["id"] == "1"
  128. path_3 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_int.json")
  129. dn_3 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_3})
  130. data_3 = dn_3.read()
  131. assert isinstance(data_3, int)
  132. assert data_3 == 1
  133. path_4 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_null.json")
  134. dn_4 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_4})
  135. data_4 = dn_4.read()
  136. assert data_4 is None
  137. def test_read_invalid_json(self):
  138. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/invalid.json.txt")
  139. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  140. with pytest.raises(ValueError):
  141. dn.read()
  142. def test_append_to_list(self, json_file):
  143. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  144. original_data = json_dn.read()
  145. # Append a dictionary
  146. append_data_1 = {"a": 1, "b": 2, "c": 3}
  147. json_dn.append(append_data_1)
  148. assert json_dn.read() == original_data + [append_data_1]
  149. # Append a list of dictionaries
  150. append_data_data_2 = [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}]
  151. json_dn.append(append_data_data_2)
  152. assert json_dn.read() == original_data + [append_data_1] + append_data_data_2
  153. def test_append_to_a_dictionary(self, json_file):
  154. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  155. original_data = {"a": 1, "b": 2, "c": 3}
  156. json_dn.write(original_data)
  157. # Append another dictionary
  158. append_data_1 = {"d": 1, "e": 2, "f": 3}
  159. json_dn.append(append_data_1)
  160. assert json_dn.read() == {**original_data, **append_data_1}
  161. # Append an overlap dictionary
  162. append_data_data_2 = {"a": 10, "b": 20, "g": 30}
  163. json_dn.append(append_data_data_2)
  164. assert json_dn.read() == {**original_data, **append_data_1, **append_data_data_2}
  165. def test_write(self, json_file):
  166. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  167. data = {"a": 1, "b": 2, "c": 3}
  168. json_dn.write(data)
  169. assert np.array_equal(json_dn.read(), data)
  170. def test_write_with_different_encoding(self, json_file):
  171. data = {"≥a": 1, "b": 2}
  172. utf8_dn = JSONDataNode("utf8_dn", Scope.SCENARIO, properties={"default_path": json_file})
  173. utf16_dn = JSONDataNode(
  174. "utf16_dn", Scope.SCENARIO, properties={"default_path": json_file, "encoding": "utf-16"}
  175. )
  176. # If a file is written with utf-8 encoding, it can only be read with utf-8, not utf-16 encoding
  177. utf8_dn.write(data)
  178. assert np.array_equal(utf8_dn.read(), data)
  179. with pytest.raises(UnicodeError):
  180. utf16_dn.read()
  181. # If a file is written with utf-16 encoding, it can only be read with utf-16, not utf-8 encoding
  182. utf16_dn.write(data)
  183. assert np.array_equal(utf16_dn.read(), data)
  184. with pytest.raises(UnicodeError):
  185. utf8_dn.read()
  186. def test_write_non_serializable(self, json_file):
  187. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  188. data = {"a": 1, "b": json_dn}
  189. with pytest.raises(TypeError):
  190. json_dn.write(data)
  191. def test_write_date(self, json_file):
  192. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  193. now = datetime.datetime.now()
  194. data = {"date": now}
  195. json_dn.write(data)
  196. read_data = json_dn.read()
  197. assert read_data["date"] == now
  198. def test_write_enum(self, json_file):
  199. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  200. data = [MyEnum.A, MyEnum.B, MyEnum.C]
  201. json_dn.write(data)
  202. read_data = json_dn.read()
  203. assert read_data == [MyEnum.A, MyEnum.B, MyEnum.C]
  204. def test_write_dataclass(self, json_file):
  205. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  206. json_dn.write(CustomDataclass(integer=1, string="foo"))
  207. read_data = json_dn.read()
  208. assert read_data.integer == 1
  209. assert read_data.string == "foo"
  210. def test_write_custom_encoder(self, json_file):
  211. json_dn = JSONDataNode(
  212. "foo", Scope.SCENARIO, properties={"default_path": json_file, "encoder": MyCustomEncoder}
  213. )
  214. data = [MyCustomObject("1", 1, "abc"), 100]
  215. json_dn.write(data)
  216. read_data = json_dn.read()
  217. assert read_data[0]["__type__"] == "MyCustomObject"
  218. assert read_data[0]["id"] == "1"
  219. assert read_data[0]["integer"] == 1
  220. assert read_data[0]["text"] == "abc"
  221. assert read_data[1] == 100
  222. def test_read_write_custom_encoder_decoder(self, json_file):
  223. json_dn = JSONDataNode(
  224. "foo",
  225. Scope.SCENARIO,
  226. properties={"default_path": json_file, "encoder": MyCustomEncoder, "decoder": MyCustomDecoder},
  227. )
  228. data = [MyCustomObject("1", 1, "abc"), 100]
  229. json_dn.write(data)
  230. read_data = json_dn.read()
  231. assert isinstance(read_data[0], MyCustomObject)
  232. assert read_data[0].id == "1"
  233. assert read_data[0].integer == 1
  234. assert read_data[0].text == "abc"
  235. assert read_data[1] == 100
  236. def test_filter(self, json_file):
  237. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  238. json_dn.write(
  239. [
  240. {"foo": 1, "bar": 1},
  241. {"foo": 1, "bar": 2},
  242. {"foo": 1},
  243. {"foo": 2, "bar": 2},
  244. {"bar": 2},
  245. {"KWARGS_KEY": "KWARGS_VALUE"},
  246. ]
  247. )
  248. assert len(json_dn.filter(("foo", 1, Operator.EQUAL))) == 3
  249. assert len(json_dn.filter(("foo", 1, Operator.NOT_EQUAL))) == 3
  250. assert len(json_dn.filter(("bar", 2, Operator.EQUAL))) == 3
  251. assert len(json_dn.filter([("bar", 1, Operator.EQUAL), ("bar", 2, Operator.EQUAL)], JoinOperator.OR)) == 4
  252. assert json_dn[0] == {"foo": 1, "bar": 1}
  253. assert json_dn[2] == {"foo": 1}
  254. assert json_dn[:2] == [{"foo": 1, "bar": 1}, {"foo": 1, "bar": 2}]
  255. @pytest.mark.parametrize(
  256. ["properties", "exists"],
  257. [
  258. ({}, False),
  259. ({"default_data": {"foo": "bar"}}, True),
  260. ],
  261. )
  262. def test_create_with_default_data(self, properties, exists):
  263. dn = JSONDataNode("foo", Scope.SCENARIO, DataNodeId("dn_id"), properties=properties)
  264. assert os.path.exists(dn.path) is exists
  265. def test_set_path(self):
  266. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.json"})
  267. assert dn.path == "foo.json"
  268. dn.path = "bar.json"
  269. assert dn.path == "bar.json"
  270. def test_read_write_after_modify_path(self):
  271. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_dict.json")
  272. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.json")
  273. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  274. read_data = dn.read()
  275. assert read_data is not None
  276. dn.path = new_path
  277. with pytest.raises(FileNotFoundError):
  278. dn.read()
  279. dn.write({"other": "stuff"})
  280. assert dn.read() == {"other": "stuff"}
  281. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  282. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.json"))
  283. pd.DataFrame([]).to_json(temp_file_path)
  284. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path})
  285. dn.write([1, 2, 3])
  286. previous_edit_date = dn.last_edit_date
  287. sleep(0.1)
  288. pd.DataFrame([4, 5, 6]).to_json(temp_file_path)
  289. new_edit_date = datetime.datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  290. assert previous_edit_date < dn.last_edit_date
  291. assert new_edit_date == dn.last_edit_date
  292. sleep(0.1)
  293. dn.write([1, 2, 3])
  294. assert new_edit_date < dn.last_edit_date
  295. os.unlink(temp_file_path)
  296. def test_migrate_to_new_path(self, tmp_path):
  297. _base_path = os.path.join(tmp_path, ".data")
  298. path = os.path.join(_base_path, "test.json")
  299. # create a file on old path
  300. os.mkdir(_base_path)
  301. with open(path, "w"):
  302. pass
  303. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": path})
  304. assert ".data" not in dn.path.name
  305. assert os.path.exists(dn.path)