0

我正在尝试使用 FastAPI 设置 pytesthttpx.AsyncClient和 sqlalchemy AsyncSession。除了异步的东西外,所有东西实际上都模仿了FastAPI Fullstack repo中的测试。

CRUD 单元测试没有问题。使用 httpx lib 中的 AsyncClient 运行 API 测试时会出现此问题。

问题是,客户端发出的任何请求都只能访问在初始化(设置)客户端夹具之前创建的用户(在我的情况下)。

我的 pytest conftest.py设置是这样的:

from typing import Dict, Generator, Callable
import asyncio
from fastapi import FastAPI
import pytest
# from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession
from httpx import AsyncClient
import os
import warnings
import sqlalchemy as sa
from alembic.config import Config
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker


async def get_test_session() -> Generator:
    test_engine = create_async_engine(
            settings.SQLALCHEMY_DATABASE_URI + '_test',
            echo=False,
        )
        
    # expire_on_commit=False will prevent attributes from being expired
    # after commit.
    async_sess = sessionmaker(
        test_engine, expire_on_commit=False, class_=AsyncSession
    )
    async with async_sess() as sess, sess.begin():    
        yield sess

@pytest.fixture(scope="session")
async def async_session() -> Generator:
    test_engine = create_async_engine(
            settings.SQLALCHEMY_DATABASE_URI + '_test',
            echo=False,
            pool_size=20, max_overflow=0
        )
        
    # expire_on_commit=False will prevent attributes from being expired
    # after commit.
    async_sess = sessionmaker(
        test_engine, expire_on_commit=False, class_=AsyncSession
    )
    yield async_sess

@pytest.fixture(scope="session")
async def insert_initial_data(async_session:Callable):
    async with async_session() as session, session.begin():
        # insert first superuser - basic CRUD ops to insert data in test db
        await insert_first_superuser(session)
        # insert test.superuser@example.com

        await insert_first_test_user(session)
        # inserts test.user@example.com

@pytest.fixture(scope='session')
def app(insert_initial_data) -> FastAPI:
    return  FastAPI()


@pytest.fixture(scope='session')
async def client(app: FastAPI) -> Generator:
    from app.api.deps import get_session
    
    app.dependency_overrides[get_session] = get_test_session
 
    async with AsyncClient(
                app=app, base_url="http://test", 
                ) as ac:
        yield ac

    # reset dependencies
    app.dependency_overrides = {}

所以在这种情况下,在运行 API 测试期间只有超级用户test.superuser@example.com和普通用户test.user@example.com可用。例如,下面的代码能够很好地获取访问令牌:

async def authentication_token_from_email(
    client: AsyncClient,  session: AsyncSession,
) -> Dict[str, str]:
    """
    Return a valid token for the user with given email.

    
    """
    
    email = 'test.user@example.com'
    password = 'test.user.password'
    
    user = await crud.user.get_by_email(session, email=email)
    assert user is not None
    
    
    data = {"username": email, "password": password}

    response = await client.post(f"{settings.API_V1_STR}/auth/access-token", 
                                 data=data)
    auth_token = response.cookies.get('access_token')
    assert auth_token is not None

    return auth_token

但是,下面的修改代码没有 - 在这里我尝试插入新用户,然后登录以获取访问令牌。

async def authentication_token_from_email(
    client: AsyncClient, session: AsyncSession,
) -> Dict[str, str]:
    """
    Return a valid token for the user with given email.
    If the user doesn't exist it is created first.

    """
    
    email = random_email()
    password = random_lower_string()

    
    user = await crud.user.get_by_email(session, email=email)
    if not user:
        user_in_create = UserCreate(email=email, 
                                    password=password)
        user = await crud.user.create(session, obj_in=user_in_create)

        
    else:
        user_in_update = UserUpdate(password=password)
        user = await crud.user.update(session, db_obj=user, obj_in=user_in_update)

    assert user is not None

    # works fine up to this point, user inserted successfully
    # now try to send http request to fetch token, and user is not found in the db
        
    data = {"username": email, "password": password}
    response = await client.post(f"{settings.API_V1_STR}/auth/access-token", 
                                   data=data)
    auth_token = response.cookies.get('access_token')
    # returns None. 

    return auth_token

这里发生了什么 ?感谢任何帮助!

4

1 回答 1

0

结果我需要做的就是,因为我不明白的原因,是在客户端夹具中定义 FastAPI 依赖项覆盖函数:


async def get_test_session() -> Generator:
    test_engine = create_async_engine(
            settings.SQLALCHEMY_DATABASE_URI + '_test',
            echo=False,
        )
        
    # expire_on_commit=False will prevent attributes from being expired
    # after commit.
    async_sess = sessionmaker(
        test_engine, expire_on_commit=False, class_=AsyncSession
    )
    async with async_sess() as sess, sess.begin():    
        yield sess

@pytest.fixture(scope='session')
async def client(app: FastAPI) -> Generator:
    from app.api.deps import get_session
    
    app.dependency_overrides[get_session] = get_test_session
 
    async with AsyncClient(
                app=app, base_url="http://test", 
                ) as ac:
        yield ac

    # reset dependencies
    app.dependency_overrides = {}


@pytest.fixture(scope="function")
async def session(async_session) -> Generator:
    async with async_session() as sess, sess.begin():
        yield sess
        


@pytest.fixture
async def client(app: FastAPI, session:AsyncSession) -> Generator:
    from app.api.deps import get_session
    
    # this needs to be defined inside this fixture
    # this is generate that yields session retrieved from `session` fixture
    
    def get_sess(): 
        yield session
    
    app.dependency_overrides[get_session] =  get_sess
        
    async with AsyncClient(
             app=app, base_url="http://test", 
             ) as ac:
        yield ac

    app.dependency_overrides = {}

我很感激对这种行为的任何解释。谢谢!

于 2021-12-30T03:06:44.253 回答