每当我在测试期间使用 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 放在测试中......在我的现实生活中,它不在测试中...它在我要测试的代码中。
最佳答案
抱歉...它似乎是一个文档化的功能...
但是,如果能举个更好的例子就好了。
参见 this .
它在第三个列表项中:
It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.
然而...这似乎与第一句话自相矛盾:
The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view. This means you can test a view function the same way as you would test any other function
特别是以同样的方式
不确定我是否应该删除这个问题......解决这个问题花了我很多时间......而不是理解我的解决方法......
所以我想有人也可以使用它..
我刚刚添加了一个文档扩展请求:https://code.djangoproject.com/ticket/20609
关于django 测试 RequestFactory 不包含 request.user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17123733/