You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastApi+Pytest认证用户Fixture失效,测试返回401未授权错误

FastAPI测试中认证客户端返回401未授权问题

我正在为FastAPI应用编写一个作为pytest fixture的认证客户端,代码实现了认证用户的创建、验证和登录流程,理论上该用户应拥有创建、更新和删除帖子的权限,但测试中始终返回401未授权错误(未登录时的错误)。

认证客户端Fixture代码

@pytest.fixture()
def authenticated_user(client):
    user_data = {
        'email': 'julioooo@gmail.com',
        'password': '123',

    }
    res = client.post('/users/create', json={
        **user_data,
        'name': 'julin',
        'job': 'farmer',
    })

    user_id = res.json() # 返回用户ID,用于调用接口确认用户创建
    user_id = user_id['id']

    verify_user = client.post(f'/users/confirm-user/{user_id}').json()
    print(verify_user) # 打印确认信息(调试用)

    log_user_res = client.post('/auth/login', json={
        **user_data
    }) # 响应头包含httponly cookie,通过response.set_cookie()设置

    client.headers={**log_user_res.headers}
    return client

登录校验函数(原生产环境版本)

调试后确认headers中确实包含httponly cookie,推测问题出在用户登录校验部分:

def get_current_user(
    request: Request,
    db=Depends(connect)
):

    user_id = request.cookies.get('Authorization')
    user = User.objects(id=user_id).first()
    if not user:
        credentials_exception = HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Could not validate credentials or Not Logged or User Does Not Exist",
            headers={"WWW-Authenticate": "Bearer"},
        )
        raise credentials_exception
    return user

测试用登录校验函数

随后发现connect依赖返回的是生产数据库连接而非测试库,于是创建了测试版本的校验函数:

def test_get_current_user(request: Request, db=Depends(test_connect)):
    load_dotenv()
    test_connection_url = os.getenv('test_connection_url')
    user_id = request.cookies.get('Authorization')
    client = MongoClient(test_connection_url)
    users = client['TestJC']['users']
    user = users.find_one({"_id": user_id})
    if not user:
        credentials_exception = HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Could not validate credentials or Not Logged or User Does Not Exist",
            headers={"WWW-Authenticate": "Bearer"},
        )
        raise credentials_exception
    return user

注:原函数使用mongoengine,新函数改用pymongo是为了解决测试后删除测试库的问题——Users.objects().delete()无效,而users.drop()可以有效删除测试库,避免误删生产库。

尝试过的解决方案

  • 尝试覆盖get_current_user依赖为测试版本
  • 创建仅返回client.headers的Fixture并在请求中传入

但所有尝试均无效,测试始终返回401错误,恳请帮忙解决。

内容的提问来源于stack exchange,提问作者Julio Raposo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:45:34