Debian Codegraph @

tests/test_path.py

raw
1 import pytest
2 from deepdiff.path import _path_to_elements, GET, GETATTR, extract, parse_path, stringify_path, _add_to_elements
3
4
5 @pytest.mark.parametrize('test_num, path, expected', [
6 (1, "root[4]['b'][3]", [(4, GET), ('b', GET), (3, GET)]),
7 (2, "root[4].b[3]", [(4, GET), ('b', GETATTR), (3, GET)]),
8 (3, "root[4].b['a3']", [(4, GET), ('b', GETATTR), ('a3', GET)]),
9 (4, "root[4.3].b['a3']", [(4.3, GET), ('b', GETATTR), ('a3', GET)]),
10 (5, "root.a.b", [('a', GETATTR), ('b', GETATTR)]),
11 (6, "root.hello", [('hello', GETATTR)]),
12 (7, "root['h']", [('h', GET)]),
13 (8, "root['a\rb']", [('a\rb', GET)]),
14 (9, "root['a\\rb']", [('a\\rb', GET)]),
15 (10, "root", []),
16 (11, ((4, GET), ('b', GET)), ((4, GET), ('b', GET))),
17 ])
18 def test_path_to_elements(test_num, path, expected):
19 result = _path_to_elements(path, root_element=None)
20 assert tuple(expected) == result, f"test_path_to_elements #{test_num} failed"
21 if isinstance(path, str):
22 path_again = stringify_path(path=result)
23 assert path == path_again, f"test_path_to_elements #{test_num} failed"
24
25
26 @pytest.mark.parametrize('obj, path, expected', [
27 ({1: [2, 3], 2: [4, 5]},
28 "root[2][1]",
29 5),
30 ({1: [{'2': 'b'}, 3], 2: {4, 5}},
31 "root[1][0]['2']",
32 'b'
33 ),
34 ({'test [a]': 'b'},
35 "root['test [a]']",
36 'b'
37 ),
38 ({"a']['b']['c": 1},
39 """root["a']['b']['c"]""",
40 1
41 ),
42 ])
43 def test_get_item(obj, path, expected):
44 result = extract(obj, path)
45 assert expected == result
46
47
48 def test_parse_path():
49 result = parse_path("root[1][2]['age']")
50 assert [1, 2, 'age'] == result
51 result2 = parse_path("root[1][2]['age']", include_actions=True)
52 assert [{'element': 1, 'action': 'GET'}, {'element': 2, 'action': 'GET'}, {'element': 'age', 'action': 'GET'}] == result2
53 result3 = parse_path("root['joe'].age")
54 assert ['joe', 'age'] == result3
55 result4 = parse_path("root['joe'].age", include_actions=True)
56 assert [{'element': 'joe', 'action': 'GET'}, {'element': 'age', 'action': 'GETATTR'}] == result4
57
58
59 @pytest.mark.parametrize('test_num, elem, inside, expected', [
60 (
61 1,
62 "'hello'",
63 None,
64 [('hello', GET)],
65 ),
66 (
67 2,
68 "'a\rb'",
69 None,
70 [('a\rb', GET)],
71 ),
72 ])
73 def test__add_to_elements(test_num, elem, inside, expected):
74 elements = []
75 _add_to_elements(elements, elem, inside)
76 assert expected == elements