Skip to content

Commit

Permalink
pydatic request serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
nekufa committed Sep 23, 2023
1 parent 069e731 commit 422d874
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
6 changes: 5 additions & 1 deletion sharded_queue/drivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ def serialize(self, request: T) -> str:
return dumps(self.get_values(request))

def deserialize(self, cls: type[T], source: str) -> T:
return cls(*loads(source))
values = loads(source)
if hasattr(cls, 'model_fields'):
return cls(**dict(zip(cls.model_fields, values)))

return cls(*values)


class RuntimeLock(Lock):
Expand Down
30 changes: 16 additions & 14 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,38 @@
from dataclasses import dataclass
from typing import Any, NamedTuple

from pytest import mark
from pydantic import BaseModel

from sharded_queue.drivers import JsonTupleSerializer
from sharded_queue.protocols import Serializer


class ExampleNamedTuple(NamedTuple):
class NamedTupleRequest(NamedTuple):
name: str


@dataclass
class ExampleRequest:
class DataclassRequest:
name: str


@mark.asyncio
async def test_named_tuple() -> None:
serializer: Serializer = JsonTupleSerializer()
request = ExampleRequest('nekufa')
await runner(serializer, request)
class PydanticRequest(BaseModel):
name: str


def test_dataclass() -> None:
runner(JsonTupleSerializer(), DataclassRequest('nekufa'))


def test_named_tuple() -> None:
runner(JsonTupleSerializer(), NamedTupleRequest('nekufa'))


@mark.asyncio
async def test_dataclass() -> None:
serializer: Serializer = JsonTupleSerializer()
request = ExampleNamedTuple('nekufa')
await runner(serializer, request)
def test_pydantic() -> None:
runner(JsonTupleSerializer(), PydanticRequest(name='nekufa'))


async def runner(serializer: Serializer, request: Any):
def runner(serializer: Serializer, request: Any):
serialized = serializer.serialize(request)
parsed = serializer.deserialize(type(request), serialized)
assert isinstance(parsed, type(request))
Expand Down

0 comments on commit 422d874

Please sign in to comment.