1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

Fix database

This commit is contained in:
MoonTestUse1
2025-01-07 05:58:51 +06:00
parent 4a9aafa810
commit 4dbe6f28d9
2 changed files with 73 additions and 45 deletions

View File

@@ -11,6 +11,8 @@ pytest>=7.4.0
pytest-cov>=4.1.0 pytest-cov>=4.1.0
pytest-timeout>=2.1.0 pytest-timeout>=2.1.0
pytest-xdist>=3.3.1 pytest-xdist>=3.3.1
pytest-mock>=3.10.0
httpx>=0.24.1 httpx>=0.24.1
redis>=4.6.0 redis>=4.6.0
aiogram>=3.4.0
python-telegram-bot>=20.4 python-telegram-bot>=20.4

View File

@@ -1,68 +1,94 @@
"""Test configuration""" """Test configuration"""
import os import os
import pytest import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, scoped_session
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from typing import Generator, Any from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
# Устанавливаем переменную окружения для тестов from app.core.config import settings
os.environ["TESTING"] = "1" from app.db.base import Base
from app.database import Base
from app.main import app from app.main import app
from app.core.test_config import test_settings from app.deps import get_db
from app.dependencies import get_db from app.models.employee import Employee
from .test_fixtures import * # импортируем все фикстуры from app.utils.security import get_password_hash
# Создаем тестовый движок базы данных # Mock Telegram notifications
DATABASE_URL = os.getenv("DATABASE_URL", test_settings.get_database_url()) @pytest.fixture(autouse=True)
engine = create_engine( def mock_telegram_bot(mocker):
DATABASE_URL, """Mock Telegram Bot"""
pool_size=5, mock_bot = mocker.patch('app.utils.telegram.Bot')
max_overflow=10, return mock_bot
pool_timeout=30,
pool_pre_ping=True
)
# Создаем тестовую фабрику сессий @pytest.fixture(autouse=True)
TestingSessionLocal = scoped_session( def mock_telegram_notify(mocker):
sessionmaker(autocommit=False, autoflush=False, bind=engine) """Mock Telegram notifications"""
) mocker.patch('app.utils.telegram.notify_new_request', return_value=None)
@pytest.fixture(scope="session", autouse=True) # Database fixtures
def setup_test_db() -> Generator[None, Any, None]: @pytest.fixture(scope="session")
"""Setup test database""" def engine():
# Создаем все таблицы """Create test database engine"""
Base.metadata.drop_all(bind=engine) engine = create_engine(
"sqlite:///:memory:",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
yield return engine
# Удаляем все таблицы и закрываем соединения
TestingSessionLocal.remove()
Base.metadata.drop_all(bind=engine)
engine.dispose()
@pytest.fixture(scope="function") @pytest.fixture(scope="function")
def db_session() -> Generator[Any, Any, None]: def db_session(engine):
"""Get database session""" """Create test database session"""
session = TestingSessionLocal() Session = sessionmaker(bind=engine)
session = Session()
try: try:
yield session yield session
finally: finally:
session.rollback() session.rollback()
session.close() session.close()
TestingSessionLocal.remove()
@pytest.fixture(scope="function") @pytest.fixture
def client(db_session: Any) -> Generator[TestClient, Any, None]: def client(db_session):
"""Get test client""" """Create test client"""
def override_get_db() -> Generator[Any, Any, None]: def override_get_db():
try: try:
yield db_session yield db_session
finally: finally:
pass pass
app.dependency_overrides[get_db] = override_get_db app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as test_client: return TestClient(app)
yield test_client
app.dependency_overrides.clear() @pytest.fixture
def test_employee(db_session):
"""Create test employee"""
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="Main",
hashed_password=get_password_hash("testpass123"),
is_active=True,
is_admin=False
)
db_session.add(employee)
db_session.commit()
db_session.refresh(employee)
return employee
@pytest.fixture
def test_admin(db_session):
"""Create test admin"""
admin = Employee(
first_name="Admin",
last_name="User",
department="IT",
office="Main",
hashed_password=get_password_hash("adminpass123"),
is_active=True,
is_admin=True
)
db_session.add(admin)
db_session.commit()
db_session.refresh(admin)
return admin