Ejemplo n.º 1
0
def test_proto_iterate():
    @dataclasses.dataclass
    class Foo:
        bar: str = None

    proto = typic.protocol(Foo)

    assert dict(proto.iterate(Foo())) == {"bar": None}
    assert [*proto.iterate(Foo(), values=True)] == [None]
Ejemplo n.º 2
0
def test_routine_protocol():
    def foo():
        ...

    proto = typic.protocol(foo)
    assert proto.transmute(foo) is foo
    assert proto.validate(foo) is foo
    with pytest.raises(TypeError):
        proto.serialize(foo)

    assert list(proto.iterate(foo)) == [None]
Ejemplo n.º 3
0
def test_custom_decode():
    def decode(o):
        return o.decode("utf-8-sig")

    @dataclasses.dataclass
    class Foo:
        bar: str = None

    proto = typic.protocol(Foo, flags=typic.flags(decoder=decode))
    inp = '{"bar":null}'.encode("utf-8-sig")
    dec = proto.decode(inp)
    assert dec == Foo()
Ejemplo n.º 4
0
def test_custom_encode():
    def encode(o):
        return ujson.encode(o).encode("utf-8-sig")

    @dataclasses.dataclass
    class Foo:
        bar: str = None

    proto = typic.protocol(Foo, flags=typic.flags(encoder=encode))
    enc = proto.encode(Foo())
    assert isinstance(enc, bytes)
    assert enc.decode("utf-8-sig") == '{"bar":null}'
Ejemplo n.º 5
0
@dataclasses.dataclass
class Model:
    id: int
    client_name: DBString
    sort_index: float
    client_phone: Optional[DBString] = None
    grecaptcha_response: Optional[GReCaptchaResponse] = None
    location: Optional[Location] = None
    contractor: Optional[PositiveInt] = None
    upstream_http_referrer: Optional[HTTPReferer] = None
    last_updated: Optional[datetime] = None
    skills: List[Skill] = dataclasses.field(default_factory=list)


model_protocol = typic.protocol(Model)


def validate(data):
    try:
        return True, model_protocol.validate(data)
    except ValueError as err:
        return False, err


def deserialize(data):
    try:
        return True, model_protocol.transmute(data)
    except (TypeError, ValueError) as err:
        return False, err
Ejemplo n.º 6
0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# flake8: noqa
import enum
from typing import Union

import typic

from .base import *
from .node import *
from .index import *


class InputType(str, enum.Enum):
    HTML = "html"
    MD = "markdown"
    DATA = "data"


protocol = typic.protocol(Union[Play, ResolvedNodeT])  # type: ignore
Ejemplo n.º 7
0
def test_invalid_serializer(type, value):
    proto = typic.protocol(type)
    with pytest.raises(ValueError):
        proto.tojson(value)