Force_authenticate superuser django rest unit testing

Viewed 750

I have structured my api so that only the superuser can delete accounts. I am trying to force authenticate a superuser in my unit test but I am running into issues.

Unit test:

class PrivateUserApiTests(TestCase):
  """Test the users API (private)"""

  def setUp(self):
    self.user = create_user(
      email='tes111t@test.com',
      password='test123',
      name='name',
    )
    self.user.is_superuser = True
    self.client = APIClient()
    self.client.force_authenticate(user=self.user)

  def test_user_successful_delete(self):
    """Test that user was succesfully deleted"""
    payload = {'email': 'test@test123.com', 'password': 'test123'}
    user = create_user(**payload)
    res = self.client.delete(reverse('user:delete_user', kwargs={'pk': user.id}))

    self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)

ERROR:

Traceback (most recent call last):
  File "/app/user/tests/test_user_api.py", line 152, in test_user_successful_delete
    self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)
AssertionError: 403 != 204

Am I using the force_authenticate() method wrong? How can I create a user that is a superuser

1 Answers

User instance needs to be saved to the database:

self.user.is_superuser = True
self.user.save(update_fields=["is_superuser"])
Related