Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Fixed #20609.Documented how to use request.user with RequestFactory. #1319

Closed
wants to merge 2 commits into from

3 participants

@onceuponatimeforever

Fixed https://code.djangoproject.com/ticket/20609. Thanks michel for the doc patch. I edited and expanded on given doc patch. Please code review. Thanks.

@mjtamlyn
Collaborator

This documentation makes no sense. You set request.user to be self.sample_user, and then assert it on the next line... The client login has absolutely no relation to the request factory instance.

Also if we were to use django.test.TestCase then there is no need to instantiate a self.client, or remove the user from the database otherwise.

I agree a small example to show how you can fix this would be helpful, but I think the following lines are sufficient:

request_factory = RequestFactory()
my_user = User.objects.create_user(...)
request = request_factory.get(...)
request.user = my_user
@timgraham
Owner

Thanks, I just modified the existing example with the suggestions. merged in 067e042.

@timgraham timgraham closed this
@onceuponatimeforever onceuponatimeforever deleted the onceuponatimeforever:20609 branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 18 additions and 1 deletion.
  1. +18 −1 docs/topics/testing/advanced.txt
View
19 docs/topics/testing/advanced.txt
@@ -49,10 +49,27 @@ The following is a simple unit test using the request factory::
# Create an instance of a GET request.
request = self.factory.get('/customer/details')
- # Test my_view() as if it were deployed at /customer/details
+ # Test my_view() as if it were deployed at /customer/details.
response = my_view(request)
self.assertEqual(response.status_code, 200)
+
+Example
+-------
+Suppose you have a logged in user. The following shows how to use request.user::
+
+ # Every test needs access to the request factory.
+ request_factory = RequestFactory()
+
+ # Create a new user account with login values.
+ my_user = User.objects.create_user(first_name='jacob', email='jacob@…',password='top_secret')
+
+ # Create an instance of a GET request.
+ request = request_factory.get('/my/ur')
+
+ # User in request instance gets assigned to newly created sample user.
+ request.user = my_user
+
.. _topics-testing-advanced-multidb:
Tests and multiple databases
Something went wrong with that request. Please try again.