pytest fixture 制作一个我有参数的 AIPClient

pytest fixture to make an AIPClient that I have parameters for

我正在尝试制作一个 returns 一个 APIClient 对象,该对象经过用户身份验证,如果需要,我可以将参数传递给该用户。我有一个名为 CustomerFactory 的 DjangoModelFactory 对象,它可以创建一个客户和一个用户,其用户是使用 UserFactory 工厂创建的。我希望能够访问创建的客户中的数据,但也有一个固定装置来发出经过身份验证的 API 请求。这个api_customer_client是我想出来的,不行。

@pytest.fixture
def api_client():
    return APIClient()


@pytest.fixture
def api_customer_client(app_customer, api_client):
    def _api_customer_client(test_customer=app_customer):
        refresh = RefreshToken.for_user(test_customer)
        api_client.credentials(HTTP_AUTHORIZATION=f"JWT {refresh.access_token}")
        return api_client

    return _api_customer_client

我用这个测试调用夹具:

def test_client_cant_view_users_without_token(self, api_customer_client, app_customer):
    client = api_customer_client(test_customer=app_customer.user)
    result = client(reverse("api:user-list"), format="json")
    assert result.status_code == 401

我一直收到错误 TypeError: 'APIClient' object is not callable,我不知道为什么。我最初认为它可能无法通过 api_customer_client 夹具并返回不同的夹具,但我尝试直接在 api_customer_client 夹具中使用 APIClient,但事实并非如此要么工作。

我有另一个几乎相同的装置,除了子方法之外,它工作得很好:

@pytest.fixture
def api_user_client(user: User, api_client):
    refresh = RefreshToken.for_user(user)
    api_client.credentials(HTTP_AUTHORIZATION=f"JWT {refresh.access_token}")
    return api_client

我希望我没有解释太久,但这可能吗?

我犯了一个愚蠢的错误。我将夹具视为问题而不是测试。

我完全重写了我的测试,但我认为问题在于:

result = client(reverse("api:user-list"), format="json")

应该说:

result = client.post(reverse("api:user-list"), format="json")

我相信这段代码仍然有效,即使我最终使用的代码有些不同。