mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
Fix tests
This commit is contained in:
@@ -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()
|
||||
@@ -8,7 +8,7 @@ def test_login_employee_success(client: TestClient, test_employee: Employee):
|
||||
"""Тест успешной авторизации сотрудника."""
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
data={"username": test_employee.email, "password": "testpassword"}
|
||||
data={"username": test_employee.last_name, "password": "testpassword"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert "access_token" in response.json()
|
||||
@@ -19,7 +19,7 @@ def test_login_employee_wrong_password(client: TestClient, test_employee: Employ
|
||||
"""Тест авторизации сотрудника с неверным паролем."""
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
data={"username": test_employee.email, "password": "wrongpassword"}
|
||||
data={"username": test_employee.last_name, "password": "wrongpassword"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Incorrect username or password"
|
||||
@@ -28,7 +28,7 @@ def test_login_employee_wrong_username(client: TestClient):
|
||||
"""Тест авторизации с несуществующим пользователем."""
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
data={"username": "nonexistent@example.com", "password": "testpassword"}
|
||||
data={"username": "nonexistent", "password": "testpassword"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Incorrect username or password"
|
||||
@@ -37,7 +37,7 @@ def test_login_admin_success(client: TestClient, test_admin: Employee):
|
||||
"""Тест успешной авторизации администратора."""
|
||||
response = client.post(
|
||||
"/api/auth/admin/login",
|
||||
data={"username": test_admin.email, "password": "adminpassword"}
|
||||
data={"username": test_admin.last_name, "password": "adminpassword"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert "access_token" in response.json()
|
||||
@@ -48,7 +48,7 @@ def test_login_admin_wrong_password(client: TestClient, test_admin: Employee):
|
||||
"""Тест авторизации администратора с неверным паролем."""
|
||||
response = client.post(
|
||||
"/api/auth/admin/login",
|
||||
data={"username": test_admin.email, "password": "wrongpassword"}
|
||||
data={"username": test_admin.last_name, "password": "wrongpassword"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Incorrect username or password"
|
||||
@@ -61,8 +61,8 @@ def test_protected_route_with_valid_token(client: TestClient, employee_token: st
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
assert data["first_name"] == test_employee.first_name
|
||||
assert data["last_name"] == test_employee.last_name
|
||||
|
||||
def test_protected_route_without_token(client: TestClient):
|
||||
"""Тест доступа к защищенному маршруту без токена."""
|
||||
@@ -77,4 +77,4 @@ def test_protected_route_with_invalid_token(client: TestClient):
|
||||
headers={"Authorization": "Bearer invalid_token"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Could not validate credentials"
|
||||
assert response.json()["detail"] == "Invalid authentication credentials"
|
||||
@@ -10,19 +10,19 @@ def test_create_employee(client: TestClient, admin_token: str, db: Session):
|
||||
"/api/employees",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
json={
|
||||
"email": "new@example.com",
|
||||
"password": "newpassword",
|
||||
"full_name": "New Employee",
|
||||
"first_name": "New",
|
||||
"last_name": "Employee",
|
||||
"department": "IT",
|
||||
"is_active": True,
|
||||
"is_admin": False
|
||||
"office": "102",
|
||||
"password": "newpassword"
|
||||
}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["email"] == "new@example.com"
|
||||
assert data["full_name"] == "New Employee"
|
||||
assert data["first_name"] == "New"
|
||||
assert data["last_name"] == "Employee"
|
||||
assert data["department"] == "IT"
|
||||
assert data["office"] == "102"
|
||||
assert "id" in data
|
||||
|
||||
def test_create_employee_unauthorized(client: TestClient):
|
||||
@@ -30,11 +30,11 @@ def test_create_employee_unauthorized(client: TestClient):
|
||||
response = client.post(
|
||||
"/api/employees",
|
||||
json={
|
||||
"email": "new@example.com",
|
||||
"password": "newpassword",
|
||||
"full_name": "New Employee",
|
||||
"is_active": True,
|
||||
"is_admin": False
|
||||
"first_name": "New",
|
||||
"last_name": "Employee",
|
||||
"department": "IT",
|
||||
"office": "102",
|
||||
"password": "newpassword"
|
||||
}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
@@ -50,9 +50,10 @@ def test_get_employees(client: TestClient, admin_token: str, test_employee: Empl
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert len(data) > 0
|
||||
assert "email" in data[0]
|
||||
assert "full_name" in data[0]
|
||||
assert "first_name" in data[0]
|
||||
assert "last_name" in data[0]
|
||||
assert "department" in data[0]
|
||||
assert "office" in data[0]
|
||||
|
||||
def test_get_employee_by_id(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения сотрудника по ID."""
|
||||
@@ -62,9 +63,10 @@ def test_get_employee_by_id(client: TestClient, admin_token: str, test_employee:
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
assert data["first_name"] == test_employee.first_name
|
||||
assert data["last_name"] == test_employee.last_name
|
||||
assert data["department"] == test_employee.department
|
||||
assert data["office"] == test_employee.office
|
||||
|
||||
def test_get_nonexistent_employee(client: TestClient, admin_token: str):
|
||||
"""Тест получения несуществующего сотрудника."""
|
||||
@@ -81,18 +83,18 @@ def test_update_employee(client: TestClient, admin_token: str, test_employee: Em
|
||||
f"/api/employees/{test_employee.id}",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
json={
|
||||
"email": "updated@example.com",
|
||||
"full_name": "Updated Employee",
|
||||
"first_name": "Updated",
|
||||
"last_name": "Name",
|
||||
"department": "HR",
|
||||
"is_active": True,
|
||||
"is_admin": False
|
||||
"office": "103"
|
||||
}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == "updated@example.com"
|
||||
assert data["full_name"] == "Updated Employee"
|
||||
assert data["first_name"] == "Updated"
|
||||
assert data["last_name"] == "Name"
|
||||
assert data["department"] == "HR"
|
||||
assert data["office"] == "103"
|
||||
|
||||
def test_delete_employee(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест удаления сотрудника."""
|
||||
@@ -102,9 +104,10 @@ def test_delete_employee(client: TestClient, admin_token: str, test_employee: Em
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
assert data["first_name"] == test_employee.first_name
|
||||
assert data["last_name"] == test_employee.last_name
|
||||
assert data["department"] == test_employee.department
|
||||
assert data["office"] == test_employee.office
|
||||
|
||||
def test_employee_me(client: TestClient, employee_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения информации о текущем сотруднике."""
|
||||
@@ -114,9 +117,10 @@ def test_employee_me(client: TestClient, employee_token: str, test_employee: Emp
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
assert data["first_name"] == test_employee.first_name
|
||||
assert data["last_name"] == test_employee.last_name
|
||||
assert data["department"] == test_employee.department
|
||||
assert data["office"] == test_employee.office
|
||||
|
||||
def test_update_me(client: TestClient, employee_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест обновления информации о текущем сотруднике."""
|
||||
@@ -124,12 +128,15 @@ def test_update_me(client: TestClient, employee_token: str, test_employee: Emplo
|
||||
"/api/employees/me",
|
||||
headers={"Authorization": f"Bearer {employee_token}"},
|
||||
json={
|
||||
"full_name": "Updated Name",
|
||||
"department": "Support"
|
||||
"first_name": "Updated",
|
||||
"last_name": "Name",
|
||||
"department": "Support",
|
||||
"office": "104"
|
||||
}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["full_name"] == "Updated Name"
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["department"] == "Support"
|
||||
assert data["first_name"] == "Updated"
|
||||
assert data["last_name"] == "Name"
|
||||
assert data["department"] == "Support"
|
||||
assert data["office"] == "104"
|
||||
@@ -11,14 +11,14 @@ def test_create_request(client: TestClient, employee_token: str, db: Session):
|
||||
"/api/requests",
|
||||
headers={"Authorization": f"Bearer {employee_token}"},
|
||||
json={
|
||||
"request_type": "support",
|
||||
"request_type": "equipment",
|
||||
"description": "Test Description",
|
||||
"priority": "medium"
|
||||
}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["request_type"] == "support"
|
||||
assert data["request_type"] == "equipment"
|
||||
assert data["description"] == "Test Description"
|
||||
assert data["priority"] == "medium"
|
||||
assert data["status"] == "new"
|
||||
@@ -29,7 +29,7 @@ def test_create_request_unauthorized(client: TestClient):
|
||||
response = client.post(
|
||||
"/api/requests",
|
||||
json={
|
||||
"request_type": "support",
|
||||
"request_type": "equipment",
|
||||
"description": "Test Description",
|
||||
"priority": "medium"
|
||||
}
|
||||
@@ -39,13 +39,9 @@ def test_create_request_unauthorized(client: TestClient):
|
||||
|
||||
def test_get_employee_requests(client: TestClient, employee_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения списка заявок сотрудника."""
|
||||
db.add(test_employee)
|
||||
db.commit()
|
||||
db.refresh(test_employee)
|
||||
|
||||
# Создаем тестовую заявку
|
||||
request = Request(
|
||||
request_type="support",
|
||||
request_type="equipment",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
@@ -62,18 +58,14 @@ def test_get_employee_requests(client: TestClient, employee_token: str, test_emp
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert len(data) > 0
|
||||
assert data[0]["request_type"] == "support"
|
||||
assert data[0]["request_type"] == "equipment"
|
||||
assert data[0]["description"] == "Test Description"
|
||||
|
||||
def test_admin_get_all_requests(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения всех заявок администратором."""
|
||||
db.add(test_employee)
|
||||
db.commit()
|
||||
db.refresh(test_employee)
|
||||
|
||||
# Создаем тестовую заявку
|
||||
request = Request(
|
||||
request_type="support",
|
||||
request_type="equipment",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
@@ -90,23 +82,18 @@ def test_admin_get_all_requests(client: TestClient, admin_token: str, test_emplo
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert len(data) > 0
|
||||
assert data[0]["request_type"] == "support"
|
||||
assert data[0]["request_type"] == "equipment"
|
||||
assert data[0]["description"] == "Test Description"
|
||||
|
||||
def test_update_request_status(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест обновления статуса заявки."""
|
||||
db.add(test_employee)
|
||||
db.commit()
|
||||
db.refresh(test_employee)
|
||||
|
||||
# Создаем тестовую заявку
|
||||
request = Request(
|
||||
request_type="support",
|
||||
request_type="equipment",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
employee_id=test_employee.id
|
||||
)
|
||||
db.add(request)
|
||||
db.commit()
|
||||
@@ -122,35 +109,28 @@ def test_update_request_status(client: TestClient, admin_token: str, test_employ
|
||||
|
||||
def test_get_request_statistics(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения статистики по заявкам."""
|
||||
db.add(test_employee)
|
||||
db.commit()
|
||||
db.refresh(test_employee)
|
||||
|
||||
# Создаем тестовые заявки с разными статусами
|
||||
requests = [
|
||||
Request(
|
||||
request_type="support",
|
||||
request_type="equipment",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
employee_id=test_employee.id
|
||||
),
|
||||
Request(
|
||||
request_type="support",
|
||||
request_type="equipment",
|
||||
description="Test Description",
|
||||
priority="high",
|
||||
status="in_progress",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
employee_id=test_employee.id
|
||||
),
|
||||
Request(
|
||||
request_type="support",
|
||||
request_type="equipment",
|
||||
description="Test Description",
|
||||
priority="low",
|
||||
status="completed",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
employee_id=test_employee.id
|
||||
)
|
||||
]
|
||||
for req in requests:
|
||||
|
||||
Reference in New Issue
Block a user