示例#1
0
def test_json_to_cel():
    """GIVEN JSON doc; WHEN json_to_cell(); THEN expected conversions applied."""
    doc = [
        {
            "bool": True
        },
        {
            "numbers": [2.71828, 42]
        },
        {
            "null": None
        },
        {
            "string": 'embedded "quote"'
        },
    ]
    actual = celpy.json_to_cel(doc)
    expected = celtypes.ListType([
        celtypes.MapType(
            {celtypes.StringType("bool"): celtypes.BoolType(True)}),
        celtypes.MapType({
            celtypes.StringType("numbers"):
            celtypes.ListType(
                [celtypes.DoubleType(2.71828),
                 celtypes.IntType(42)])
        }),
        celtypes.MapType({celtypes.StringType("null"): None}),
        celtypes.MapType({
            celtypes.StringType("string"):
            celtypes.StringType('embedded "quote"')
        }),
    ])
    assert actual == expected
示例#2
0
def json_to_cel(document: JSON) -> celtypes.Value:
    """Convert parsed JSON object from Python to CEL to the extent possible.

    It's difficult to distinguish strings which should be timestamps or durations.

    ::

        >>> from pprint import pprint
        >>> from celpy.adapter import json_to_cel
        >>> doc = json.loads('["str", 42, 3.14, null, true, {"hello": "world"}]')
        >>> cel = json_to_cel(doc)
        >>> pprint(cel)
        ListType([StringType('str'), IntType(42), DoubleType(3.14), None, BoolType(True), \
MapType({StringType('hello'): StringType('world')})])
    """
    if isinstance(document, bool):
        return celtypes.BoolType(document)
    elif isinstance(document, float):
        return celtypes.DoubleType(document)
    elif isinstance(document, int):
        return celtypes.IntType(document)
    elif isinstance(document, str):
        return celtypes.StringType(document)
    elif document is None:
        return None
    elif isinstance(document, List):
        return celtypes.ListType([json_to_cel(item) for item in document])
    elif isinstance(document, Dict):
        return celtypes.MapType({
            json_to_cel(key): json_to_cel(value)
            for key, value in document.items()
        })
    else:
        raise ValueError(
            f"unexpected type {type(document)} in JSON structure {document!r}")
示例#3
0
def mock_cel_environment_integer(monkeypatch):
    mock_runner = Mock(evaluate=Mock(
        return_value=celtypes.IntType(3735928559)))
    mock_env = Mock(compile=Mock(return_value=sentinel.AST),
                    program=Mock(return_value=mock_runner))
    mock_env_class = Mock(return_value=mock_env)
    monkeypatch.setattr(celpy.__main__, "Environment", mock_env_class)
    return mock_env_class
示例#4
0
def test_decoder():
    json_text = (
        '{"bool": 1, "numbers": [2.71828, 42], "null": null, '
        '"string": "embedded \\"quote\\"", "bytes": "Ynl0ZXM=", '
        '"timestamp": "2009-02-13T23:31:30Z", "duration": "42s"}'
     )
    cel_obj = json.loads(json_text, cls=celpy.CELJSONDecoder)
    assert cel_obj == celtypes.MapType({
        celtypes.StringType('bool'): celtypes.IntType(1),
        celtypes.StringType('bytes'): celtypes.StringType('Ynl0ZXM='),
        celtypes.StringType('duration'): celtypes.StringType('42s'),
        celtypes.StringType('null'): None,
        celtypes.StringType('numbers'):
            celtypes.ListType([celtypes.DoubleType(2.71828), celtypes.IntType(42)]),
        celtypes.StringType('string'): celtypes.StringType('embedded "quote"'),
        celtypes.StringType('timestamp'): celtypes.StringType('2009-02-13T23:31:30Z'),
    })
示例#5
0
def size_parse_cidr(
    value: celtypes.StringType, ) -> Optional[celtypes.IntType]:
    """CIDR prefixlen value"""
    cidr = parse_cidr(value)  # type: ignore[no-untyped-call]
    if cidr:
        return celtypes.IntType(cidr.prefixlen)
    else:
        return None
示例#6
0
def unique_size(collection: celtypes.ListType) -> celtypes.IntType:
    """
    Unique size of a list
    """
    return celtypes.IntType(len(set(collection)))