Coverage for tests/test_asyncio.py: 100%

43 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-16 00:02 +0000

1import asyncio 1nopqrstuvwxyz

2from collections.abc import Mapping 1nopqrstuvwxyz

3from typing import Any, assert_type 1nopqrstuvwxyz

4 

5import pytest 1nopqrstuvwxyz

6from sqlalchemy import update 1nopqrstuvwxyz

7from sqlalchemy.engine import CursorResult, ScalarResult 1nopqrstuvwxyz

8from sqlalchemy.ext.asyncio import create_async_engine 1nopqrstuvwxyz

9from sqlmodel import Field, SQLModel, col, select 1nopqrstuvwxyz

10from sqlmodel.ext.asyncio.session import AsyncSession 1nopqrstuvwxyz

11 

12 

13@pytest.mark.parametrize("execution_options", [{}, {"populate_existing": True}]) 1nopqrstuvwxyz

14def test_async_session(execution_options: Mapping[str, Any]) -> None: 1nopqrstuvwxyz

15 class Hero(SQLModel, table=True): 1abcdefghijklm

16 id: int | None = Field(default=None, primary_key=True) 1abcdefghijklm

17 name: str 1abcdefghijklm

18 

19 async def run() -> None: 1abcdefghijklm

20 engine = create_async_engine("sqlite+aiosqlite://") 1abcdefghijklm

21 try: 1abcdefghijklm

22 async with engine.begin() as connection: 1abcdefghijklm

23 await connection.run_sync(SQLModel.metadata.create_all) 1abcdefghijklm

24 async with AsyncSession(engine) as session: 1abcdefghijklm

25 session.add(Hero(name="Deadpond")) 1abcdefghijklm

26 await session.commit() 1abcdefghijklm

27 

28 statement = select(Hero) 1abcdefghijklm

29 result = await session.exec( 1abcdefghijklm

30 statement, execution_options=execution_options 

31 ) 

32 assert_type(result, ScalarResult[Hero]) 1abcdefghijklm

33 assert result.one().name == "Deadpond" 1abcdefghijklm

34 

35 with pytest.warns(DeprecationWarning, match="session.exec"): 1abcdefghijklm

36 scalars = await session.scalars(statement) 1abcdefghijklm

37 assert_type(scalars, ScalarResult[Hero]) 1abcdefghijklm

38 assert scalars.one().name == "Deadpond" 1abcdefghijklm

39 

40 row = (await session.exec(select(col(Hero.id), Hero.name))).one() 1abcdefghijklm

41 assert_type(row, tuple[int | None, str]) 1abcdefghijklm

42 assert row == (1, "Deadpond") 1abcdefghijklm

43 

44 updated = await session.exec(update(Hero).values(name="Rusty-Man")) 1abcdefghijklm

45 assert_type(updated, CursorResult[*tuple[Any, ...]]) 1abcdefghijklm

46 assert updated.rowcount == 1 1abcdefghijklm

47 await session.commit() 1abcdefghijklm

48 assert (await session.exec(select(Hero.name))).one() == "Rusty-Man" 1abcdefghijklm

49 

50 with pytest.warns(DeprecationWarning, match="session.exec"): 1abcdefghijklm

51 result = await session.execute(select(Hero)) # ty: ignore[deprecated] 1abcdefghijklm

52 assert result.scalars().one().name == "Rusty-Man" 1abcdefghijklm

53 finally: 

54 await engine.dispose() 1abcdefghijklm

55 

56 asyncio.run(run()) 1abcdefghijklm