python - Django 测试 : RequestFactory() follow redirect

标签 python django django-testing

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

用于测试的标准 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 客户端,您可以使用 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

关于python - Django 测试 : RequestFactory() follow redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47391719/

相关文章:

带有 django-nose : two identical settings files with different behavior in running test command 的 Django

python - Django rest framework,设置api响应Content-Encoding为gzip

DjangoCMS,在 CMS 模板之外使用片段

python - 将 upload_to 函数与模型类关联的首选 pythonic 方式?

mysql - 全文搜索 django : Mysql not so bad ?(对比 sphinx、xapian)

python - 解决 SQLite 缺乏命名参数支持的问题

python - 使用 python 队列进行 Django Rest Framework 测试

python - Pandas 识别组中第一行的列值

python - 使用 Tensorflow 的多元线性回归模型

python - MongoEngine fieldDoesNotExist错误,但实际上是