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

feat(sqla_factory): refresh object in async_session after commit to db #541

Merged
merged 6 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
6 changes: 5 additions & 1 deletion polyfactory/factories/sqlalchemy_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,14 @@ def __init__(self, session: AsyncSession) -> None:
async def save(self, data: T) -> T:
self.session.add(data)
await self.session.commit()
await self.session.refresh(data)
return data

async def save_many(self, data: list[T]) -> list[T]:
self.session.add_all(data)
await self.session.commit()
for batch_item in data:
await self.session.refresh(batch_item)
return data


Expand Down Expand Up @@ -97,7 +100,8 @@ def get_sqlalchemy_types(cls) -> dict[Any, Callable[[], Any]]:
postgresql.TSTZRANGE: lambda: (cls.__faker__.past_datetime(), datetime.now()), # noqa: DTZ005
postgresql.HSTORE: lambda: cls.__faker__.pydict(),
# `types.JSON` is compatible for sqlachemy extend dialects. Such as `pg.JSON` and `JSONB`
types.JSON: lambda: cls.__faker__.pydict(),
# accept `str,int,float` as basic types in case `sqlalchemy/sql/sqltypes.json.json_serializer` raise error
types.JSON: lambda: cls.__faker__.pydict(value_types=[int, str, float]),
wangxin688 marked this conversation as resolved.
Show resolved Hide resolved
}

@classmethod
Expand Down
10 changes: 9 additions & 1 deletion tests/sqlalchemy_factory/test_sqlalchemy_factory_common.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Any, Callable, Type, Union
from uuid import UUID

import pytest
from sqlalchemy import Column, ForeignKey, Integer, String, create_engine, inspect, orm, types
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, create_engine, func, inspect, orm, types
from sqlalchemy.engine import Engine
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine
from sqlalchemy.ext.hybrid import hybrid_property
Expand Down Expand Up @@ -318,6 +319,7 @@ class AsyncModel(Base):
__tablename__ = "table"

id: Any = Column(Integer(), primary_key=True)
test_datetime: Any = Column(DateTime(timezone=True), server_default=func.now())

await create_tables(async_engine, Base)

Expand All @@ -328,12 +330,18 @@ class Factory(SQLAlchemyFactory[AsyncModel]):
__model__ = AsyncModel
wangxin688 marked this conversation as resolved.
Show resolved Hide resolved

result = await Factory.create_async()
assert result.test_datetime is not None
assert isinstance(result.test_datetime, datetime)
assert inspect(result).persistent # type: ignore[union-attr]
await session.delete(result)
await session.commit()

batch_result = await Factory.create_batch_async(size=2)
assert len(batch_result) == 2
for batch_item in batch_result:
assert inspect(batch_item).persistent # type: ignore[union-attr]
assert batch_item.test_datetime is not None
assert isinstance(result.test_datetime, datetime)


def test_alias() -> None:
Expand Down
Loading