Ejemplo n.º 1
0
def tests_should_deserialize_any():
    @dataclass
    class FakeDataclass:
        test_any: Any

    dataclass1 = asdataclass({'test_any': 0.1}, FakeDataclass)
    any_object = object()
    dataclass2 = asdataclass({'test_any': any_object}, FakeDataclass)

    assert dataclass1 == FakeDataclass(0.1)
    assert dataclass2 == FakeDataclass(any_object)
Ejemplo n.º 2
0
def as_request(
    request_cls: Type[Request],
    body: bytes,
    path_args: AsgiPathArgs = {},
    query_dict: AsgiQueryDict = {},
    headers: AsgiHeaders = [],
) -> Request:
    annotations = getattr(request_cls, '__annotations__', {})
    path_args_cls = annotations.get('path_args', PathArgs)
    query_cls = annotations.get('query', Query)
    headers_cls = annotations.get('headers', Headers)
    body_cls = annotations.get('body', Body)
    request_path_args = as_typed_dict(path_args, path_args_cls)
    request_query = get_query(query_cls, query_dict)
    request_headers = get_headers(headers_cls, headers)
    content_type = request_headers.get('content_type')
    parsed_body: Any = None

    if content_type is None or content_type is ContentType.APPLICATION_JSON:
        parsed_body = orjson.loads(body) if body else {}
        parsed_body = as_typed_dict_field(parsed_body, 'body', body_cls)
    else:
        parsed_body = body.decode()

    return asdataclass(  # type: ignore
        dict(
            path_args=request_path_args,
            query=request_query,
            headers=request_headers,
            body=parsed_body if parsed_body else None,
        ),
        request_cls,
        skip_fields=('body', ),
    )
Ejemplo n.º 3
0
def tests_should_deserialize_dict_args_nested():
    @dataclass
    class FakeDataclass:
        test: str

    @dataclass
    class FakeDataclass2:
        fakes: Dict[int, List[FakeDataclass]]
        fakeint: int

    fakes_data = {
        b'1': [{'test': 'fake11'}, {'test': 'fake12'}, {'test': 'fake13'}]
    }
    dataclass_ = asdataclass(
        {'fakes': fakes_data, 'fakeint': '1'}, FakeDataclass2
    )

    assert dataclass_ == FakeDataclass2(
        {
            1: [
                FakeDataclass('fake11'),
                FakeDataclass('fake12'),
                FakeDataclass('fake13'),
            ]
        },
        1,
    )
Ejemplo n.º 4
0
def tests_should_deserialize_set_args():
    @dataclass
    class FakeDataclass:
        test_set: Set[int]

    dataclass_ = asdataclass({'test_set': [b'1', '2', 3]}, FakeDataclass)

    assert dataclass_ == FakeDataclass({1, 2, 3})
Ejemplo n.º 5
0
def tests_should_deserialize_tuple_args():
    @dataclass
    class FakeDataclass:
        test_tuple: Tuple[int, ...]

    dataclass_ = asdataclass({'test_tuple': [b'1', '2', 3]}, FakeDataclass)

    assert dataclass_ == FakeDataclass((1, 2, 3))
Ejemplo n.º 6
0
def tests_should_deserialize_tuple_args_limited():
    @dataclass
    class FakeDataclass:
        test_tuple: Tuple[int, str]

    dataclass_ = asdataclass({'test_tuple': [b'1', 2]}, FakeDataclass)

    assert dataclass_ == FakeDataclass((1, '2'))
Ejemplo n.º 7
0
def tests_should_deserialize_union_args():
    @dataclass
    class FakeDataclass:
        test_union: Union[int, str]

    dataclass_ = asdataclass({'test_union': b'1'}, FakeDataclass)

    assert dataclass_ == FakeDataclass(1)
Ejemplo n.º 8
0
def tests_should_deserialize_list_args():
    @dataclass
    class FakeDataclass:
        test_list: List[int]

    dataclass_ = asdataclass({'test_list': [b'1', '2', 3]}, FakeDataclass)

    assert dataclass_ == FakeDataclass([1, 2, 3])
