django 测试 - 如何获取响应数据以备将来使用

who*_*rth 6 django unit-testing django-rest-framework

我正在运行这样的登录测试:

def test_login_user(self):
    client = APIClient()
    url = reverse('rest_login')
    data = {
        'username': 'test',
        'password': 'Welcome2'
    }
    response = self.client.post(url, data)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    client.logout()
Run Code Online (Sandbox Code Playgroud)

如果我正常登录应用程序,我会看到一个 json 返回,如下所示:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImV2YW4iLCJleHAiOjE1MTQ2NzYzNTYsImVtYWlsIjoiZXZhbkAyOGJlYXR0eS5jb20iLCJvcmlnX2lhdCI6MTUxNDY3Mjc1Nn0.8CfhfgtMLkNjEaWBfNXbUWXQMZG4_LIru_y4pdLlmeI",
    "user": {
        "pk": 2,
        "username": "test",
        "email": "test@test.com",
        "first_name": "",
        "last_name": ""
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够获取该token值以备将来使用,但是response似乎没有data获取值。

who*_*rth 6

我正在寻找的是response.content根据官方文档

https://docs.djangoproject.com/en/2.0/topics/testing/tools/#testing-responses


C.K*_*.K. 1

显示错误响应:

response.context["form"].errors
Run Code Online (Sandbox Code Playgroud)