|
| 1 | +import asyncio |
| 2 | +from typing import Generator, Optional |
| 3 | + |
| 4 | +import pytest |
| 5 | +from sqlmodel import Field, SQLModel, select |
| 6 | +from sqlmodel.ext.asyncio import AsyncSession, create_async_engine |
| 7 | +from testcontainers.postgres import PostgresContainer |
| 8 | + |
| 9 | + |
| 10 | +# The first time this test is run, it will download the postgres image which can take |
| 11 | +# a while. Subsequent runs will be much faster. |
| 12 | +@pytest.fixture(scope="module") |
| 13 | +def postgres_container_url() -> Generator[str, None, None]: |
| 14 | + with PostgresContainer("postgres:13") as postgres: |
| 15 | + postgres.driver = "asyncpg" |
| 16 | + yield postgres.get_connection_url() |
| 17 | + |
| 18 | + |
| 19 | +async def _test_async_create(postgres_container_url: str) -> None: |
| 20 | + class Hero(SQLModel, table=True): |
| 21 | + # SQLModel.metadata is a singleton and the Hero Class has already been defined. |
| 22 | + # If I flush the metadata during this test, it will cause test_enum to fail |
| 23 | + # because in that file, the model isn't defined within a function. For now, the |
| 24 | + # workaround is to set extend_existing to True. In the future, test setup and |
| 25 | + # teardown should be refactored to avoid this issue. |
| 26 | + __table_args__ = {"extend_existing": True} |
| 27 | + |
| 28 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 29 | + name: str |
| 30 | + secret_name: str |
| 31 | + age: Optional[int] = None |
| 32 | + |
| 33 | + hero_create = Hero(name="Deadpond", secret_name="Dive Wilson") |
| 34 | + |
| 35 | + engine = create_async_engine(postgres_container_url) |
| 36 | + async with engine.begin() as conn: |
| 37 | + await conn.run_sync(SQLModel.metadata.create_all) |
| 38 | + |
| 39 | + async with AsyncSession(engine) as session: |
| 40 | + session.add(hero_create) |
| 41 | + await session.commit() |
| 42 | + await session.refresh(hero_create) |
| 43 | + |
| 44 | + async with AsyncSession(engine) as session: |
| 45 | + statement = select(Hero).where(Hero.name == "Deadpond") |
| 46 | + results = await session.exec(statement) |
| 47 | + hero_query = results.one() |
| 48 | + assert hero_create == hero_query |
| 49 | + |
| 50 | + |
| 51 | +def test_async_create(postgres_container_url: str) -> None: |
| 52 | + asyncio.run(_test_async_create(postgres_container_url)) |
0 commit comments