test_json_data_node.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. import uuid
  16. from dataclasses import dataclass
  17. from enum import Enum
  18. from time import sleep
  19. import freezegun
  20. import numpy as np
  21. import pandas as pd
  22. import pytest
  23. from taipy.config.common.scope import Scope
  24. from taipy.config.config import Config
  25. from taipy.config.exceptions.exceptions import InvalidConfigurationId
  26. from taipy.core.data._data_manager import _DataManager
  27. from taipy.core.data.data_node_id import DataNodeId
  28. from taipy.core.data.json import JSONDataNode
  29. from taipy.core.data.operator import JoinOperator, Operator
  30. from taipy.core.exceptions.exceptions import NoData
  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.json")
  35. if os.path.isfile(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 MyCustomObject2:
  43. def __init__(self, id, boolean, text):
  44. self.id = id
  45. self.boolean = boolean
  46. self.text = text
  47. class MyEnum(Enum):
  48. A = 1
  49. B = 2
  50. C = 3
  51. @dataclass
  52. class CustomDataclass:
  53. integer: int
  54. string: str
  55. class MyCustomEncoder(json.JSONEncoder):
  56. def default(self, o):
  57. if isinstance(o, MyCustomObject):
  58. return {"__type__": "MyCustomObject", "id": o.id, "integer": o.integer, "text": o.text}
  59. return super().default(self, o)
  60. class MyCustomDecoder(json.JSONDecoder):
  61. def __init__(self, *args, **kwargs):
  62. super().__init__(*args, **kwargs, object_hook=self.object_hook)
  63. def object_hook(self, o):
  64. if o.get("__type__") == "MyCustomObject":
  65. return MyCustomObject(o["id"], o["integer"], o["text"])
  66. else:
  67. return o
  68. class TestJSONDataNode:
  69. def test_create(self):
  70. path = "data/node/path"
  71. dn = JSONDataNode("foo_bar", Scope.SCENARIO, properties={"default_path": path, "name": "super name"})
  72. assert isinstance(dn, JSONDataNode)
  73. assert dn.storage_type() == "json"
  74. assert dn.config_id == "foo_bar"
  75. assert dn.name == "super name"
  76. assert dn.scope == Scope.SCENARIO
  77. assert dn.id is not None
  78. assert dn.owner_id is None
  79. assert dn.last_edit_date is None
  80. assert dn.job_ids == []
  81. assert not dn.is_ready_for_reading
  82. assert dn.path == path
  83. with pytest.raises(InvalidConfigurationId):
  84. dn = JSONDataNode(
  85. "foo bar", Scope.SCENARIO, properties={"default_path": path, "has_header": False, "name": "super name"}
  86. )
  87. def test_get_user_properties(self, json_file):
  88. dn_1 = JSONDataNode("dn_1", Scope.SCENARIO, properties={"path": json_file})
  89. assert dn_1._get_user_properties() == {}
  90. dn_2 = JSONDataNode(
  91. "dn_2",
  92. Scope.SCENARIO,
  93. properties={
  94. "default_data": "foo",
  95. "default_path": json_file,
  96. "encoder": MyCustomEncoder,
  97. "decoder": MyCustomDecoder,
  98. "foo": "bar",
  99. },
  100. )
  101. # default_data, default_path, path, encoder, decoder are filtered out
  102. assert dn_2._get_user_properties() == {"foo": "bar"}
  103. def test_new_json_data_node_with_existing_file_is_ready_for_reading(self):
  104. not_ready_dn_cfg = Config.configure_data_node(
  105. "not_ready_data_node_config_id", "json", default_path="NOT_EXISTING.json"
  106. )
  107. not_ready_dn = _DataManager._bulk_get_or_create([not_ready_dn_cfg])[not_ready_dn_cfg]
  108. assert not not_ready_dn.is_ready_for_reading
  109. assert not_ready_dn.path == "NOT_EXISTING.json"
  110. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_list.json")
  111. ready_dn_cfg = Config.configure_data_node("ready_data_node_config_id", "json", default_path=path)
  112. ready_dn = _DataManager._bulk_get_or_create([ready_dn_cfg])[ready_dn_cfg]
  113. assert ready_dn.is_ready_for_reading
  114. def test_read_non_existing_json(self):
  115. not_existing_json = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": "WRONG.json"})
  116. with pytest.raises(NoData):
  117. assert not_existing_json.read() is None
  118. not_existing_json.read_or_raise()
  119. def test_read(self):
  120. path_1 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_list.json")
  121. dn_1 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_1})
  122. data_1 = dn_1.read()
  123. assert isinstance(data_1, list)
  124. assert len(data_1) == 4
  125. path_2 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_dict.json")
  126. dn_2 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_2})
  127. data_2 = dn_2.read()
  128. assert isinstance(data_2, dict)
  129. assert data_2["id"] == "1"
  130. path_3 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_int.json")
  131. dn_3 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_3})
  132. data_3 = dn_3.read()
  133. assert isinstance(data_3, int)
  134. assert data_3 == 1
  135. path_4 = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_null.json")
  136. dn_4 = JSONDataNode("bar", Scope.SCENARIO, properties={"default_path": path_4})
  137. data_4 = dn_4.read()
  138. assert data_4 is None
  139. def test_read_invalid_json(self):
  140. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/invalid.json.txt")
  141. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  142. with pytest.raises(ValueError):
  143. dn.read()
  144. def test_append_to_list(self, json_file):
  145. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  146. original_data = json_dn.read()
  147. # Append a dictionary
  148. append_data_1 = {"a": 1, "b": 2, "c": 3}
  149. json_dn.append(append_data_1)
  150. assert json_dn.read() == original_data + [append_data_1]
  151. # Append a list of dictionaries
  152. append_data_data_2 = [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}]
  153. json_dn.append(append_data_data_2)
  154. assert json_dn.read() == original_data + [append_data_1] + append_data_data_2
  155. def test_append_to_a_dictionary(self, json_file):
  156. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  157. original_data = {"a": 1, "b": 2, "c": 3}
  158. json_dn.write(original_data)
  159. # Append another dictionary
  160. append_data_1 = {"d": 1, "e": 2, "f": 3}
  161. json_dn.append(append_data_1)
  162. assert json_dn.read() == {**original_data, **append_data_1}
  163. # Append an overlap dictionary
  164. append_data_data_2 = {"a": 10, "b": 20, "g": 30}
  165. json_dn.append(append_data_data_2)
  166. assert json_dn.read() == {**original_data, **append_data_1, **append_data_data_2}
  167. def test_write(self, json_file):
  168. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  169. data = {"a": 1, "b": 2, "c": 3}
  170. json_dn.write(data)
  171. assert np.array_equal(json_dn.read(), data)
  172. def test_write_with_different_encoding(self, json_file):
  173. data = {"≥a": 1, "b": 2}
  174. utf8_dn = JSONDataNode("utf8_dn", Scope.SCENARIO, properties={"default_path": json_file})
  175. utf16_dn = JSONDataNode(
  176. "utf16_dn", Scope.SCENARIO, properties={"default_path": json_file, "encoding": "utf-16"}
  177. )
  178. # If a file is written with utf-8 encoding, it can only be read with utf-8, not utf-16 encoding
  179. utf8_dn.write(data)
  180. assert np.array_equal(utf8_dn.read(), data)
  181. with pytest.raises(UnicodeError):
  182. utf16_dn.read()
  183. # If a file is written with utf-16 encoding, it can only be read with utf-16, not utf-8 encoding
  184. utf16_dn.write(data)
  185. assert np.array_equal(utf16_dn.read(), data)
  186. with pytest.raises(UnicodeError):
  187. utf8_dn.read()
  188. def test_write_non_serializable(self, json_file):
  189. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  190. data = {"a": 1, "b": json_dn}
  191. with pytest.raises(TypeError):
  192. json_dn.write(data)
  193. def test_write_date(self, json_file):
  194. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  195. now = datetime.datetime.now()
  196. data = {"date": now}
  197. json_dn.write(data)
  198. read_data = json_dn.read()
  199. assert read_data["date"] == now
  200. def test_write_enum(self, json_file):
  201. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  202. data = [MyEnum.A, MyEnum.B, MyEnum.C]
  203. json_dn.write(data)
  204. read_data = json_dn.read()
  205. assert read_data == [MyEnum.A, MyEnum.B, MyEnum.C]
  206. def test_write_dataclass(self, json_file):
  207. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  208. json_dn.write(CustomDataclass(integer=1, string="foo"))
  209. read_data = json_dn.read()
  210. assert read_data.integer == 1
  211. assert read_data.string == "foo"
  212. def test_write_custom_encoder(self, json_file):
  213. json_dn = JSONDataNode(
  214. "foo", Scope.SCENARIO, properties={"default_path": json_file, "encoder": MyCustomEncoder}
  215. )
  216. data = [MyCustomObject("1", 1, "abc"), 100]
  217. json_dn.write(data)
  218. read_data = json_dn.read()
  219. assert read_data[0]["__type__"] == "MyCustomObject"
  220. assert read_data[0]["id"] == "1"
  221. assert read_data[0]["integer"] == 1
  222. assert read_data[0]["text"] == "abc"
  223. assert read_data[1] == 100
  224. def test_read_write_custom_encoder_decoder(self, json_file):
  225. json_dn = JSONDataNode(
  226. "foo",
  227. Scope.SCENARIO,
  228. properties={"default_path": json_file, "encoder": MyCustomEncoder, "decoder": MyCustomDecoder},
  229. )
  230. data = [MyCustomObject("1", 1, "abc"), 100]
  231. json_dn.write(data)
  232. read_data = json_dn.read()
  233. assert isinstance(read_data[0], MyCustomObject)
  234. assert read_data[0].id == "1"
  235. assert read_data[0].integer == 1
  236. assert read_data[0].text == "abc"
  237. assert read_data[1] == 100
  238. def test_filter(self, json_file):
  239. json_dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": json_file})
  240. json_dn.write(
  241. [
  242. {"foo": 1, "bar": 1},
  243. {"foo": 1, "bar": 2},
  244. {"foo": 1},
  245. {"foo": 2, "bar": 2},
  246. {"bar": 2},
  247. {"KWARGS_KEY": "KWARGS_VALUE"},
  248. ]
  249. )
  250. assert len(json_dn.filter(("foo", 1, Operator.EQUAL))) == 3
  251. assert len(json_dn.filter(("foo", 1, Operator.NOT_EQUAL))) == 3
  252. assert len(json_dn.filter(("bar", 2, Operator.EQUAL))) == 3
  253. assert len(json_dn.filter([("bar", 1, Operator.EQUAL), ("bar", 2, Operator.EQUAL)], JoinOperator.OR)) == 4
  254. assert json_dn[0] == {"foo": 1, "bar": 1}
  255. assert json_dn[2] == {"foo": 1}
  256. assert json_dn[:2] == [{"foo": 1, "bar": 1}, {"foo": 1, "bar": 2}]
  257. @pytest.mark.parametrize(
  258. ["properties", "exists"],
  259. [
  260. ({"default_data": {"foo": "bar"}}, True),
  261. ({}, False),
  262. ],
  263. )
  264. def test_create_with_default_data(self, properties, exists):
  265. dn = JSONDataNode("foo", Scope.SCENARIO, DataNodeId(f"dn_id_{uuid.uuid4()}"), properties=properties)
  266. assert dn.path == os.path.join(Config.core.storage_folder.strip("/"), "jsons", dn.id + ".json")
  267. assert os.path.exists(dn.path) is exists
  268. def test_set_path(self):
  269. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": "foo.json"})
  270. assert dn.path == "foo.json"
  271. dn.path = "bar.json"
  272. assert dn.path == "bar.json"
  273. def test_read_write_after_modify_path(self):
  274. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_dict.json")
  275. new_path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/temp.json")
  276. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"default_path": path})
  277. read_data = dn.read()
  278. assert read_data is not None
  279. dn.path = new_path
  280. with pytest.raises(FileNotFoundError):
  281. dn.read()
  282. dn.write({"other": "stuff"})
  283. assert dn.read() == {"other": "stuff"}
  284. def test_get_system_modified_date_instead_of_last_edit_date(self, tmpdir_factory):
  285. temp_file_path = str(tmpdir_factory.mktemp("data").join("temp.json"))
  286. pd.DataFrame([]).to_json(temp_file_path)
  287. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": temp_file_path})
  288. dn.write([1, 2, 3])
  289. previous_edit_date = dn.last_edit_date
  290. sleep(0.1)
  291. pd.DataFrame([4, 5, 6]).to_json(temp_file_path)
  292. new_edit_date = datetime.datetime.fromtimestamp(os.path.getmtime(temp_file_path))
  293. assert previous_edit_date < dn.last_edit_date
  294. assert new_edit_date == dn.last_edit_date
  295. sleep(0.1)
  296. dn.write([1, 2, 3])
  297. assert new_edit_date < dn.last_edit_date
  298. os.unlink(temp_file_path)
  299. def test_migrate_to_new_path(self, tmp_path):
  300. _base_path = os.path.join(tmp_path, ".data")
  301. path = os.path.join(_base_path, "test.json")
  302. # create a file on old path
  303. os.mkdir(_base_path)
  304. with open(path, "w"):
  305. pass
  306. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": path})
  307. assert ".data" not in dn.path
  308. assert os.path.exists(dn.path)
  309. def test_get_download_path(self):
  310. path = os.path.join(pathlib.Path(__file__).parent.resolve(), "data_sample/json/example_dict.json")
  311. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": path})
  312. assert dn._get_downloadable_path() == path
  313. def test_get_download_path_with_not_existed_file(self):
  314. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": "NOT_EXISTED.json"})
  315. assert dn._get_downloadable_path() == ""
  316. def test_upload(self, json_file, tmpdir_factory):
  317. old_json_path = tmpdir_factory.mktemp("data").join("df.json").strpath
  318. old_data = [{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}]
  319. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": old_json_path})
  320. dn.write(old_data)
  321. old_last_edit_date = dn.last_edit_date
  322. with open(json_file, "r") as f:
  323. upload_content = json.load(f)
  324. with freezegun.freeze_time(old_last_edit_date + datetime.timedelta(seconds=1)):
  325. dn._upload(json_file)
  326. assert dn.read() == upload_content # The content of the dn should change to the uploaded content
  327. assert dn.last_edit_date > old_last_edit_date
  328. assert dn.path == old_json_path # The path of the dn should not change
  329. def test_upload_with_upload_check(self, json_file, tmpdir_factory):
  330. old_json_path = tmpdir_factory.mktemp("data").join("df.json").strpath
  331. old_data = [{"a": 0, "b": 1, "c": 2}, {"a": 3, "b": 4, "c": 5}]
  332. dn = JSONDataNode("foo", Scope.SCENARIO, properties={"path": old_json_path})
  333. dn.write(old_data)
  334. old_last_edit_date = dn.last_edit_date
  335. def check_data_keys(upload_path, upload_data):
  336. all_column_is_abc = all(data.keys() == {"a", "b", "c"} for data in upload_data)
  337. return upload_path.endswith(".json") and all_column_is_abc
  338. not_exists_json_path = tmpdir_factory.mktemp("data").join("not_exists.json").strpath
  339. reasons = dn._upload(not_exists_json_path, upload_checker=check_data_keys)
  340. assert bool(reasons) is False
  341. assert (
  342. str(list(reasons._reasons[dn.id])[0]) == "The uploaded file not_exists.json can not be read,"
  343. f' therefore is not a valid data file for data node "{dn.id}"'
  344. )
  345. not_json_path = tmpdir_factory.mktemp("data").join("wrong_format_df.not_json").strpath
  346. with open(not_json_path, "w") as f:
  347. json.dump([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}], f)
  348. # The upload should fail when the file is not a json
  349. reasons = dn._upload(not_json_path, upload_checker=check_data_keys)
  350. assert bool(reasons) is False
  351. assert (
  352. str(list(reasons._reasons[dn.id])[0])
  353. == f'The uploaded file wrong_format_df.not_json has invalid data for data node "{dn.id}"'
  354. )
  355. wrong_format_json_path = tmpdir_factory.mktemp("data").join("wrong_format_df.json").strpath
  356. with open(wrong_format_json_path, "w") as f:
  357. json.dump([{"a": 1, "b": 2, "d": 3}, {"a": 4, "b": 5, "d": 6}], f)
  358. # The upload should fail when check_data_keys() return False
  359. reasons = dn._upload(wrong_format_json_path, upload_checker=check_data_keys)
  360. assert bool(reasons) is False
  361. assert (
  362. str(list(reasons._reasons[dn.id])[0])
  363. == f'The uploaded file wrong_format_df.json has invalid data for data node "{dn.id}"'
  364. )
  365. assert dn.read() == old_data # The content of the dn should not change when upload fails
  366. assert dn.last_edit_date == old_last_edit_date # The last edit date should not change when upload fails
  367. assert dn.path == old_json_path # The path of the dn should not change
  368. # The upload should succeed when check_data_keys() return True
  369. assert dn._upload(json_file, upload_checker=check_data_keys)