Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django how to set request user in client test

I am testing a view and my test looks like:

def test_profile(self, user_id):
    user = User.objects.create_user(username="myusername", password="password", email="[email protected]")
    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 view has a login_required decorator. How can I set user to request.user?

like image 474
gamer Avatar asked Jul 22 '15 07:07

gamer


2 Answers

Try this:

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 the user and set the login credentials for the user. Then I create a client and login with that user. So in your views.py, when you do request.user, you will get this user.

like image 108
Sarin Madarasmi Avatar answered Oct 19 '22 10:10

Sarin Madarasmi


I was trying to do the same myself but found out that Django Test Client does not set the user in the request and it is not possible to set request.user while using Client any other way. I used RequestFactory to that.

def setUp(self):
    self.request_factory = RequestFactory()
    self.user = User.objects.create_user(
        username='javed', email='[email protected]', password='my_secret')
    
def test_my_test_method(self):
    payload = {
        'question_title_name': 'my first question title',
        'question_name': 'my first question',
        'question_tag_name': 'first, question'
    }
    request = self.request_factory.post(reverse('home'), payload)
    request.user = self.user
    response = home_page(request)

More about request factory here

like image 37
javed Avatar answered Oct 19 '22 09:10

javed