如何在 Django 中进行测试

How do test in Django

我正在尝试对 Django 进行第一次测试,但我不知道该怎么做,或者在阅读了文档(其中解释了一个非常简单的测试)之后我仍然不知道该怎么做。

我正在尝试进行一项测试,该测试转到 "login" url 并进行登录,并在成功登录后重定向到授权页面。

from unittest import TestCase

from django.test.client import Client


class Test(TestCase):
    def testLogin(self):
        client = Client()
        headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'}
        data = {}
        response = client.post('/login/', headers=headers, data=data, secure=False)
        assert(response.status_code == 200)

并且测试成功,但我不知道是因为加载“/login/”的 200 还是因为测试执行登录并在重定向后获得 200 代码。

如何检查登录后 url 重定向的测试是否正确?有没有插件之类的可以帮助测试的?或者我在哪里可以找到一个很好的教程来测试我的观点和模型?

感谢和问候。

Django 有很多测试工具。对于此任务,您应该使用 Django 中的测试用例 class,例如 django.test.TestCase。 然后你可以使用方法 assertRedirects() ,它会检查你被重定向到哪里以及使用了哪些代码。您可以找到所需的任何信息 here。 我已尝试为您的任务编写代码:

from django.test import TestCase

class Test(TestCase):
    def test_login(self):
        data = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password'}
        response = client.post('/login/', data=data, content_type='application/json', secure=false)
        assertRedirects(response, '/expected_url/', 200)

然后你可以使用python3 manage.py test来运行所有测试。

要正确测试重定向,请使用 follow 参数

If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.

那么你的代码就这么简单

从django.test导入测试用例

class Test(TestCase):
    def test_login(self):
        client = Client()
        headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'}
        data = {}
        response = client.post('/login/', headers=headers, data=data, secure=False)
        self.assertRedirects(response,'/destination/',302,200)

请注意,它是 self.assertRedirects 而不是 assertassertRedirects

另请注意,上述测试很可能会失败,因为您将空字典作为表单数据发布。当表单无效时,Django 表单视图不会重定向,空表单可能在这里无效。