|
| 1 | +import dataclasses |
| 2 | +import operator |
| 3 | +from typing import Any |
| 4 | +from typing import Mapping |
| 5 | +from typing import Sequence |
| 6 | +from typing import Union |
| 7 | + |
| 8 | +import pytest |
| 9 | + |
| 10 | +from jsonpath import JSONPathEnvironment |
| 11 | +from jsonpath import function_extensions |
| 12 | + |
| 13 | + |
| 14 | +@dataclasses.dataclass |
| 15 | +class Case: |
| 16 | + description: str |
| 17 | + path: str |
| 18 | + data: Union[Sequence[Any], Mapping[str, Any]] |
| 19 | + want: Union[Sequence[Any], Mapping[str, Any]] |
| 20 | + |
| 21 | + |
| 22 | +SOME_OBJECT = object() |
| 23 | + |
| 24 | +TEST_CASES = [ |
| 25 | + Case( |
| 26 | + description="value in keys of an object", |
| 27 | + path="$.some[?'thing' in keys(@)]", |
| 28 | + data={"some": [{"thing": "foo"}]}, |
| 29 | + want=[{"thing": "foo"}], |
| 30 | + ), |
| 31 | + Case( |
| 32 | + description="value not in keys of an object", |
| 33 | + path="$.some[?'else' in keys(@)]", |
| 34 | + data={"some": [{"thing": "foo"}]}, |
| 35 | + want=[], |
| 36 | + ), |
| 37 | + Case( |
| 38 | + description="keys of an array", |
| 39 | + path="$[?'thing' in keys(@)]", |
| 40 | + data={"some": [{"thing": "foo"}]}, |
| 41 | + want=[], |
| 42 | + ), |
| 43 | + Case( |
| 44 | + description="keys of an string value", |
| 45 | + path="$some[0].thing[?'else' in keys(@)]", |
| 46 | + data={"some": [{"thing": "foo"}]}, |
| 47 | + want=[], |
| 48 | + ), |
| 49 | +] |
| 50 | + |
| 51 | + |
| 52 | +@pytest.fixture() |
| 53 | +def env() -> JSONPathEnvironment: |
| 54 | + _env = JSONPathEnvironment() |
| 55 | + _env.function_extensions["keys"] = function_extensions.Keys() |
| 56 | + return _env |
| 57 | + |
| 58 | + |
| 59 | +@pytest.mark.parametrize("case", TEST_CASES, ids=operator.attrgetter("description")) |
| 60 | +def test_isinstance_function(env: JSONPathEnvironment, case: Case) -> None: |
| 61 | + path = env.compile(case.path) |
| 62 | + assert path.findall(case.data) == case.want |
0 commit comments