Files
2025-10-12 16:39:15 +03:00

40 lines
1.8 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.

import pytest
from httpx import AsyncClient, ASGITransport
from fastapi import status
from server.backend import JWT # твой JWT модуль
from server.backend.endpoints import api
from server.testing.conftest import client
@pytest.mark.asyncio
async def test_protected_unauthorized(client):
"Проверка: без токена — 401"
response = await client.get("/protected") #отправляется GET /protected без токена
assert response.status_code == status.HTTP_401_UNAUTHORIZED
@pytest.mark.asyncio
async def test_protected_invalidtoken(client):
"Проверка: Токена неверный - 401"
response = await client.get("/protected", headers={"Authorization": "Invalid token"})
assert response.status_code == status.HTTP_401_UNAUTHORIZED
@pytest.mark.asyncio
async def test_protected_authorized(client):
"Проверка: с токеном — ответ с Hello"
async def fake_current_user(): #фейковая зависимость (fake_current_user) — функция, которая имитирует поведение настоящего JWT.current_user, но просто возвращает строку "test_user".
return "test_user"
# подменяем зависимость
api.dependency_overrides[JWT.current_user] = fake_current_user #FastAPI позволяет временно подменять зависимости (через Depends).
response = await client.get("/protected", headers={"Authorization": "Bearer faketoken"})
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"msg": "Hello, test_user"}
api.dependency_overrides.clear() #после теста очистка оверрайда, чтобы не повлиять на другие тесты.