Ejemplo n.º 9
0
def tests_should_deserialize_bytes_to_string():
    @dataclass
    class FakeDataclass:
        test_union: str

    dataclass_ = asdataclass({'test_union': b'test'}, FakeDataclass)

    assert dataclass_ == FakeDataclass('test')
Ejemplo n.º 10
0
def tests_should_raise_error_when_deserializing_invalid_tuple_size():
    @dataclass
    class FakeDataclass:
        test: str

    @dataclass
    class FakeDataclass2:
        fakes: Tuple[FakeDataclass, int]
        fakeint: int

    fakes_data = [{'test': 'fake11'}, '1', None]

    with pytest.raises(DeserializationError) as exc_info:
        asdataclass({'fakes': fakes_data, 'fakeint': '1'}, FakeDataclass2)

    assert exc_info.value.args == (
        f'Invalid type={Tuple[FakeDataclass, int]} for field=fakes', )
Ejemplo n.º 11
0
def tests_should_deserialize_dict_args():
    @dataclass
    class FakeDataclass:
        test_dict: Dict[int, str]

    dataclass_ = asdataclass(
        {'test_dict': {b'1': b'1', '2': '2', 3: 3}}, FakeDataclass
    )

    assert dataclass_ == FakeDataclass({1: '1', 2: '2', 3: '3'})
Ejemplo n.º 12
0
def tests_should_choose_fields_to_deserialize():
    @jsondaora(deserialize_fields=('test2', ))
    @dataclass
    class FakeDataclass:
        test: int
        test2: str

    dataclass_ = asdataclass({'test': '1', 'test2': 2}, FakeDataclass)

    assert dataclass_ == FakeDataclass('1', '2')
Ejemplo n.º 13
0
def tests_should_serialize_all_fields_with_choosen_deserialize_fields():
    @jsondaora(deserialize_fields=('test2', ))
    @dataclass
    class FakeDataclass:
        test: int
        test2: str

    dataclass_ = asdataclass({'test': '1', 'test2': 2}, FakeDataclass)

    assert dataclass_asjson(dataclass_) == b'{"test":"1","test2":"2"}'
Ejemplo n.º 14
0
def tests_should_deserialize_optional_args():
    @dataclass
    class FakeDataclass:
        test: str
        test_default: Optional[int] = None

    dataclass_ = asdataclass(
        {'test': 'test', 'test_default': '1'}, FakeDataclass
    )

    assert dataclass_ == FakeDataclass('test', 1)
Ejemplo n.º 15
0
def tests_should_deserialize_nested_jsondict():
    @dataclass
    class FakeDataclass:
        test: str

    @dataclass
    class FakeDataclass2:
        fake: FakeDataclass

    dataclass_ = asdataclass({'fake': {'test': b'test'}}, FakeDataclass2)

    assert dataclass_ == FakeDataclass2(FakeDataclass('test'))
Ejemplo n.º 16
0
def tests_should_deserialize_nested_dataclass_typed_dict():
    @jsondaora
    class FakeTypedDict(TypedDict):
        test: str

    @jsondaora
    class FakeDataclass:
        fake: FakeTypedDict

    dataclass = asdataclass({'fake': {'test': b'test'}}, FakeDataclass)

    assert dataclass == FakeDataclass(fake={'test': 'test'})
Ejemplo n.º 17
0
def tests_should_deserialize_tuple_args_nested_limited():
    @dataclass
    class FakeDataclass:
        test: str

    @dataclass
    class FakeDataclass2:
        fakes: Tuple[FakeDataclass, int]
        fakeint: int

    fakes_data = [{'test': 'fake11'}, '1']
    dataclass_ = asdataclass(
        {'fakes': fakes_data, 'fakeint': '1'}, FakeDataclass2
    )

    assert dataclass_ == FakeDataclass2((FakeDataclass('fake11'), 1), 1,)
