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

在DRF中从APIClient获取已登录用户的更优方法

问题描述

我在pytest中使用一个返回已登录APIClient的夹具,代码如下:

@pytest.fixture 
def create_client(create_user) -> APIClient:
    data = {
        "email": create_user.email,
        "password": "TestPassword",
    }
    client = APIClient()
    client.post(path="/user/login/", data=data)
    return client

我希望在测试用例中获取该已登录用户,目前想到的方法是发送GET请求后从响应中获取,代码如下:

def test_get_user(create_client):
    response = create_client.get(path="/some/random/path/")
    user = response.user
    return user

请问是否有更优的实现方式?


更优实现方案

有几种直接且高效的方式,无需额外发送无用请求来获取已登录用户:

1. 让夹具返回客户端与用户的元组

修改原夹具,同时返回已登录客户端和对应的用户对象,测试用例可直接解构使用:

@pytest.fixture 
def logged_in_client(create_user) -> tuple[APIClient, User]:
    data = {
        "email": create_user.email,
        "password": "TestPassword",
    }
    client = APIClient()
    client.post(path="/user/login/", data=data)
    return client, create_user

测试用例使用示例:

def test_get_user(logged_in_client):
    client, user = logged_in_client
    # 直接使用user对象,无需额外请求
    assert user.email == "test@example.com"

2. 给APIClient实例附加用户属性

如果不想改变夹具的返回类型,可在夹具中直接把用户对象挂载到客户端实例上:

@pytest.fixture 
def create_client(create_user) -> APIClient:
    data = {
        "email": create_user.email,
        "password": "TestPassword",
    }
    client = APIClient()
    client.post(path="/user/login/", data=data)
    # 将已登录用户附加到客户端实例
    client.user = create_user
    return client

测试用例使用示例:

def test_get_user(create_client):
    user = create_client.user
    # 直接使用user对象
    assert user.is_authenticated

3. 从登录响应提取用户信息

如果你的登录接口会返回用户数据,可直接从登录响应中解析并附加到客户端,这种方式适合需要验证接口返回用户正确性的场景:

@pytest.fixture 
def create_client(create_user) -> APIClient:
    data = {
        "email": create_user.email,
        "password": "TestPassword",
    }
    client = APIClient()
    login_response = client.post(path="/user/login/", data=data)
    # 假设登录响应返回用户JSON数据,解析后附加到客户端
    client.user = User(**login_response.json())
    return client

测试用例中同样直接通过create_client.user获取用户对象即可。

以上方法都避免了额外的无效请求,更高效且符合测试用例的设计逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:31:03