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

时间:2017-12-31 22:29:01

标签: 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()

如果我正常登录应用程序,我会看到这样的json返回:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImV2YW4iLCJleHAiOjE1MTQ2NzYzNTYsImVtYWlsIjoiZXZhbkAyOGJlYXR0eS5jb20iLCJvcmlnX2lhdCI6MTUxNDY3Mjc1Nn0.8CfhfgtMLkNjEaWBfNXbUWXQMZG4_LIru_y4pdLlmeI",
    "user": {
        "pk": 2,
        "username": "test",
        "email": "test@test.com",
        "first_name": "",
        "last_name": ""
    }
}

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

1 个答案:

答案 0 :(得分:1)

根据官方文档

,我正在寻找的是response.content

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