Django测试RequestFactory不包括request.user

5
每当我在测试中使用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,所以也要在我想要的(单元)测试中使用...

感谢这个问题和答案,我发现需要手动将用户添加到请求中:如何在测试时访问request.user?,我将其作为解决方法添加了进去。

我的问题是:

  • 为什么会这样?
  • 感觉这是请求工厂中的一个错误,是吗?(所以这是一个解决方法,还是只是一个未记录的功能)
  • 还是我做错了其他事情?(测试客户端和工厂的组合)
  • 有更好的方法来测试已登录用户的请求吗?

我也尝试过这个:同样的问题

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

顺便提一下,这个答案:访问Django测试中的request.user对象建议使用。
response.context['user'] 

代替
request.user

但在我的代码中情况并非如此,据我所知,使用request.user是很正常的。为了解释我的问题,我将request.user放入了测试中...但在我的实际应用中,它并不在测试中...它在我想要测试的代码中。

1个回答

9

抱歉...这似乎是一个已记录的功能...

然而,给出一个更好的例子会更好。

请参见this

在第三个列表项中可以找到它:

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

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

RequestFactory与测试客户端共享相同的API。但是,它不像浏览器那样运行,而是提供了一种生成请求实例的方式,该请求实例可以用作任何视图的第一个参数。这意味着您可以像测试其他函数一样测试视图函数

特别是the same way

不确定是否应该删除此问题...解决此问题花费了我很多时间...理解我的解决方法也是如此...

因此,我认为其他人也可以使用这个方法..

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


1
从1.5版本开始,这已经得到了适当的记录:https://docs.djangoproject.com/en/1.5/topics/testing/advanced/#module-django.test.client - Marcin
1
由于v1.5的另一个链接已经失效,因此添加了更新的链接。https://docs.djangoproject.com/en/1.8/topics/testing/advanced/#module-django.test.client。 - cjukjones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接