Sto configurando il DRF per lavorare con l'autenticazione token JWT. A un certo punto, mi sembra che DRF-JWT stia funzionando correttamente, ma non riesco a ottenere un test di accesso per funzionare correttamente.Django Rest Framework Test di autenticazione JWT
Ho seguito i passaggi di installazione nel django-rest-framework-jwt docs e sono in grado di eseguire correttamente il ricciolo $ curl -X POST -d "username=admin&password=abc123" http://localhost:8000/api-token-auth/
e recuperare un token.
Mi aspetto che il mio test mi restituisca un token, ma a quanto pare non ho impostato correttamente.
# 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)
I primi due Unittests eseguito correttamente, ma il terzo non tornerà il token, ma invece restituisce {'non_field_error':'Unable to login with provided credentials.'}
, quello che mi aspetto quando le credenziali non sono corrette.
Per creare l'istanza utente (e altre istanze del modello) sto utilizzando factory_boy. Questo stesso metodo per creare istanze funziona in altre app all'interno di questo progetto, così come altri progetti, e ho verificato che l'utente esiste nel database di test.
# factories.py
class UserFactory(DjangoModelFactory):
class Meta:
model = User
native_language = 'es'
class NormalUserFactory(UserFactory):
username = 'normaluser'
password = 'normalpassword'
email = '[email protected]'
first_name = 'John'
last_name = 'Doe'
qui sono le mie impostazioni relative così:
# settings.py
REST_FRAMEWORK = {
'API_ROOT': '/v1/',
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}
Si deve usare 'User.set_password' a imposta la password. Il campo 'password' contiene l'hash. –