Search code examples
pythondjangodjango-rest-frameworkdjango-testsdjango-rest-auth

Django REST Framework client.login() not working. (User created)


I'm building simple API with Django REST Framework, everything works as expected with curl and API web admin, but if I run the following test:

class OrderTest(APITestCase):
    username = 'admin'
    password = '12345'

    def setUp(self):
        User.objects.create(
            username=self.username,
            password=self.password,
            email='demo@demo.com',
            is_superuser=True,
            is_staff=True
        )

    def test_create_order_by_admin(self):
        url = '/api/orders/'
        data = {
            'name': 'John Doe',
            'phone': '380000000000',
            'status': 1,
            'email': 'jonhn.doe@gmail.com',
            'date': datetime.now(),
        }
        # Cheking if user exist
        self.assertEqual(User.objects.get(pk=1).username, self.username)
        self.client.login(
            username=self.username,
            password=self.password,
        )
        response = self.client.post(url, data, format='json')

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Order.objects.count(), 1)

        for key, value in data.items():
            self.assertEqual(Order.objects.get().key, value)

it fails with the following error:

Failure
Traceback (most recent call last):
  File "/home/linevich/projects/swebion.com/project/order_form/tests.py", line 71, in test_create_order_by_admin
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
AssertionError: 403 != 201

That means that client.login() not working. Any ideas?


Solution

  • Problem was in using User.objects.create() insetad of User.objects.create_superuser(), thanks to @C14L.