示例#1
0
def test_structure_hook_func():
    """ testing the hook_func method """
    converter = Converter()

    def can_handle(cls):
        return cls.__name__.startswith("F")

    def handle(obj, cls):
        return "hi"

    class Foo(object):
        pass

    class Bar(object):
        pass

    converter.register_structure_hook_func(can_handle, handle)

    assert converter.structure(10, Foo) == "hi"
    with raises(ValueError):
        converter.structure(10, Bar)
示例#2
0
def test_optional_field_roundtrip(cl_and_vals):
    """
    Classes with optional fields can be unstructured and structured.
    """
    converter = Converter()
    cl, vals = cl_and_vals

    @attr.s
    class C(object):
        a = attr.ib(type=Optional[cl])

    inst = C(a=cl(*vals))
    assert inst == converter.structure(converter.unstructure(inst), C)

    inst = C(a=None)
    unstructured = converter.unstructure(inst)

    assert inst == converter.structure(unstructured, C)
示例#3
0
def test_union_field_roundtrip(cl_and_vals_a, cl_and_vals_b, strat):
    """
    Classes with union fields can be unstructured and structured.
    """
    converter = Converter(unstruct_strat=strat)
    cl_a, vals_a = cl_and_vals_a
    cl_b, _ = cl_and_vals_b
    a_field_names = {a.name for a in fields(cl_a)}
    b_field_names = {a.name for a in fields(cl_b)}
    assume(a_field_names)
    assume(b_field_names)

    common_names = a_field_names & b_field_names
    assume(len(a_field_names) > len(common_names))

    @attr.s
    class C(object):
        a = attr.ib(type=Union[cl_a, cl_b])

    inst = C(a=cl_a(*vals_a))

    if strat is UnstructureStrategy.AS_DICT:
        unstructured = converter.unstructure(inst)
        assert inst == converter.structure(
            converter.unstructure(unstructured), C
        )
    else:
        # Our disambiguation functions only support dictionaries for now.
        with pytest.raises(ValueError):
            converter.structure(converter.unstructure(inst), C)

        def handler(obj, _):
            return converter.structure(obj, cl_a)

        converter.register_structure_hook(Union[cl_a, cl_b], handler)
        unstructured = converter.unstructure(inst)
        assert inst == converter.structure(unstructured, C)
示例#4
0
def test_310_optional_field_roundtrip(cl_and_vals):
    """
    Classes with optional fields can be unstructured and structured.
    """
    converter = Converter()
    cl, vals = cl_and_vals

    @define
    class C:
        a: cl | None

    inst = C(a=cl(*vals))
    assert inst == converter.structure(converter.unstructure(inst), C)

    inst = C(a=None)
    unstructured = converter.unstructure(inst)

    assert inst == converter.structure(unstructured, C)
示例#5
0
from twisted.logger import Logger

from ims.ext.json import dateTimeAsRFC3339Text, rfc3339TextAsDateTime

__all__ = ()

log = Logger()


class JSONCodecError(Exception):
    """
    Error while serializing or deserializing JSON data.
    """


converter = Converter()
jsonSerialize = converter.unstructure
jsonDeserialize = converter.structure

registerSerializer = converter.register_unstructure_hook
registerDeserializer = converter.register_structure_hook

# Serialization hooks

registerSerializer(DateTime, dateTimeAsRFC3339Text)

# Deserialization hooks


def deserializeDateTime(obj: str, cl: Type) -> DateTime:
    assert cl is DateTime, (cl, obj)
示例#6
0
def test_able_to_structure_generics(converter: Converter, t, t2, result):
    res = converter.structure(asdict(result), TClass[t, t2])

    assert res == result
示例#7
0
from enum import Enum, IntEnum, unique
from typing import List, Optional

import attr
from aiohttp import ClientSession
from cattr import Converter
from pendulum import DateTime, from_timestamp
from ujson import dumps, loads

