|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from datetime import UTC, datetime |
| 4 | +from types import SimpleNamespace |
| 5 | +from typing import Any, cast |
| 6 | +from unittest.mock import AsyncMock, Mock |
| 7 | +from uuid import uuid4 |
| 8 | + |
| 9 | +import pytest |
| 10 | +from fastapi import HTTPException |
| 11 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 12 | + |
| 13 | +from app.models.user import User |
| 14 | +from app.security import dependences as auth_dep |
| 15 | +from app.security.jwt import TokenData, TokenInvalid |
| 16 | + |
| 17 | + |
| 18 | +@pytest.fixture |
| 19 | +def fake_session() -> AsyncSession: |
| 20 | + """Создаёт фейковую AsyncSession для unit-тестов зависимости авторизации.""" |
| 21 | + return cast(AsyncSession, AsyncMock(spec=AsyncSession)) |
| 22 | + |
| 23 | + |
| 24 | +def _make_user(*, is_active: bool = True) -> User: |
| 25 | + """Создаёт лёгкий объект пользователя для тестирования веток get_current_user.""" |
| 26 | + return cast( |
| 27 | + User, |
| 28 | + SimpleNamespace( |
| 29 | + id=uuid4(), |
| 30 | + email="user@example.com", |
| 31 | + hashed_password="hashed", |
| 32 | + is_active=is_active, |
| 33 | + created_at=datetime.now(UTC), |
| 34 | + ), |
| 35 | + ) |
| 36 | + |
| 37 | + |
| 38 | +@pytest.mark.asyncio |
| 39 | +async def test_get_current_user_returns_active_user( |
| 40 | + fake_session: AsyncSession, |
| 41 | + monkeypatch: pytest.MonkeyPatch, |
| 42 | +) -> None: |
| 43 | + """Проверяет успешный путь: валидный токен и активный пользователь возвращаются как результат.""" |
| 44 | + user = _make_user(is_active=True) |
| 45 | + decode_access_token = Mock( |
| 46 | + return_value=TokenData(sub=str(user.id), payload={"type": "access"}) |
| 47 | + ) |
| 48 | + get_user_by_id = AsyncMock(return_value=user) |
| 49 | + monkeypatch.setattr(auth_dep, "decode_access_token", cast(Any, decode_access_token)) |
| 50 | + monkeypatch.setattr(auth_dep, "get_user_by_id", cast(Any, get_user_by_id)) |
| 51 | + |
| 52 | + result = await auth_dep.get_current_user(token="access-token", session=fake_session) |
| 53 | + |
| 54 | + assert result is user |
| 55 | + get_user_by_id.assert_awaited_once_with(fake_session, user.id) |
| 56 | + |
| 57 | + |
| 58 | +@pytest.mark.asyncio |
| 59 | +async def test_get_current_user_raises_401_for_invalid_token( |
| 60 | + fake_session: AsyncSession, |
| 61 | + monkeypatch: pytest.MonkeyPatch, |
| 62 | +) -> None: |
| 63 | + """Проверяет, что невалидный токен приводит к 401 и заголовку WWW-Authenticate.""" |
| 64 | + decode_access_token = Mock(side_effect=TokenInvalid("bad token")) |
| 65 | + monkeypatch.setattr(auth_dep, "decode_access_token", cast(Any, decode_access_token)) |
| 66 | + |
| 67 | + with pytest.raises(HTTPException) as exc: |
| 68 | + await auth_dep.get_current_user(token="broken-token", session=fake_session) |
| 69 | + |
| 70 | + assert exc.value.status_code == 401 |
| 71 | + assert exc.value.headers == {"WWW-Authenticate": "Bearer"} |
| 72 | + |
| 73 | + |
| 74 | +@pytest.mark.asyncio |
| 75 | +async def test_get_current_user_raises_401_for_invalid_subject( |
| 76 | + fake_session: AsyncSession, |
| 77 | + monkeypatch: pytest.MonkeyPatch, |
| 78 | +) -> None: |
| 79 | + """Проверяет ветку с некорректным sub в токене: должен возвращаться 401.""" |
| 80 | + decode_access_token = Mock( |
| 81 | + return_value=TokenData(sub="not-a-uuid", payload={"type": "access"}) |
| 82 | + ) |
| 83 | + monkeypatch.setattr(auth_dep, "decode_access_token", cast(Any, decode_access_token)) |
| 84 | + |
| 85 | + with pytest.raises(HTTPException) as exc: |
| 86 | + await auth_dep.get_current_user(token="access-token", session=fake_session) |
| 87 | + |
| 88 | + assert exc.value.status_code == 401 |
| 89 | + assert exc.value.detail == "Некорректный идентификатор в токене" |
| 90 | + |
| 91 | + |
| 92 | +@pytest.mark.asyncio |
| 93 | +async def test_get_current_user_raises_401_when_user_not_found( |
| 94 | + fake_session: AsyncSession, |
| 95 | + monkeypatch: pytest.MonkeyPatch, |
| 96 | +) -> None: |
| 97 | + """Проверяет, что при отсутствии пользователя в БД зависимость возвращает 401.""" |
| 98 | + user_id = uuid4() |
| 99 | + decode_access_token = Mock( |
| 100 | + return_value=TokenData(sub=str(user_id), payload={"type": "access"}) |
| 101 | + ) |
| 102 | + get_user_by_id = AsyncMock(return_value=None) |
| 103 | + monkeypatch.setattr(auth_dep, "decode_access_token", cast(Any, decode_access_token)) |
| 104 | + monkeypatch.setattr(auth_dep, "get_user_by_id", cast(Any, get_user_by_id)) |
| 105 | + |
| 106 | + with pytest.raises(HTTPException) as exc: |
| 107 | + await auth_dep.get_current_user(token="access-token", session=fake_session) |
| 108 | + |
| 109 | + assert exc.value.status_code == 401 |
| 110 | + assert exc.value.detail == "Сессия недействительна (пользователь не найден)" |
| 111 | + |
| 112 | + |
| 113 | +@pytest.mark.asyncio |
| 114 | +async def test_get_current_user_raises_403_for_inactive_user( |
| 115 | + fake_session: AsyncSession, |
| 116 | + monkeypatch: pytest.MonkeyPatch, |
| 117 | +) -> None: |
| 118 | + """Проверяет, что неактивный пользователь получает 403 в зависимости get_current_user.""" |
| 119 | + user = _make_user(is_active=False) |
| 120 | + decode_access_token = Mock( |
| 121 | + return_value=TokenData(sub=str(user.id), payload={"type": "access"}) |
| 122 | + ) |
| 123 | + get_user_by_id = AsyncMock(return_value=user) |
| 124 | + monkeypatch.setattr(auth_dep, "decode_access_token", cast(Any, decode_access_token)) |
| 125 | + monkeypatch.setattr(auth_dep, "get_user_by_id", cast(Any, get_user_by_id)) |
| 126 | + |
| 127 | + with pytest.raises(HTTPException) as exc: |
| 128 | + await auth_dep.get_current_user(token="access-token", session=fake_session) |
| 129 | + |
| 130 | + assert exc.value.status_code == 403 |
| 131 | + assert exc.value.detail == "Аккаунт заблокирован. Обратитесь в поддержку." |
0 commit comments