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

Fix tests

This commit is contained in:
MoonTestUse1
2025-01-06 23:40:39 +06:00
parent 161361609d
commit fec52c777b
17 changed files with 249 additions and 368 deletions

View File

@@ -1,129 +1,110 @@
"""Test configuration."""
"""Test fixtures"""
import os
import pytest
from typing import Generator
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
import fakeredis.aioredis
from typing import Generator
from app.core.test_config import test_settings
from app.database import get_db
from app.models.base import Base
# Устанавливаем флаг тестирования
os.environ["TESTING"] = "True"
from app.main import app
from app.database import Base, get_db
from app.models.employee import Employee
from app.utils.auth import get_password_hash
# Создаем тестовую базу данных в памяти
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
engine = create_engine(
test_settings.DATABASE_URL,
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
poolclass=StaticPool
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class MockRedis:
"""Мок для Redis."""
def __init__(self):
self.data = {}
# Создаем тестовую базу данных
Base.metadata.create_all(bind=engine)
def get(self, key):
return self.data.get(key)
def set(self, key, value, ex=None):
self.data[key] = value
return True
def delete(self, key):
if key in self.data:
del self.data[key]
return True
def exists(self, key):
return key in self.data
@pytest.fixture(scope="function")
def redis_mock():
"""Фикстура для мока Redis."""
with patch("app.utils.jwt.redis") as mock:
redis_instance = MockRedis()
mock.get.side_effect = redis_instance.get
mock.set.side_effect = redis_instance.set
mock.delete.side_effect = redis_instance.delete
mock.exists.side_effect = redis_instance.exists
yield mock
@pytest.fixture(scope="function")
@pytest.fixture
def db() -> Generator:
"""Фикстура для создания тестовой базы данных."""
Base.metadata.create_all(bind=engine)
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
Base.metadata.drop_all(bind=engine)
"""Фикстура для получения тестовой сессии БД."""
connection = engine.connect()
transaction = connection.begin()
session = TestingSessionLocal(bind=connection)
yield session
session.close()
transaction.rollback()
connection.close()
@pytest.fixture(scope="function")
def client(db: TestingSessionLocal, redis_mock) -> Generator:
"""Фикстура для создания тестового клиента."""
@pytest.fixture
def client(db) -> TestClient:
"""Фикстура для получения тестового клиента."""
def override_get_db():
try:
yield db
finally:
db.close()
pass
# Импортируем app здесь, чтобы использовать тестовые настройки
from app.main import get_application
app = get_application(test_settings)
app.dependency_overrides[get_db] = override_get_db
return TestClient(app)
yield TestClient(app)
app.dependency_overrides.clear()
@pytest.fixture(scope="function")
def test_employee(db: TestingSessionLocal) -> Employee:
@pytest.fixture
def test_employee(db) -> Employee:
"""Фикстура для создания тестового сотрудника."""
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="101",
hashed_password=get_password_hash("testpassword")
last_name="Employee",
department="Test Department",
office="Test Office",
hashed_password=get_password_hash("testpassword"),
is_admin=False
)
db.add(employee)
db.commit()
db.refresh(employee)
return employee
@pytest.fixture(scope="function")
def test_admin(db: TestingSessionLocal) -> Employee:
@pytest.fixture
def test_admin(db) -> Employee:
"""Фикстура для создания тестового администратора."""
admin = Employee(
first_name="Admin",
last_name="User",
department="Administration",
office="100",
hashed_password=get_password_hash("adminpassword")
department="Admin Department",
office="Admin Office",
hashed_password=get_password_hash("adminpassword"),
is_admin=True
)
db.add(admin)
db.commit()
db.refresh(admin)
return admin
@pytest.fixture(scope="function")
def employee_token(test_employee: Employee, db: TestingSessionLocal) -> str:
"""Фикстура для создания токена тестового сотрудника."""
from app.utils.jwt import create_access_token
token = create_access_token({"sub": str(test_employee.id)})
# Сохраняем токен в Redis мок
from app.utils.jwt import redis
redis.set(f"token:{token}", "valid")
return token
@pytest.fixture
def employee_token(client: TestClient, test_employee: Employee) -> str:
"""Фикстура для получения токена сотрудника."""
response = client.post(
"/api/auth/login",
data={"username": test_employee.last_name, "password": "testpassword"}
)
return response.json()["access_token"]
@pytest.fixture(scope="function")
def admin_token(test_admin: Employee, db: TestingSessionLocal) -> str:
"""Фикстура для создания токена администратора."""
from app.utils.jwt import create_access_token
token = create_access_token({"sub": str(test_admin.id)})
# Сохраняем токен в Redis мок
from app.utils.jwt import redis
redis.set(f"token:{token}", "valid")
return token
@pytest.fixture
def admin_token(client: TestClient, test_admin: Employee) -> str:
"""Фикстура для получения токена администратора."""
response = client.post(
"/api/auth/admin/login",
data={"username": test_admin.last_name, "password": "adminpassword"}
)
return response.json()["access_token"]
@pytest.fixture
def redis_mock():
"""Фикстура для мока Redis."""
return fakeredis.aioredis.FakeRedis()