I have fixtures
from typing import AsyncGenerator, Generator
@pytest.fixture(scope='session')
def init_session(config: Config) -> None:
init_db(config)
@pytest.fixture(scope="session")
async def session(init_session: None) -> AsyncGenerator[AsyncSession, None]:
async with get_session() as session:
yield session
@pytest.fixture(scope="session")
def user_repository(session: AsyncSession) -> UserRepository:
return UserRepository(session)
And I have test
import datetime
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
import UserStatus
import UserRepository
import RawUser
from tests.test_utils import random_str
from tests.test_utils.user import convert_user_model_to_raw_user, get_user_by_id
TEST_USER_LOGIN = random_str()
TEST_USER_PASSWORD_HASH = random_str()
TEST_USER_STATUS = UserStatus.ACTIVE
TEST_USER_CREATED_AT = datetime.datetime.now(datetime.UTC)
TEST_USER_UPDATED_AT = datetime.datetime.now(datetime.UTC)
@pytest.mark.asyncio
async def test_create_user(user_repository: UserRepository, session: AsyncSession) -> None:
raw_user = RawUser(
login=TEST_USER_LOGIN,
password_hash=TEST_USER_PASSWORD_HASH,
status=TEST_USER_STATUS,
created_at=TEST_USER_CREATED_AT,
updated_at=TEST_USER_UPDATED_AT,
)
user_id = await user_repository.create_user(raw_user)
user_model = await get_user_by_id(session, user_id)
user_from_db = convert_user_model_to_raw_user(user_model)
assert user_from_db == raw_user
Function create_user
from sqlalchemy import insert
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
import UserModel
import RawUser
class UserRepository:
def __init__(self, session: AsyncSession) -> None:
self.session = session
async def create_user(self, raw_user: RawUser) -> int:
try:
result = await self.session.execute(
insert(UserModel)
.values(
login=raw_user.login,
password_hash=raw_user.password_hash,
status=raw_user.status,
created_at=raw_user.created_at,
updated_at=raw_user.updated_at,
)
.returning(UserModel.id)
)
user_id = result.scalar()
if user_id is None:
raise RuntimeError("Failed to retrieve user ID after insertion.")
await self.session.commit()
return user_id
except SQLAlchemyError as e:
await self.session.rollback()
raise RuntimeError(f"Failed to create user: {e}")
For some reason I get AsyncGenerator instead of AsyncSession. I’ve tried everything that comes to mind, but I don’t know how to solve this problem. I would be very grateful for your help.
I tried making fixtures synchronous, but it doesn’t work. The only way I got the test to complete was when I used a loop inside it to pull the session out of the generator, but I was told that this option is not suitable.
AttributeError: ‘async_generator’ object has no attribute ‘execute’
Andi swim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.