pytest 1.2

This commit is contained in:
2025-10-12 16:39:15 +03:00
parent a4f9af3e2d
commit d0a13e3863
2 changed files with 35 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
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() #после теста очистка оверрайда, чтобы не повлиять на другие тесты.