django测试RequestFactory不包含request.user

时间:2013-06-15 12:40:43

标签: django unit-testing testing request testcase

每次我在测试期间使用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放在测试...在我的现实生活中,它不在测试中......它在我想要测试的代码中。

1 个答案:

答案 0 :(得分:7)

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

然而,提供一个更好的例子会很不错。

请参阅this

它位于第三个列表项中:

  

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

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

  

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

特别以同样的方式

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

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

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