Search code examples
djangounit-testingdjango-testsdjango-unittest

Unittest with mock for django login


I am writing Unittests for the Login on Django. And I have serious problems with the get_user(). I just can't figure out how to get through this function in test. I can't make a mock, and I can't substitute values. I think I'm wrong do it. But I don't know how do it right!

Please, I need help!

def user_login(request):
    if request.method == 'POST':
        form = UserLoginForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('/')

I need unittest for this simply function.


Solution

  • Here is a very basic test for the login view, it asserts that a 200 response is returned when someone logs in. I don't think that mocks are required. For completeness you would most likely want to add tests for incorrect username/password and deactivated accounts

    import unittest
    from django.test import Client
    from django.contrib.auth import get_user_model
    
    
    class SimpleTest(unittest.TestCase):
        def setUp(self):
            self.client = Client()
            self.username = 'foo'
            self.password = 'bar'
            self.user = get_user_model().objects.create_user(self.username, password=self.password)
    
        def test_login(self):
            response = c.post('/login/', {'username': self.username, 'password': self.password})
            self.assertEqual(response.status_code, 200)