80 lines
2.6 KiB
Python
80 lines
2.6 KiB
Python
from rest_framework import status
|
|
from rest_framework.test import APITestCase
|
|
from django.contrib.auth import get_user_model
|
|
|
|
User = get_user_model()
|
|
|
|
|
|
class TestLogin(APITestCase):
|
|
def setUp(self) -> None:
|
|
self.password = 'theonering'
|
|
self.user = User.objects.create(
|
|
username='sauron',
|
|
email='sauron@mordor.middleearth',
|
|
)
|
|
|
|
self.user.set_password(self.password)
|
|
self.user.save()
|
|
|
|
def test_login(self):
|
|
response = self.client.post('/api/v1/auth/login/', {
|
|
'username': self.user.username,
|
|
'password': self.password,
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.data.get('access') is not None
|
|
assert response.data.get('refresh') is not None
|
|
|
|
def test_login_then_verify(self):
|
|
response = self.client.post('/api/v1/auth/login/', {
|
|
'username': self.user.username,
|
|
'password': self.password,
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
jwt_token = response.data.get('access')
|
|
response = self.client.post('/api/v1/auth/verify/', {
|
|
'token': jwt_token,
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
|
|
def test_login_then_refresh(self):
|
|
response = self.client.post('/api/v1/auth/login/', {
|
|
'username': self.user.username,
|
|
'password': self.password,
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
jwt_token = response.data.get('refresh')
|
|
response = self.client.post('/api/v1/auth/refresh/', {
|
|
'refresh': jwt_token,
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.data.get('access') is not None
|
|
assert response.data.get('access') != jwt_token
|
|
|
|
def test_login_then_get_user_info(self):
|
|
response = self.client.post('/api/v1/auth/login/', {
|
|
'username': self.user.username,
|
|
'password': self.password,
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
jwt_token = response.data.get('access')
|
|
self.client.credentials(HTTP_AUTHORIZATION=f'JWT {jwt_token}')
|
|
response = self.client.get('/api/v1/auth/me/')
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.data.get('email') == self.user.email
|
|
|
|
def test_login_failed(self):
|
|
response = self.client.post('/api/v1/auth/login/', {
|
|
'username': self.user.username,
|
|
'password': 'wrongpassword',
|
|
})
|
|
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|