#20609 closed Cleanup/optimization (fixed)
Document how to use request.user with RequestFactory
Reported by: | Owned by: | Susan Tan | |
---|---|---|---|
Component: | Documentation | Version: | 1.5 |
Severity: | Normal | Keywords: | |
Cc: | timograham@… | Triage Stage: | Accepted |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | yes |
Easy pickings: | yes | UI/UX: | no |
Description
I had a lot of problems finding out why I cannot use request.user in my tests while using RequestFactory.
this line in the documentation (https://docs.djangoproject.com/en/1.4/topics/testing/#the-request-factory) seems to say it:
It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.
But it would be nice to have an example with a user added, like:
class TestCaseWithUser(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')
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"})
# add a user so in the view to test request.user works
request.user = self.user_foo
nt.assert_equal(request.user,self.user_foo)
Change History (10)
comment:1 by , 12 years ago
Cc: | added |
---|---|
Easy pickings: | set |
Summary: | Documentation extension → Document how to use request.user with RequestFactory |
Triage Stage: | Unreviewed → Accepted |
Type: | Uncategorized → Cleanup/optimization |
comment:2 by , 11 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:3 by , 11 years ago
comment:4 by , 11 years ago
Resolution: | → fixed |
---|---|
Status: | assigned → closed |
comment:7 by , 10 years ago
Patch needs improvement: | set |
---|
This is not sufficient. This still breaks when you need to test requests where there is no authenticated user.
comment:8 by , 10 years ago
Resolution: | fixed |
---|---|
Status: | closed → new |
comment:9 by , 10 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
See https://github.com/django/django/pull/1319/files for PR. I edited the given doc patch. Please code review. Thanks.