This repository has been archived on 2022-05-05. You can view files and clone it, but cannot push or open issues or pull requests.
userausfall/userausfall/rest_api/tests/auth.py

91 lines
2.8 KiB
Python

from rest_framework import status
from userausfall.models import User
from userausfall.rest_api.tests.userausfall import UserausfallAPITestCase
class UserMixin:
user: User
password: str
username: str
def create_user(self):
self.username = f"test{User.objects.count()}"
self.password = "test12345"
self.user = User.objects.create_user(self.username, self.password)
return self.user
def ensure_user_exists(self):
if not hasattr(self, "user"):
self.create_user()
def authenticate_user(self):
self.ensure_user_exists()
if hasattr(self.client, "force_authentication"):
self.client.force_authenticate(user=self.user)
else:
self.client.force_login(user=self.user)
class AuthenticationTestCase(UserMixin, UserausfallAPITestCase):
base_url = "/api/auth"
def test_signup(self):
"""
Create a new user account (signup)
"""
url = "/register/"
username = "test"
password = "test12345"
data = {"username": username, "password": password, "passwordConfirm": password}
response = self.client.post(self.get_api_url(url), data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(User.objects.count(), 1)
self.assertEqual(User.objects.get().username, username)
def test_login(self) -> None:
"""
Create a session cookie (login)
"""
url = "/login/"
self.create_user()
data = {"login": self.username, "password": self.password}
response = self.client.post(self.get_api_url(url), data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(response.wsgi_request.user.is_authenticated)
def test_logout(self) -> None:
"""
Remove the session (logout)
"""
url = "/logout/"
self.authenticate_user()
response = self.client.post(self.get_api_url(url))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertFalse(response.wsgi_request.user.is_authenticated)
def test_retrieve_user(self) -> None:
"""
Retrieve data of authenticated user
"""
url = "/profile/"
self.create_user()
self.authenticate_user()
response = self.client.get(self.get_api_url(url))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertDictEqual(
response.data,
{
"username": self.username,
"id": self.user.id,
},
)
def test_create_two_users(self) -> None:
"""
Create more than one user
"""
self.create_user()
self.create_user()
self.assertEqual(User.objects.count(), 2)