Django 测试:RequestFactory() 跟随重定向

Django testing: RequestFactory() follow redirect

在 Django 中,我有一个视图,它将重定向到某些用户的注册页面,我想为此编写一个测试。

用于测试的标准 request.client.get 不允许我指定用户(它只是默认为 anonymous_user?),所以我无法测试该行为。

使用 RequestFactory() 我可以指定 request.user。但是,它没有遵循重定向,因此测试失败。

from .views import my_view
from django.test import RequestFactory()

def test_mytest(self):
    user = create_guest_user()
    self.factory = RequestFactory()
    request = self.factory.get(reverse('my_view'), follow=True)
    request.user = user
    response = my_view(request)
    self.assertContains(response, "page where redirected should contain this")

它在最后一行失败并显示此错误消息:

AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)

知道怎么做吗?

编辑:据我所知,这不是重复的,因为它指的是 RequestFactory(),它不同于 self.client.get(其中 follow=True 将解决问题)。

要验证默认的 Django client,您可以在 client:

上使用 force_login 方法
user = create_guest_user()
self.client.force_login(user)

If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important.

要使用测试 client 遵循重定向(或不遵循),您必须使用 follow 参数,如下所述:https://docs.djangoproject.com/en/1.11/topics/testing/tools/#django.test.Client.get

self.client.get(url, follow=True)

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.

因此您的完整代码应如下所示:

from django.test import TestCase

class MyTestCase(TestCase):
    def test_mytest(self):
        user = create_guest_user()
        self.client.force_login(user)
        response = self.client.get(reverse('my_view'), follow=True)
        # Do your assertions on the response here