97 lines
4.9 KiB
Python
97 lines
4.9 KiB
Python
|
from fastapi.testclient import TestClient
|
|||
|
from sqlalchemy.orm import Session
|
|||
|
import pytest
|
|||
|
|
|||
|
# Импортируем модели и схемы (если нужно для assert'ов)
|
|||
|
from app.models.calculation import Calculation
|
|||
|
from app.schemas.calculation import CalculationRead
|
|||
|
|
|||
|
# Используем фикстуры client и db_session из conftest.py
|
|||
|
|
|||
|
def test_create_calculation(client: TestClient, db_session: Session):
|
|||
|
"""Тест успешного создания расчета."""
|
|||
|
input_data = {
|
|||
|
"input_params": {"width": 1000, "height": 800, "pieces": [1, 2, 3]},
|
|||
|
"model_name": "test_model"
|
|||
|
}
|
|||
|
response = client.post("/calculation/", json=input_data)
|
|||
|
|
|||
|
assert response.status_code == 201
|
|||
|
data = response.json()
|
|||
|
assert data["input_params"] == input_data["input_params"]
|
|||
|
assert data["model_name"] == input_data["model_name"]
|
|||
|
assert "id" in data
|
|||
|
assert "timestamp" in data
|
|||
|
assert "output_results" in data # Заглушка должна вернуть результаты
|
|||
|
assert data["output_results"] is not None
|
|||
|
# Можно добавить более детальные проверки output_results, если заглушка детерминирована
|
|||
|
# assert "waste_percentage" in data["output_results"]
|
|||
|
assert "objective_score" in data # waste_percentage используется как objective_score
|
|||
|
|
|||
|
# Проверяем, что запись действительно появилась в тестовой БД
|
|||
|
calc_id = data["id"]
|
|||
|
db_calc = db_session.query(Calculation).filter(Calculation.id == calc_id).first()
|
|||
|
assert db_calc is not None
|
|||
|
assert db_calc.input_params == input_data["input_params"]
|
|||
|
assert db_calc.model_name == input_data["model_name"]
|
|||
|
assert db_calc.output_results is not None
|
|||
|
|
|||
|
def test_read_calculation(client: TestClient, db_session: Session):
|
|||
|
"""Тест получения расчета по ID."""
|
|||
|
# Сначала создаем расчет для теста
|
|||
|
input_data = {"input_params": {"size": "large"}, "model_name": "reader_test"}
|
|||
|
response_create = client.post("/calculation/", json=input_data)
|
|||
|
assert response_create.status_code == 201
|
|||
|
created_data = response_create.json()
|
|||
|
calc_id = created_data["id"]
|
|||
|
|
|||
|
# Теперь запрашиваем созданный расчет
|
|||
|
response_read = client.get(f"/calculation/{calc_id}")
|
|||
|
assert response_read.status_code == 200
|
|||
|
read_data = response_read.json()
|
|||
|
assert read_data["id"] == calc_id
|
|||
|
assert read_data["input_params"] == input_data["input_params"]
|
|||
|
assert read_data["model_name"] == input_data["model_name"]
|
|||
|
assert read_data["output_results"] == created_data["output_results"] # Сравниваем с тем, что вернул POST
|
|||
|
assert read_data["timestamp"] is not None
|
|||
|
assert read_data["objective_score"] is not None
|
|||
|
|
|||
|
def test_read_calculation_not_found(client: TestClient):
|
|||
|
"""Тест получения несуществующего расчета."""
|
|||
|
response = client.get("/calculation/99999") # Используем ID, которого точно нет
|
|||
|
assert response.status_code == 404
|
|||
|
assert response.json() == {"detail": "Calculation not found"}
|
|||
|
|
|||
|
def test_read_calculation_history(client: TestClient, db_session: Session):
|
|||
|
"""Тест получения истории расчетов."""
|
|||
|
# Очистим таблицу на всякий случай (хотя фикстура должна это делать)
|
|||
|
# db_session.query(Calculation).delete()
|
|||
|
# db_session.commit()
|
|||
|
|
|||
|
# Создаем несколько расчетов
|
|||
|
client.post("/calculation/", json={"input_params": {"test": 1}})
|
|||
|
client.post("/calculation/", json={"input_params": {"test": 2}})
|
|||
|
|
|||
|
# Запрашиваем историю
|
|||
|
response = client.get("/calculation/history/")
|
|||
|
assert response.status_code == 200
|
|||
|
history_data = response.json()
|
|||
|
assert isinstance(history_data, list)
|
|||
|
assert len(history_data) >= 2 # Проверяем, что созданные расчеты есть в истории
|
|||
|
|
|||
|
# Проверяем структуру элементов истории
|
|||
|
if len(history_data) > 0:
|
|||
|
item = history_data[0]
|
|||
|
assert "id" in item
|
|||
|
assert "input_params" in item
|
|||
|
assert "output_results" in item
|
|||
|
assert "timestamp" in item
|
|||
|
assert "model_name" in item
|
|||
|
assert "objective_score" in item
|
|||
|
|
|||
|
def test_create_calculation_invalid_input(client: TestClient):
|
|||
|
"""Тест создания расчета с невалидными данными (проверка Pydantic)."""
|
|||
|
# Отправляем данные без обязательного поля input_params
|
|||
|
response = client.post("/calculation/", json={"model_name": "invalid"})
|
|||
|
assert response.status_code == 422 # Ошибка валидации Pydantic
|
|||
|
# Можно проверить тело ошибки, если нужно
|