Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix regression on model dump #212

Merged
merged 2 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions esmerald/responses/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import dataclasses
from dataclasses import is_dataclass
from json import dumps
from typing import TYPE_CHECKING, Any, Dict, Generic, NoReturn, Optional, TypeVar, Union, cast

import msgspec
from orjson import OPT_OMIT_MICROSECONDS, OPT_SERIALIZE_NUMPY, dumps
from pydantic import BaseModel
from starlette import status
from starlette.responses import FileResponse as FileResponse # noqa
Expand Down Expand Up @@ -164,7 +164,11 @@ def render(self, content: Any) -> bytes:
):
return b""
if self.media_type == MediaType.JSON:
return dumps(content, default=self.transform, ensure_ascii=False).encode("utf-8")
return dumps(
content,
default=self.transform,
option=OPT_SERIALIZE_NUMPY | OPT_OMIT_MICROSECONDS,
)
return super().render(content)
except (AttributeError, ValueError, TypeError) as e: # pragma: no cover
raise ImproperlyConfigured("Unable to serialize response content") from e
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ dependencies = [
"itsdangerous>=2.1.2,<3.0.0",
"jinja2>=3.1.2,<4.0.0",
"loguru>=0.7.0,<0.8.0",
"pydantic>=2.5.0,<3.0.0",
"pydantic>=2.5.1,<3.0.0",
"pydantic-settings>=2.0.0,<3.0.0",
"python-multipart>=0.0.5,<0.0.7",
"openapi-schemas-pydantic>=3.0.0",
Expand Down Expand Up @@ -115,7 +115,7 @@ test = [
"python-jose>=3.3.0,<4",
"saffier[postgres]>=0.18.0",
"edgy[postgres]>=0.4.0",
"mongoz>=0.3.1",
"mongoz>=0.3.3",
"requests>=2.28.2,<3.0.0",
"ruff>=0.0.256,<1.0.0",
"ujson>=5.7.0,<6",
Expand Down
83 changes: 83 additions & 0 deletions tests/databases/edgy/test_serialization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import random
import string
from typing import AsyncGenerator
from uuid import uuid4

import edgy
import pytest
from httpx import AsyncClient

from esmerald import Esmerald, Gateway, post
from esmerald.conf import settings

database, models = settings.edgy_registry
pytestmark = pytest.mark.anyio


def get_random_string(length=10):
letters = string.ascii_lowercase
result_str = "".join(random.choice(letters) for i in range(length))
return result_str


class TestUser(edgy.Model):
"""
Inherits from the abstract user and adds the registry
from esmerald settings.
"""

name = edgy.CharField(max_length=255, null=False)
user_id = edgy.UUIDField(default=uuid4)
created_at = edgy.DateTimeField(auto_now=True)
updated_at = edgy.DateTimeField(auto_now_add=True)

class Meta:
registry = models


@pytest.fixture(autouse=True, scope="module")
async def create_test_database():
try:
await models.create_all()
yield
await models.drop_all()
except Exception:
pytest.skip("No database available")


@pytest.fixture(autouse=True)
async def rollback_transactions():
with database.force_rollback():
async with database:
yield


@pytest.fixture()
def app() -> Esmerald:
app = Esmerald(routes=[Gateway(handler=user)])
return app


@pytest.fixture()
async def async_client(app) -> AsyncGenerator:
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac


@post("/create")
async def user() -> TestUser:
user = await TestUser.query.create(name="Esmerald")
return user


async def test_can_create_user_serialized(test_client_factory, async_client):
response = await async_client.post("/create")

assert response.status_code == 201

data = response.json()

assert data["name"] == "Esmerald"
assert data["created_at"] is not None
assert data["updated_at"] is not None
assert data["user_id"] is not None