Pytest Login Test Fails

Hi,

I am using pytest for testing the login API and it is failing.

import pytest
from rest_framework import status

from core.fixtures.user import user


class TestAuthenticationViewSet:
    endpoint = "/api/auth/"

    def test_login(self, client, user):
        data = {"username": user.username, "password": "test_password"}
        response = client.post(self.endpoint + "login/", data)

        assert response.status_code == status.HTTP_200_OK
        assert response.data["access"]
        assert response.data["user"]["id"] == user.public_id.hex
        assert response.data["user"]["username"] == user.username
        assert response.data["user"]["email"] == user.email

I get the following warning and a subsequent Error

  assert response.status_code == status.HTTP_200_OK

E assert 400 == 200
E + where 400 = <Response status_code=400, “application/json”>.status_code
E + and 200 = status.HTTP_200_OK

core/auth/tests.py:14: AssertionError
----------------------------------------------- Captured log call -----------------------------------------------
WARNING django.request:log.py:225 Bad Request: /api/auth/login/

FAILED core/auth/tests.py::TestAuthenticationViewSet::test_login - assert 400 == 200

The login API works fine via Postman or Browser. What am I missing?

Cheers,
Nithin

What do your fixtures look like?

Are you working with a test database separate from your main database, that you wouldn’t be using when testing with Postman or the browser?

What other environmental differences might there be?

I am following a tutorial related to this (GitHub - PacktPublishing/Full-stack-Django-and-React: Full-stack Django and React, published by Packt). I am assuming it is the same database. The user fixture is here.

import pytest
from core.user.models import User

data_user = {
    "username": "test_user",
    "email": "test@gmail.com",
    "first_name": "Test",
    "last_name": "User",
    "password": "test_password",
}


@pytest.fixture
def user(db) -> User:
    return User.objects.create_user(**data_user)

The conftest.py file is here.

import pytest
from rest_framework.test import APIClient

@pytest.fixture
def client():
    return APIClient()

I am also wondering why there is a bad request.

What does the authentication viewset and related serializer look like ?

Also, when getting a 400 response status, printing the response content would show you what’s wrong with the request

Thanks for the tip on the Response status. It was expecting email whereas I was passing the user name.