1
0

test_json_data_node.py 20 KB

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