Reputation: 674
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='[email protected]',
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': '[email protected]', '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
Upvotes: 2
Views: 1241
Reputation: 11
User instance needs to be saved to the database:
self.user.is_superuser = True
self.user.save(update_fields=["is_superuser"])
Upvotes: 1