I am configuring DRF to work with JWT token authentication. I seem to be in such a situation that DRF-JWT says that it works correctly, but I can not successfully pass the login test.
I went through the installation steps in django-rest-framework-jwt docs and I can successfully run curl $ curl -X POST -d "username=admin&password=abc123" http://localhost:8000/api-token-auth/ and return token.
I expect my test will also return a token to me, but apparently I do not have it correctly.
# tests.py class LoginTests(APITestCase): def setUp(self): self.user = NormalUserFactory.create() self.jwt_url = reverse('jwt_login') def test_token_get_not_allowed(self): # do not allow GET requests to the login page response = self.client.get(self.jwt_url) self.assertEqual(response.data.get('detail'), 'Method "GET" not allowed.') def test_token_login_fail_incorrect_credentials(self): # pass in incorrect credentials data = { 'username': self.user.username, 'password': 'inCorrect01' } response = self.client.post(self.jwt_url, data) self.assertEqual(response.data.get('non_field_errors'), ['Unable to login with provided credentials.']) def test_token_login_success(self): data = { 'username': self.user.username, 'password': 'normalpassword', } response = self.client.post(self.jwt_url, data) print(response.data.get("token")) self.assertNotEqual(response.data.get("token"), None)
The first two unittests run successfully, but the third does not return a token, but instead returns {'non_field_error':'Unable to login with provided credentials.'} , Which I expect when the credentials are incorrect.
To create a user instance (and other model instances), I use factory_boy. The same method of creating instances works in other applications in this project, as well as in other projects, and I confirmed that the user exists in the test database.
# factories.py class UserFactory(DjangoModelFactory): class Meta: model = User native_language = 'es' class NormalUserFactory(UserFactory): username = 'normaluser' password = 'normalpassword' email = ' user@email.com ' first_name = 'John' last_name = 'Doe'
here are my respective settings:
# settings.py REST_FRAMEWORK = { 'API_ROOT': '/v1/', 'TEST_REQUEST_DEFAULT_FORMAT': 'json',