django测试RequestFactory不包含request.user

问题描述 投票:5回答:1

每当我在测试期间使用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', '[email protected]', '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个回答
7
投票

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

但是,提供一个更好的例子会很好。

this

它在第三个列表项中:

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

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

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

特别是同样的方式

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.