Ejemplo n.º 1
0
def test_evaluate_jsonpointer(value, testkey):
    resolved_pointers = {}

    def generate_pointers(ptr, val):
        resolved_pointers[ptr] = val
        if isinstance(val, list):
            for i, item in enumerate(val):
                generate_pointers(f'{ptr}/{i}', item)
        elif isinstance(val, dict):
            for k, item in val.items():
                generate_pointers(f"{ptr}/{jsonpointer_escape(k)}", item)

    assert JSONPointer().evaluate(value) == value
    assert JSONPointer().evaluate(JSON(value)) == value

    generate_pointers('', value)
    for pointer, target in resolved_pointers.items():
        assert JSONPointer(pointer).evaluate(value) == target
        assert JSONPointer(pointer).evaluate(JSON(value)) == target

    if isinstance(value, list):
        with pytest.raises(JSONPointerError):
            JSONPointer(f'/{len(value)}').evaluate(value)
        with pytest.raises(JSONPointerError):
            JSONPointer('/-').evaluate(value)
        with pytest.raises(JSONPointerError):
            JSONPointer('/').evaluate(value)
    elif isinstance(value, dict):
        if testkey not in value:
            with pytest.raises(JSONPointerError):
                JSONPointer(f'/{jsonpointer_escape(testkey)}').evaluate(value)
    else:
        with pytest.raises(JSONPointerError):
            JSONPointer(f'/{value}').evaluate(value)
Ejemplo n.º 2
0
def test_jsonpointer_invalid(instval):
    result = evaluate("json-pointer", instval)
    try:
        JSONPointer(instval)
        assert result is True
    except JSONPointerError:
        assert result is False
Ejemplo n.º 3
0
def test_get_schema(example_schema_uri, ptr, is_schema):
    uri = example_schema_uri.copy(fragment=ptr)
    if is_schema:
        subschema = Catalogue.get_schema(uri)
        assert JSONPointer(ptr).evaluate(example_schema) == subschema
    else:
        with pytest.raises(CatalogueError):
            Catalogue.get_schema(uri)
Ejemplo n.º 4
0
def assert_json_node(
    inst: JSON,
    val: AnyJSONCompatible,
    parent: Optional[JSON],
    key: Optional[str],
    ptr: str,
):
    assert inst.value == (Decimal(f'{val}') if isinstance(val, float) else val)
    assert inst.parent == parent
    assert inst.key == key
    assert inst.path == JSONPointer(ptr)

    if val is None:
        assert inst.type == "null"
    elif isinstance(val, bool):
        assert inst.type == "boolean"
    elif isinstance(val, (int, float, Decimal)):
        assert inst.type == "number"
    elif isinstance(val, str):
        assert inst.type == "string"
    elif isinstance(val, list):
        assert inst.type == "array"
        for i, el in enumerate(val):
            assert_json_node(inst[i], el, inst, str(i), f'{inst.path}/{i}')
    elif isinstance(val, dict):
        assert inst.type == "object"
        for k, v in val.items():
            assert_json_node(inst[k], v, inst, k,
                             f'{inst.path}/{jsonpointer_escape(k)}')
    else:
        assert False

    assert bool(inst) == bool(val)

    if isinstance(val, (str, list, dict)):
        assert len(inst) == len(val)
    else:
        with pytest.raises(TypeError):
            len(inst)

    if not isinstance(val, (list, dict)):
        with pytest.raises(TypeError):
            iter(inst)

    if not isinstance(val, list):
        with pytest.raises(TypeError):
            _ = inst[0]

    if not isinstance(val, dict):
        with pytest.raises(TypeError):
            _ = inst['']
Ejemplo n.º 5
0
def test_create_jsonpointer(values: List[Union[str, List[str]]]):
    keys = []
    for value in values:
        keys += [jsonpointer_unescape(token) for token in value.split('/')[1:]] if isinstance(value, str) else value

    ptr0 = JSONPointer(*values)
    assert ptr0 == (ptr1 := JSONPointer(*values))
    assert ptr0 == (ptr2 := JSONPointer(keys))
    assert ptr0 == (ptr3 := JSONPointer(ptr0))
    assert ptr0 != (ptr4 := JSONPointer() if keys else JSONPointer('/'))
    assert ptr0 != (ptr5 := JSONPointer('/', keys))
    assert JSONPointer(ptr0, keys, *values) == JSONPointer(*values, keys, ptr0)

    ptrs = {ptr0, ptr1, ptr2, ptr3}
    assert ptrs == {ptr0}
    ptrs |= {ptr4, ptr5}
    assert ptrs > {ptr0}

    assert str(ptr0) == ''.join(f'/{jsonpointer_escape(key)}' for key in keys)
    assert list(ptr0) == keys
    assert bool(ptr0) == bool(keys)
    assert eval(repr(ptr0)) == ptr0
Ejemplo n.º 6
0
def test_uri(ptr: str, uri: str, canonical: bool):
    rootschema = JSONSchema(id_example, metaschema_uri=metaschema_uri_2020_12)
    schema: JSONSchema = JSONPointer.parse_uri_fragment(
        ptr[1:]).evaluate(rootschema)
    assert schema == Catalogue.get_schema(uri := URI(uri))
    if canonical:
        # 'canonical' is as per the JSON Schema spec; however, we skip testing of
        # anchored URIs since we have only one way to calculate a schema's canonical URI
        if (fragment := uri.fragment) and not fragment.startswith('/'):
            return

        if fragment:
            # allow chars in the RFC3986 'sub-delims' set in the 'safe' arg,
            # since these are allowed by the 'fragment' definition; in particular,
            # this means we don't percent encode '$'
            uri = uri.copy(
                fragment=urllib.parse.quote(fragment, safe="/!$&'()*+,;="))
        else:
            # remove empty fragment
            uri = uri.copy(fragment=False)

        assert schema.canonical_uri == uri
Ejemplo n.º 7
0
def test_base_uri(ptr: str, base_uri: str):
    rootschema = JSONSchema(id_example, metaschema_uri=metaschema_uri_2020_12)
    schema: JSONSchema = JSONPointer.parse_uri_fragment(
        ptr[1:]).evaluate(rootschema)
    assert schema.base_uri == URI(base_uri)
Ejemplo n.º 8
0
def test_extend_jsonpointer_multi_keys(value, newkeys):
    pointer = (base_ptr := JSONPointer(value)) / newkeys
    for i in range(len(newkeys)):
        assert pointer[len(base_ptr) + i] == newkeys[i]
    assert str(pointer) == value + ''.join(f'/{jsonpointer_escape(key)}' for key in newkeys)
Ejemplo n.º 9
0
def test_extend_jsonpointer_one_key(value, newkey):
    pointer = JSONPointer(value) / newkey
    newtoken = jsonpointer_escape(newkey)
    assert pointer[-1] == newkey
    assert str(pointer) == f'{value}/{newtoken}'
Ejemplo n.º 10
0
def jsonpointer_validator(value):
    if isinstance(value, str):
        try:
            JSONPointer(value)
        except JSONPointerError as e:
            raise ValueError(str(e))