tests
This commit is contained in:
0
server/testing/__init__.py
Normal file
0
server/testing/__init__.py
Normal file
9
server/testing/conftest.py
Normal file
9
server/testing/conftest.py
Normal file
@@ -0,0 +1,9 @@
|
||||
import pytest_asyncio
|
||||
from httpx import AsyncClient, ASGITransport
|
||||
from server.backend.endpoints import api
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client():
|
||||
transport = ASGITransport(app=api)#подключение к FastAPI-приложению напрямую
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as ac: #Имитирует подключение в это приложение, как будто по сети
|
||||
yield ac #чтобы вернуть значение, но не завершить функцию.
|
||||
0
server/testing/tests/__init__.py
Normal file
0
server/testing/tests/__init__.py
Normal file
@@ -1,7 +1,39 @@
|
||||
# test_math.py
|
||||
def add(a, b):
|
||||
return a + b
|
||||
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() #после теста очистка оверрайда, чтобы не повлиять на другие тесты.
|
||||
|
||||
|
||||
def test_addition():
|
||||
assert add(2, 2) == 4
|
||||
assert add(-1, 1) == 0
|
||||
Reference in New Issue
Block a user