【问题标题】:django test RequestFactory does not include request.userdjango test RequestFactory 不包括 request.user
【发布时间】:2013-06-12 00:04:06
【问题描述】:

每当我在测试期间使用 requestFactory 时,例如:

from django.contrib.auth.models import User
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.client import Client
import nose.tools as nt

class TestSomeTestCaseWithUser(TestCase):

    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.client = Client()
        self.user_foo = User.objects.create_user('foo', 'foo@bar.com', 'bar')

    def tearDown(self):
        # Delete those objects that are saved in setup
        self.user_foo.delete()

    def test_request_user(self):
        self.client.login( username='foo', password='bar')
        request = self.factory.post('/my/url/', {"somedata": "data"})
        nt.assert_equal(request.user,self.user_foo)

关于我尝试使用 request.user 的所有内容:

AttributeError: 'dict' object has no attribute 'user'

这行不通,所以我添加了一个解决方法:

def test_request_user(self):
    # Create an instance of a GET request.
    self.client.login( username='foo', password='bar')
    request = self.factory.post('/my/url/', {"somedata": "data"})
    # a little workaround, because factory does not add the logged in user
    request.user = self.user_foo
    nt.assert_equal(request.user,self.user_foo)

我在我的代码中经常使用 request.user ......所以在我想要(单元)测试的东西中也是如此......

感谢这个问题和答案,我发现您需要手动将用户添加到请求中:How to access request.user while testing?,我将其添加为一种解决方法。

我的问题是:

  • 这是为什么呢?
  • 感觉像是请求工厂中的错误,是吗? (这是一种解决方法,还是只是一个未记录的功能)
  • 还是我做错了什么? (测试客户端和工厂的组合)
  • 有没有更好的方法来测试请求中的登录用户?

我也试过了:同样的问题

    response = self.client.post("/my/url/")
    request = response.request

顺便说一句,这个答案:Accessing the request.user object when testing Django 建议使用

response.context['user'] 

代替

request.user

但在我的代码中并非如此,据我所知 request.user 已退出正常使用,为了解释我的问题,我将 request.user 置于测试中......在我的现实生活中,它不在测试中……它在我要测试的代码中。

【问题讨论】:

    标签: django unit-testing testing request testcase


    【解决方案1】:

    对不起...这似乎是一个记录在案的功能...

    不过,如果能举个更好的例子就好了。

    this

    它在第三个列表项中:

    它不支持中间件。会话和身份验证属性 如果视图需要,必须由测试本身提供 功能正常。

    然而……这似乎与第一句话矛盾:

    RequestFactory 与测试客户端共享相同的 API。然而, RequestFactory 提供了一种方法,而不是像浏览器一样 生成可用作第一个参数的请求实例 到任何视图。这意味着您可以像测试视图函数一样 你会测试任何其他功能

    尤其是同样的方式

    不确定我是否应该删除这个问题......解决这个问题花了我很多时间......而不是理解我的解决方法......

    所以我想有人也可以使用它..

    我刚刚添加了一个文档扩展请求:https://code.djangoproject.com/ticket/20609

    【讨论】:

    猜你喜欢
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2011-07-26
    • 2011-04-01
    • 1970-01-01
    • 2020-11-14
    • 2019-08-24
    相关资源
    最近更新 更多