mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
Fix tests
This commit is contained in:
36
backend/app/core/test_config.py
Normal file
36
backend/app/core/test_config.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
"""Test settings configuration"""
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
class TestSettings(BaseSettings):
|
||||||
|
"""Test application settings"""
|
||||||
|
PROJECT_NAME: str = "Support Service Test"
|
||||||
|
VERSION: str = "1.0.0"
|
||||||
|
API_V1_STR: str = "/api"
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DATABASE_URL: str = "sqlite:///:memory:"
|
||||||
|
|
||||||
|
# JWT
|
||||||
|
SECRET_KEY: str = "test-secret-key"
|
||||||
|
ALGORITHM: str = "HS256"
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||||
|
|
||||||
|
# Redis
|
||||||
|
REDIS_HOST: str = "redis"
|
||||||
|
REDIS_PORT: int = 6379
|
||||||
|
|
||||||
|
# Admin
|
||||||
|
ADMIN_USERNAME: str = "admin"
|
||||||
|
ADMIN_PASSWORD: str = "admin123"
|
||||||
|
|
||||||
|
# Telegram
|
||||||
|
TELEGRAM_BOT_TOKEN: str = "test-bot-token"
|
||||||
|
TELEGRAM_CHAT_ID: str = "test-chat-id"
|
||||||
|
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env.test",
|
||||||
|
env_file_encoding="utf-8",
|
||||||
|
case_sensitive=True
|
||||||
|
)
|
||||||
|
|
||||||
|
test_settings = TestSettings()
|
||||||
@@ -8,8 +8,16 @@ from .models.employee import Employee # noqa
|
|||||||
from .models.request import Request # noqa
|
from .models.request import Request # noqa
|
||||||
from .models.token import Token # noqa
|
from .models.token import Token # noqa
|
||||||
|
|
||||||
# Используем разные URL для тестов и продакшена
|
def get_database_url():
|
||||||
SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL
|
"""Получение URL базы данных в зависимости от окружения."""
|
||||||
|
try:
|
||||||
|
from .core.test_config import test_settings
|
||||||
|
return test_settings.DATABASE_URL
|
||||||
|
except ImportError:
|
||||||
|
return settings.DATABASE_URL
|
||||||
|
|
||||||
|
# Используем правильный URL для базы данных
|
||||||
|
SQLALCHEMY_DATABASE_URL = get_database_url()
|
||||||
|
|
||||||
# Создаем движок с нужными параметрами
|
# Создаем движок с нужными параметрами
|
||||||
connect_args = {}
|
connect_args = {}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
from .models.base import Base
|
from .models.base import Base
|
||||||
from .database import engine, SessionLocal
|
from .database import engine, SessionLocal
|
||||||
@@ -9,9 +10,11 @@ from .routers import admin, employees, requests, auth, statistics
|
|||||||
from .db.init_db import init_db
|
from .db.init_db import init_db
|
||||||
from .core.config import settings
|
from .core.config import settings
|
||||||
|
|
||||||
# Создаем таблицы только если не в тестовом режиме
|
def get_application(app_settings: BaseSettings = settings) -> FastAPI:
|
||||||
if not settings.TESTING:
|
"""Создание экземпляра приложения с заданными настройками."""
|
||||||
|
# Создаем таблицы
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
# Инициализируем базу данных
|
# Инициализируем базу данных
|
||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
@@ -19,37 +22,41 @@ if not settings.TESTING:
|
|||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
# Включаем автоматическое перенаправление со слэшем
|
# Включаем автоматическое перенаправление со слэшем
|
||||||
redirect_slashes=True,
|
redirect_slashes=True,
|
||||||
# Добавляем описание API
|
# Добавляем описание API
|
||||||
title="Support System API",
|
title="Support System API",
|
||||||
description="API для системы поддержки",
|
description="API для системы поддержки",
|
||||||
version="1.0.0"
|
version="1.0.0"
|
||||||
)
|
)
|
||||||
|
|
||||||
# CORS configuration
|
# CORS configuration
|
||||||
origins = [
|
origins = [
|
||||||
"http://localhost",
|
"http://localhost",
|
||||||
"http://localhost:8080",
|
"http://localhost:8080",
|
||||||
"http://localhost:5173",
|
"http://localhost:5173",
|
||||||
"http://127.0.0.1:5173",
|
"http://127.0.0.1:5173",
|
||||||
"http://127.0.0.1:8080",
|
"http://127.0.0.1:8080",
|
||||||
"http://185.139.70.62", # Добавляем ваш production домен
|
"http://185.139.70.62", # Добавляем ваш production домен
|
||||||
]
|
]
|
||||||
|
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=origins,
|
allow_origins=origins,
|
||||||
allow_credentials=True,
|
allow_credentials=True,
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
expose_headers=["*"]
|
expose_headers=["*"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Include routers
|
# Include routers
|
||||||
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
|
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
|
||||||
app.include_router(employees.router, prefix="/api/employees", tags=["employees"])
|
app.include_router(employees.router, prefix="/api/employees", tags=["employees"])
|
||||||
app.include_router(requests.router, prefix="/api/requests", tags=["requests"])
|
app.include_router(requests.router, prefix="/api/requests", tags=["requests"])
|
||||||
app.include_router(admin.router, prefix="/api/admin", tags=["admin"])
|
app.include_router(admin.router, prefix="/api/admin", tags=["admin"])
|
||||||
app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])
|
app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
app = get_application()
|
||||||
@@ -2,14 +2,25 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from typing import Generator
|
from typing import Generator
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from sqlalchemy.pool import StaticPool
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from .test_config import engine, TestingSessionLocal
|
from app.core.test_config import test_settings
|
||||||
from app.database import get_db
|
from app.database import get_db
|
||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
from app.models.employee import Employee
|
from app.models.employee import Employee
|
||||||
from app.utils.auth import get_password_hash
|
from app.utils.auth import get_password_hash
|
||||||
|
|
||||||
|
# Создаем тестовую базу данных в памяти
|
||||||
|
engine = create_engine(
|
||||||
|
test_settings.DATABASE_URL,
|
||||||
|
connect_args={"check_same_thread": False},
|
||||||
|
poolclass=StaticPool
|
||||||
|
)
|
||||||
|
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
class MockRedis:
|
class MockRedis:
|
||||||
"""Мок для Redis."""
|
"""Мок для Redis."""
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@@ -55,14 +66,15 @@ def db() -> Generator:
|
|||||||
@pytest.fixture(scope="function")
|
@pytest.fixture(scope="function")
|
||||||
def client(db: TestingSessionLocal, redis_mock) -> Generator:
|
def client(db: TestingSessionLocal, redis_mock) -> Generator:
|
||||||
"""Фикстура для создания тестового клиента."""
|
"""Фикстура для создания тестового клиента."""
|
||||||
from app.main import app
|
|
||||||
|
|
||||||
def override_get_db():
|
def override_get_db():
|
||||||
try:
|
try:
|
||||||
yield db
|
yield db
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
# Импортируем app здесь, чтобы использовать тестовые настройки
|
||||||
|
from app.main import get_application
|
||||||
|
app = get_application(test_settings)
|
||||||
app.dependency_overrides[get_db] = override_get_db
|
app.dependency_overrides[get_db] = override_get_db
|
||||||
return TestClient(app)
|
return TestClient(app)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user