from pyrseia import create_client, rpc
from pyrseia.aiohttp import aiohttp_client_adapter
from pyrseia.wire import Call

PRODUCTION_URL = "https://buy.itunes.apple.com/verifyReceipt"
SANDBOX_URL = "https://sandbox.itunes.apple.com/verifyReceipt"
APP_STORE_CONVERTER = Converter()

APP_STORE_CONVERTER.register_structure_hook(
    DateTime, lambda m, _: from_timestamp(float(m) / 1000)
)


@attr.s(slots=True, frozen=True)
class ResponseBody:
    """This structure is called 'responseBody' by Apple."""

    @unique
    class Environment(str, Enum):
        SANDBOX = "Sandbox"
        PRODUCTION = "Production"
示例#8
0
def create_cattrs_converter():
    converter = Converter()
    converter.register_structure_hook(bool, _structure_bool)
    converter.register_structure_hook(string_type, _structure_string)
    converter.register_structure_hook(Model, _structure_schematics)
    converter.register_structure_hook(BaseType, _structure_basetype)
    converter.register_structure_hook(datetime, _structure_datetime)
    converter.register_unstructure_hook(Model, _unstructure_schematics)
    converter.register_unstructure_hook(datetime, _unstructure_datetime)
    converter.register_unstructure_hook(BaseType, _unstructure_basetype)
    return converter
示例#9
0
else:
    import pickle
    pickle_loads = f.partial(pickle.loads, encoding='bytes')
    pickle_load = f.partial(pickle.load, encoding='bytes')
    pickle_dumps = f.partial(pickle.dumps, protocol=2)
    pickle_dump = f.partial(pickle.dump, protocol=2)


def u2c(value):
    """Convert underscore string to capitalized string."""
    # Make a list of capitalized words and underscores to be preserved
    capitalized_words = [w.capitalize() if w else '_' for w in value.split('_')]
    return "".join(capitalized_words)


CUSTOM_CVT = Converter()
CUSTOM_CVT.register_unstructure_hook(
    np.ndarray, lambda a: dict(dtype=a.dtype.name, data=a.tobytes(), shape=list(a.shape)))


CUSTOM_CVT.register_structure_hook(
    np.ndarray, lambda a, _: np.frombuffer(a['data'], dtype=a['dtype']).reshape(tuple(a['shape'])))


def to_dict(obj):
    """Convert object to dict"""
    global CUSTOM_CVT
    return CUSTOM_CVT.unstructure(obj)


def from_dict(d, cls, compatible=True):
示例#10
0
def converter():
    return Converter()
示例#11
0
def test_structuring_primitives(primitive_and_type):
    """Test just structuring a primitive value."""
    converter = Converter()
    val, t = primitive_and_type
    assert converter.structure(val, t) == val
    assert converter.structure(val, Any) == val
示例#12
0
def test_structuring_enums(data, enum):
    """Test structuring enums by their values."""
    converter = Converter()
    val = data.draw(sampled_from(list(enum)))

    assert converter.structure(val.value, enum) == val
示例#13
0
def setup_cattrs(converter: cattr.Converter) -> None:
    # mypy cannot infer :(
    def unstructure_snowflake(struct: Snowflake) -> str:
        return str(struct)

    converter.register_unstructure_hook(Snowflake, unstructure_snowflake)
示例#14
0
from schematics.types import DateTimeType

datetime_type = DateTimeType()


def _structure_datetime(data, cls):
    if not data:
        raise ValueError("datetime is empty")
    return datetime_type.to_native(data)


def _unstructure_datetime(data):
    return data.isoformat()


converter = Converter()
converter.register_structure_hook(datetime, _structure_datetime)
converter.register_unstructure_hook(datetime, _unstructure_datetime)


def validate_len(instance, attribute, value):
    if len(value) > 100:
        raise ValueError("val should <= 100")


@attr.s
class Artist2:
    name = attr.ib(type=str, validator=validate_len)


@attr.s