Cannot login in Django tests

186 Views Asked by At

Trying to write tests for a legacy Django 1.11 project. The project is using unittest package (I don't know if that's standard or a choice).

I'm trying to use django.test.Client.force_login to test a view with LoginRequiredMixin but it does nothing. I have added print(self.request.user) to the mixin's dispatch method. It outputs AnonymousUser whether I use force_login or not. Why is it not working?

The test (simplified for readability's sake):

class CheckoutTest(TestCase):
    def test_successful_payment(self):
        user = UserAccount.objects.create(email='[email protected]', is_owner=True, is_customer=True)

        self.client.force_login(user)

        self.client.post('/subscription/buy/' + str(package.id) + '/', {
            ... redacted ...
        })

The view:

class BuyPackageView(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        ... redacted ...
1

There are 1 best solutions below

1
Michael Ushakov On

My test code snippet looks like, I am getting user from table related to allauth app:

from django.test import TestCase
from rest_framework.test import APIClient
from mainapp.tests.test_helper import TestsHelper


class ProjectViewSetTestCase(TestCase):

    def setUp(self):
        self._client = APIClient(enforce_csrf_checks=False)
        self._test_helper.prepare_data()

    def tearDown(self):
        # do some custom clean-up

    def testCreateProjectWithoutKeyWords(self):
        user_id = self._test_helper.user1_id
        user = User.objects.get(id=user_id)

        # prepare current test data ...
        self._client.force_authenticate(user=user)
        # interact with REST API, if you need to switch user use logout
        self._client.logout()

   _client = None