File: test_keys_function.py

package info (click to toggle)
python-jsonpath 2.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,028 kB
  • sloc: python: 9,473; makefile: 6
file content (60 lines) | stat: -rw-r--r-- 1,533 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import dataclasses
import operator
from typing import Any
from typing import Mapping
from typing import Sequence
from typing import Union

import pytest

from jsonpath import JSONPathEnvironment
from jsonpath import function_extensions


@dataclasses.dataclass
class Case:
    description: str
    path: str
    data: Union[Sequence[Any], Mapping[str, Any]]
    want: Union[Sequence[Any], Mapping[str, Any]]


TEST_CASES = [
    Case(
        description="value in keys of an object",
        path="$.some[?'thing' in keys(@)]",
        data={"some": [{"thing": "foo"}]},
        want=[{"thing": "foo"}],
    ),
    Case(
        description="value not in keys of an object",
        path="$.some[?'else' in keys(@)]",
        data={"some": [{"thing": "foo"}]},
        want=[],
    ),
    Case(
        description="keys of an array",
        path="$[?'thing' in keys(@)]",
        data={"some": [{"thing": "foo"}]},
        want=[],
    ),
    Case(
        description="keys of an string value",
        path="$some[0].thing[?'else' in keys(@)]",
        data={"some": [{"thing": "foo"}]},
        want=[],
    ),
]


@pytest.fixture()
def env() -> JSONPathEnvironment:
    _env = JSONPathEnvironment()
    _env.function_extensions["keys"] = function_extensions.Keys()
    return _env


@pytest.mark.parametrize("case", TEST_CASES, ids=operator.attrgetter("description"))
def test_isinstance_function(env: JSONPathEnvironment, case: Case) -> None:
    path = env.compile(case.path)
    assert path.findall(case.data) == case.want