Django how to set user request in client test
I am testing a view and my test looks like this:
def test_profile(self, user_id):
user = User.objects.create_user(username="myusername", password="password", email="abc@testmail.com")
self.client.user = user
print(user.id)
request = self.client.get("/account/profile/{}/".format(user_id), follow=True)
self.assertEqual(request.status_code, 200)
Here my profile has a login_required
decorator. So how can I ask the user request.user
+4
source to share
2 answers
I tried to do the same too, but found out that Django Test Client does not set user in request and it is not possible to set request.user when using Client in any other way. I used RequestFactory for this.
def setUp(self):
self.request_factory = RequestFactory()
self.user = User.objects.create_user(
username='javed', email='javed@javed.com', password='my_secret')
def test_my_test_method(self):
request = self.request_factory.post(reverse('home'), {'question_title_name':'my first question title', 'question_name':'my first question', 'question_tag_name':'first, question'})
request.user = self.user
response = home_page(request)
more details about the factory request here
+9
source to share
Try it:
from django.test import TestCase, Client
from django.contrib.auth.models import User
class YourTestCase(TestCase):
def test_profile(self, user_id):
user = User.objects.create(username='testuser')
user.set_password('12345')
user.save()
client = Client()
client.login(username='testuser', password='12345')
response = client.get("/account/profile/{}/".format(user.id), follow=True)
self.assertEqual(response.status_code, 200)
Here I first create a user and set the login credentials for it. Then I create a client and log in with that user. So in your views.py, when you do request.user, you get that user.
+5
source to share