Ejemplo n.º 18
0
def test_should_build_object():
    @jsondaora
    class FakeItem(TypedDict):
        id: str

    values = {
        'id': 'fake_id',
        'title': 'fake_title',
        'medias': ['item1', 'item2'],
        'variations': {
            'qwe': ['case1', 'case2']
        },
    }
    schema = {
        'type': 'object',
        'required': ['id'],
        'properties': {
            'id': {
                'type': 'string'
            },
            'title': {
                'type': 'string'
            },
            'medias': {
                'type': 'array',
                'items': {
                    'type': 'string'
                }
            },
            'variations': {
                'type': 'object',
                'additionalProperties': {
                    'type': 'array',
                    'items': {
                        'type': 'string'
                    },
                },
            },
        },
    }
    type_ = jsonschema_asdataclass('test_id', schema, bases=(FakeItem, ))
    item = asdataclass(values, type_)

    assert item['id'] == values['id']
    assert item['medias'] == values['medias']
    assert item['variations']['qwe'] == values['variations']['qwe']
Ejemplo n.º 19
0
def tests_should_deserialize_any_nested():
    @dataclass
    class FakeDataclass:
        test: str

    @dataclass
    class FakeDataclass2:
        fakes: Set[Any]
        fakeint: int

    any_object = object()
    fakes_data = [any_object, 0.1]
    dataclass_ = asdataclass(
        {'fakes': fakes_data, 'fakeint': '1'}, FakeDataclass2
    )

    assert dataclass_ == FakeDataclass2({any_object, 0.1}, 1,)
Ejemplo n.º 20
0
def tests_should_deserialize_list_args_nested():
    @dataclass
    class FakeDataclass:
        test: str

    @dataclass
    class FakeDataclass2:
        fakes: List[FakeDataclass]
        fakeint: int

    fakes_data = [{'test': 'fake11'}, {'test': 'fake12'}, {'test': 'fake13'}]
    dataclass_ = asdataclass(
        {'fakes': fakes_data, 'fakeint': '1'}, FakeDataclass2
    )

    assert dataclass_ == FakeDataclass2(
        [
            FakeDataclass('fake11'),
            FakeDataclass('fake12'),
            FakeDataclass('fake13'),
        ],
        1,
    )
Ejemplo n.º 21
0
def tests_should_deserialize_set_args_nested():
    @dataclass(unsafe_hash=True)
    class FakeDataclass:
        test: str

    @dataclass
    class FakeDataclass2:
        fakes: Set[FakeDataclass]
        fakeint: int

    fakes_data = [{'test': 'fake11'}, {'test': 'fake12'}, {'test': 'fake13'}]
    dataclass_ = asdataclass(
        {'fakes': fakes_data, 'fakeint': '1'}, FakeDataclass2
    )

    assert dataclass_ == FakeDataclass2(
        {
            FakeDataclass('fake11'),
            FakeDataclass('fake12'),
            FakeDataclass('fake13'),
        },
        1,
    )
Ejemplo n.º 22
0
def tests_should_deserialize_list_args_nested_dataclass_typed_dict():
    @jsondaora
    class FakeTypedDict(TypedDict):
        fakeint: int

    @jsondaora
    class FakeDataclass:
        fakes: List[FakeTypedDict]
        fakefloat: float

    fakes_data = [{'fakeint': '1'}, {'fakeint': '2'}, {'fakeint': '3'}]
    dataclass = asdataclass({
        'fakes': fakes_data,
        'fakefloat': '0.1'
    }, FakeDataclass)

    assert dataclass == FakeDataclass(fakefloat=0.1,
                                      fakes=[{
                                          'fakeint': 1
                                      }, {
                                          'fakeint': 2
                                      }, {
                                          'fakeint': 3
                                      }])
Ejemplo n.º 23
0
    def payload_type(self, type_: Type[Any], channel_id: str,
                     **message: Any) -> Any:
        if type_ and dataclasses.is_dataclass(type_):
            return asdataclass(message, type_)

        return message
)


@jsondaora(serialize_fields=('name', 'age'))
class Person:
    name: str
    age: int

    class Music:
        name: str

    musics: List[Music]


jsondict = dict(name='John', age=40, musics=[dict(name='Imagine')])
person = asdataclass(jsondict, Person)

print('dataclass:')
print(person)
print(dataclass_asjson(person))
print()

# TypedDict


@jsondaora(serialize_fields=('age'))
class Person(TypedDict):
    name: str
    age: int

    class Music(TypedDict):