0

can somebody help me. I can't authorize my test user in unittests

class APIGameTestCase(APITestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='testuser', password='123')
        self.token = Token.objects.get(user=self.user)
        self.api_authentication()

    def api_authentication(self):
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)

    def test_create_game(self):
        url = reverse('game-list')
        payload = {
            'name': 'testgame',
            'game_category': 'testgamecategory',
            'played': False,
            'release_date': '2016-06-21T03:02:00.776594Z',
        }
        response = self.client.post(url, payload)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

Assert error

AssertionError: 401 != 201

models.py

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

1 Answer 1

2

There is better way to do that. You can use client.force_authenticate. This is included in DRF Base test class. Bacause that, you can focus on testing

class APIGameTestCase(APITestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='testuser', password='123')
        self.client.force_authenticate(self.user)

    def test_create_game(self):
        url = reverse('game-list')
        payload = {
            'name': 'testgame',
            'game_category': 'testgamecategory',
            'played': False,
            'release_date': '2016-06-21T03:02:00.776594Z',
        }
        response = self.client.post(url, payload)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

You can read more about that here: https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

Sign up to request clarification or add additional context in comments.

2 Comments

Sharpek thanks for answer. With this advice i have a 400 Bad Request. Maybe the problem that my db is postgresql? I'm trying to print the auth user username with print(self.client.username) and i get the AttributeError: 'APIClient' object has no attribute 'username'
self.client it's not user, but APIClient - tool to do testing request. You have to check why you get bad request, by doing for example print(response.json())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.