uchill/backend/apps/users/tests/test_api.py

178 lines
6.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Тесты API пользователей.
"""
import pytest
from django.contrib.auth import get_user_model
from rest_framework import status
User = get_user_model()
@pytest.mark.django_db
class TestUserRegistration:
"""Тесты регистрации пользователей."""
def test_register_mentor_success(self, api_client):
"""Тест успешной регистрации ментора."""
data = {
'email': 'newmentor@test.com',
'password': 'SecurePass123!',
'password_confirm': 'SecurePass123!',
'first_name': 'Новый',
'last_name': 'Ментор',
'phone': '+79991234567',
'role': 'mentor'
}
response = api_client.post('/api/users/register/', data)
assert response.status_code == status.HTTP_201_CREATED
assert 'user' in response.data
assert response.data['user']['email'] == 'newmentor@test.com'
assert response.data['user']['role'] == 'mentor'
# Проверяем, что пользователь создан в БД
user = User.objects.get(email='newmentor@test.com')
assert user is not None
assert user.is_email_verified is False # Требуется верификация
def test_register_with_existing_email(self, api_client, mentor_user):
"""Тест регистрации с уже существующим email."""
data = {
'email': mentor_user.email,
'password': 'SecurePass123!',
'password_confirm': 'SecurePass123!',
'first_name': 'Другой',
'last_name': 'Пользователь',
'phone': '+79991234568',
'role': 'client'
}
response = api_client.post('/api/users/register/', data)
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_register_password_mismatch(self, api_client):
"""Тест регистрации с несовпадающими паролями."""
data = {
'email': 'test@test.com',
'password': 'SecurePass123!',
'password_confirm': 'DifferentPass123!',
'first_name': 'Тест',
'last_name': 'Пользователь',
'phone': '+79991234569',
'role': 'client'
}
response = api_client.post('/api/users/register/', data)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.django_db
class TestUserLogin:
"""Тесты входа пользователей."""
def test_login_success(self, api_client, mentor_user):
"""Тест успешного входа."""
data = {
'email': 'mentor@test.com',
'password': 'TestPass123!'
}
response = api_client.post('/api/users/login/', data)
assert response.status_code == status.HTTP_200_OK
assert 'access' in response.data
assert 'refresh' in response.data
assert 'user' in response.data
def test_login_invalid_credentials(self, api_client):
"""Тест входа с неверными учетными данными."""
data = {
'email': 'wrong@test.com',
'password': 'WrongPass123!'
}
response = api_client.post('/api/users/login/', data)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_login_unverified_email(self, api_client):
"""Тест входа с неподтвержденным email."""
# Создаем пользователя с неподтвержденным email
user = User.objects.create_user(
email='unverified@test.com',
password='TestPass123!',
first_name='Непроверенный',
last_name='Пользователь',
role='client',
is_email_verified=False
)
data = {
'email': 'unverified@test.com',
'password': 'TestPass123!'
}
response = api_client.post('/api/users/login/', data)
# В зависимости от логики - может быть 401 или 403
assert response.status_code in [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]
@pytest.mark.django_db
class TestUserProfile:
"""Тесты профиля пользователя."""
def test_get_profile(self, authenticated_client, mentor_user):
"""Тест получения профиля."""
response = authenticated_client.get('/api/users/profile/')
assert response.status_code == status.HTTP_200_OK
assert response.data['email'] == mentor_user.email
assert response.data['first_name'] == mentor_user.first_name
def test_update_profile(self, authenticated_client):
"""Тест обновления профиля."""
data = {
'first_name': 'Обновленное',
'last_name': 'Имя',
'phone': '+79999999999'
}
response = authenticated_client.patch('/api/users/profile/', data)
assert response.status_code == status.HTTP_200_OK
assert response.data['first_name'] == 'Обновленное'
assert response.data['last_name'] == 'Имя'
def test_profile_unauthorized(self, api_client):
"""Тест доступа к профилю без аутентификации."""
response = api_client.get('/api/users/profile/')
assert response.status_code == status.HTTP_401_UNAUTHORIZED
@pytest.mark.django_db
class TestTokenRefresh:
"""Тесты обновления токенов."""
def test_refresh_token(self, api_client, tokens_for_user, mentor_user):
"""Тест обновления access токена."""
tokens = tokens_for_user(mentor_user)
data = {'refresh': tokens['refresh']}
response = api_client.post('/api/users/token/refresh/', data)
assert response.status_code == status.HTTP_200_OK
assert 'access' in response.data
def test_refresh_invalid_token(self, api_client):
"""Тест обновления с невалидным токеном."""
data = {'refresh': 'invalid_token'}
response = api_client.post('/api/users/token/refresh/', data)
assert response.status_code == status.HTTP_401_UNAUTHORIZED