File: test_examples.py

package info (click to toggle)
jsonpath-ng 1.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 372 kB
  • sloc: python: 2,172; makefile: 4
file content (77 lines) | stat: -rw-r--r-- 2,452 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import pytest

from jsonpath_ng.ext import parse
from jsonpath_ng.ext.filter import Expression, Filter
from jsonpath_ng.jsonpath import Child, Descendants, Fields, Index, Root, Slice, This


@pytest.mark.parametrize(
    "string, parsed",
    [
        # The authors of all books in the store
        (
            "$.store.book[*].author",
            Child(
                Child(Child(Child(Root(), Fields("store")), Fields("book")), Slice()),
                Fields("author"),
            ),
        ),
        #
        # All authors
        ("$..author", Descendants(Root(), Fields("author"))),
        #
        # All things in the store
        ("$.store.*", Child(Child(Root(), Fields("store")), Fields("*"))),
        #
        # The price of everything in the store
        (
            "$.store..price",
            Descendants(Child(Root(), Fields("store")), Fields("price")),
        ),
        #
        # The third book
        ("$..book[2]", Child(Descendants(Root(), Fields("book")), Index(2))),
        #
        # The last book in order
        # "$..book[(@.length-1)]"  # Not implemented
        ("$..book[-1:]", Child(Descendants(Root(), Fields("book")), Slice(start=-1))),
        #
        # The first two books
        # "$..book[0,1]"  # Not implemented
        ("$..book[:2]", Child(Descendants(Root(), Fields("book")), Slice(end=2))),
        #
        # Filter all books with an ISBN
        (
            "$..book[?(@.isbn)]",
            Child(
                Descendants(Root(), Fields("book")),
                Filter([Expression(Child(This(), Fields("isbn")), None, None)]),
            ),
        ),
        #
        # Filter all books cheaper than 10
        (
            "$..book[?(@.price<10)]",
            Child(
                Descendants(Root(), Fields("book")),
                Filter([Expression(Child(This(), Fields("price")), "<", 10)]),
            ),
        ),
        #
        # All members of JSON structure
        ("$..*", Descendants(Root(), Fields("*"))),
    ],
)
def test_goessner_examples(string, parsed):
    """
    Test Stefan Goessner's `examples`_

    .. _examples: https://goessner.net/articles/JsonPath/index.html#e3
    """
    assert parse(string, debug=True) == parsed


def test_attribute_and_dict_syntax():
    """Verify that attribute and dict syntax result in identical parse trees."""

    assert parse("$.store.book[0].title") == parse("$['store']['book'][0]['title']")