mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
testing pipe
This commit is contained in:
@@ -1,101 +1,127 @@
|
||||
"""Test configuration."""
|
||||
import os
|
||||
import pytest
|
||||
from typing import Generator
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from unittest.mock import MagicMock
|
||||
from app.db.base import Base
|
||||
from app.database import get_db
|
||||
from app.main import app
|
||||
from app.utils.jwt import create_and_save_token, redis
|
||||
from app.crud import employees
|
||||
from app.utils.auth import get_password_hash
|
||||
from app.models.token import Token
|
||||
from app.models.employee import Employee
|
||||
from app.models.request import Request
|
||||
from app.schemas.employee import EmployeeCreate
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
# Используем SQLite для тестов
|
||||
from app.database import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.employee import Employee
|
||||
from app.utils.auth import get_password_hash
|
||||
from app.utils.jwt import create_access_token
|
||||
from app.core.config import settings
|
||||
|
||||
# Создаем тестовую базу данных в памяти
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
|
||||
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Создаем мок для Redis
|
||||
class RedisMock:
|
||||
class MockRedis:
|
||||
"""Мок для Redis."""
|
||||
def __init__(self):
|
||||
self.data = {}
|
||||
|
||||
def setex(self, name, time, value):
|
||||
self.data[name] = value
|
||||
def get(self, key):
|
||||
return self.data.get(key)
|
||||
|
||||
def set(self, key, value, ex=None):
|
||||
self.data[key] = value
|
||||
return True
|
||||
|
||||
def get(self, name):
|
||||
return self.data.get(name)
|
||||
|
||||
def delete(self, name):
|
||||
if name in self.data:
|
||||
del self.data[name]
|
||||
def delete(self, key):
|
||||
if key in self.data:
|
||||
del self.data[key]
|
||||
return True
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_redis(monkeypatch):
|
||||
redis_mock = RedisMock()
|
||||
monkeypatch.setattr("app.utils.jwt.redis", redis_mock)
|
||||
return redis_mock
|
||||
def exists(self, key):
|
||||
return key in self.data
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def test_db():
|
||||
# Удаляем все таблицы
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
# Создаем все таблицы заново
|
||||
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")
|
||||
def db() -> Generator:
|
||||
"""Фикстура для создания тестовой базы данных."""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Создаем сессию
|
||||
db = TestingSessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def test_employee(test_db):
|
||||
hashed_password = get_password_hash("testpass123")
|
||||
employee_data = EmployeeCreate(
|
||||
first_name="Test",
|
||||
last_name="User",
|
||||
department="IT",
|
||||
office="101",
|
||||
password="testpass123"
|
||||
def client(db: TestingSessionLocal, redis_mock) -> Generator:
|
||||
"""Фикстура для создания тестового клиента."""
|
||||
def override_get_db():
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
return TestClient(app)
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def test_employee(db: TestingSessionLocal) -> Employee:
|
||||
"""Фикстура для создания тестового сотрудника."""
|
||||
employee = Employee(
|
||||
email="test@example.com",
|
||||
full_name="Test Employee",
|
||||
hashed_password=get_password_hash("testpassword"),
|
||||
is_active=True,
|
||||
is_admin=False,
|
||||
department="IT"
|
||||
)
|
||||
employee = employees.create_employee(test_db, employee_data, hashed_password)
|
||||
db.add(employee)
|
||||
db.commit()
|
||||
db.refresh(employee)
|
||||
return employee
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def test_token(test_db, test_employee):
|
||||
token = create_and_save_token(test_employee.id, test_db)
|
||||
def test_admin(db: TestingSessionLocal) -> Employee:
|
||||
"""Фикстура для создания тестового администратора."""
|
||||
admin = Employee(
|
||||
email="admin@example.com",
|
||||
full_name="Test Admin",
|
||||
hashed_password=get_password_hash("adminpassword"),
|
||||
is_active=True,
|
||||
is_admin=True,
|
||||
department="Administration"
|
||||
)
|
||||
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(scope="function")
|
||||
def test_auth_header(test_token):
|
||||
return {"Authorization": f"Bearer {test_token}"}
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def admin_token(test_db):
|
||||
token = create_and_save_token(-1, test_db) # -1 для админа
|
||||
return token
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def admin_auth_header(admin_token):
|
||||
return {"Authorization": f"Bearer {admin_token}"}
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def test_employee_id(test_employee):
|
||||
return test_employee.id
|
||||
|
||||
# Переопределяем зависимость для получения БД
|
||||
def override_get_db():
|
||||
db = TestingSessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
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
|
||||
@@ -1,98 +1,80 @@
|
||||
"""Authentication tests."""
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session
|
||||
from app.main import app
|
||||
from app.crud import employees
|
||||
from app.utils.auth import verify_password, get_password_hash
|
||||
from app.schemas.employee import EmployeeCreate
|
||||
from app.models.employee import Employee
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
def test_login_success(test_db: Session):
|
||||
# Создаем тестового сотрудника
|
||||
hashed_password = get_password_hash("testpass123")
|
||||
employee_data = EmployeeCreate(
|
||||
first_name="Test",
|
||||
last_name="User",
|
||||
department="IT",
|
||||
office="101",
|
||||
password="testpass123"
|
||||
)
|
||||
employee = employees.create_employee(test_db, employee_data, hashed_password)
|
||||
|
||||
def test_login_employee_success(client: TestClient, test_employee: Employee):
|
||||
"""Тест успешной авторизации сотрудника."""
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
data={
|
||||
"username": "User",
|
||||
"password": "testpass123"
|
||||
}
|
||||
data={"username": test_employee.email, "password": "testpassword"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "access_token" in response.json()
|
||||
assert "token_type" in response.json()
|
||||
assert response.json()["token_type"] == "bearer"
|
||||
|
||||
def test_login_wrong_password(test_db: Session):
|
||||
# Создаем тестового сотрудника
|
||||
hashed_password = get_password_hash("testpass123")
|
||||
employee_data = EmployeeCreate(
|
||||
first_name="Test",
|
||||
last_name="User",
|
||||
department="IT",
|
||||
office="101",
|
||||
password="testpass123"
|
||||
)
|
||||
employees.create_employee(test_db, employee_data, hashed_password)
|
||||
|
||||
def test_login_employee_wrong_password(client: TestClient, test_employee: Employee):
|
||||
"""Тест авторизации сотрудника с неверным паролем."""
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
data={
|
||||
"username": "User",
|
||||
"password": "wrongpass"
|
||||
}
|
||||
data={"username": test_employee.email, "password": "wrongpassword"}
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert "detail" in response.json()
|
||||
assert response.json()["detail"] == "Incorrect username or password"
|
||||
|
||||
def test_login_nonexistent_user(test_db: Session):
|
||||
def test_login_employee_wrong_username(client: TestClient):
|
||||
"""Тест авторизации с несуществующим пользователем."""
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
data={
|
||||
"username": "NonExistent",
|
||||
"password": "testpass123"
|
||||
}
|
||||
data={"username": "nonexistent@example.com", "password": "testpassword"}
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert "detail" in response.json()
|
||||
assert response.json()["detail"] == "Incorrect username or password"
|
||||
|
||||
def test_admin_login_success():
|
||||
def test_login_admin_success(client: TestClient, test_admin: Employee):
|
||||
"""Тест успешной авторизации администратора."""
|
||||
response = client.post(
|
||||
"/api/auth/admin/login",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
data={
|
||||
"username": "admin",
|
||||
"password": "admin123"
|
||||
}
|
||||
data={"username": test_admin.email, "password": "adminpassword"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "access_token" in response.json()
|
||||
assert "token_type" in response.json()
|
||||
assert response.json()["token_type"] == "bearer"
|
||||
|
||||
def test_admin_login_wrong_password():
|
||||
def test_login_admin_wrong_password(client: TestClient, test_admin: Employee):
|
||||
"""Тест авторизации администратора с неверным паролем."""
|
||||
response = client.post(
|
||||
"/api/auth/admin/login",
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
data={
|
||||
"username": "admin",
|
||||
"password": "wrongpass"
|
||||
}
|
||||
data={"username": test_admin.email, "password": "wrongpassword"}
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert "detail" in response.json()
|
||||
assert response.json()["detail"] == "Incorrect username or password"
|
||||
|
||||
def test_protected_route_with_valid_token(client: TestClient, employee_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест доступа к защищенному маршруту с валидным токеном."""
|
||||
response = client.get(
|
||||
"/api/employees/me",
|
||||
headers={"Authorization": f"Bearer {employee_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
|
||||
def test_protected_route_without_token(client: TestClient):
|
||||
"""Тест доступа к защищенному маршруту без токена."""
|
||||
response = client.get("/api/employees/me")
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Not authenticated"
|
||||
|
||||
def test_protected_route_with_invalid_token(client: TestClient):
|
||||
"""Тест доступа к защищенному маршруту с недействительным токеном."""
|
||||
response = client.get(
|
||||
"/api/employees/me",
|
||||
headers={"Authorization": "Bearer invalid_token"}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Could not validate credentials"
|
||||
@@ -1,117 +1,135 @@
|
||||
"""Employee tests."""
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session
|
||||
from app.main import app
|
||||
from app.crud import employees
|
||||
from app.utils.auth import get_password_hash
|
||||
from app.schemas.employee import EmployeeCreate
|
||||
from app.models.employee import Employee
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
def test_create_employee(test_db: Session, admin_auth_header):
|
||||
"""Test creating a new employee"""
|
||||
employee_data = {
|
||||
"first_name": "John",
|
||||
"last_name": "Doe",
|
||||
"department": "IT",
|
||||
"office": "B205",
|
||||
"password": "test123"
|
||||
}
|
||||
|
||||
def test_create_employee(client: TestClient, admin_token: str, db: Session):
|
||||
"""Тест создания сотрудника."""
|
||||
response = client.post(
|
||||
"/api/employees/",
|
||||
json=employee_data,
|
||||
headers=admin_auth_header
|
||||
"/api/employees",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
json={
|
||||
"email": "new@example.com",
|
||||
"password": "newpassword",
|
||||
"full_name": "New Employee",
|
||||
"department": "IT",
|
||||
"is_active": True,
|
||||
"is_admin": False
|
||||
}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["email"] == "new@example.com"
|
||||
assert data["full_name"] == "New Employee"
|
||||
assert data["department"] == "IT"
|
||||
assert "id" in data
|
||||
|
||||
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
|
||||
}
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Not authenticated"
|
||||
|
||||
def test_get_employees(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения списка сотрудников."""
|
||||
response = client.get(
|
||||
"/api/employees",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["first_name"] == employee_data["first_name"]
|
||||
assert data["last_name"] == employee_data["last_name"]
|
||||
assert data["department"] == employee_data["department"]
|
||||
assert data["office"] == employee_data["office"]
|
||||
assert "password" not in data
|
||||
assert isinstance(data, list)
|
||||
assert len(data) > 0
|
||||
assert "email" in data[0]
|
||||
assert "full_name" in data[0]
|
||||
assert "department" in data[0]
|
||||
|
||||
def test_get_employees(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test getting list of employees"""
|
||||
response = client.get("/api/employees/", headers=admin_auth_header)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) >= 1
|
||||
assert data[0]["first_name"] == test_employee.first_name
|
||||
assert data[0]["last_name"] == test_employee.last_name
|
||||
assert data[0]["department"] == test_employee.department
|
||||
assert data[0]["office"] == test_employee.office
|
||||
assert "password" not in data[0]
|
||||
|
||||
def test_create_employee_unauthorized(test_db: Session):
|
||||
"""Test creating employee without authorization"""
|
||||
employee_data = {
|
||||
"first_name": "John",
|
||||
"last_name": "Doe",
|
||||
"department": "IT",
|
||||
"office": "B205",
|
||||
"password": "test123"
|
||||
}
|
||||
response = client.post("/api/employees/", json=employee_data)
|
||||
assert response.status_code == 401 # Unauthorized
|
||||
|
||||
def test_get_employees_unauthorized(test_db: Session):
|
||||
"""Test getting employees list without authorization"""
|
||||
response = client.get("/api/employees/")
|
||||
assert response.status_code == 401 # Unauthorized
|
||||
|
||||
def test_get_employee_by_id(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test getting employee by ID"""
|
||||
def test_get_employee_by_id(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения сотрудника по ID."""
|
||||
response = client.get(
|
||||
f"/api/employees/{test_employee.id}",
|
||||
headers=admin_auth_header
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["first_name"] == test_employee.first_name
|
||||
assert data["last_name"] == test_employee.last_name
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
assert data["department"] == test_employee.department
|
||||
assert data["office"] == test_employee.office
|
||||
assert "password" not in data
|
||||
|
||||
def test_update_employee(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test updating employee data"""
|
||||
update_data = {
|
||||
"first_name": "Updated",
|
||||
"last_name": "Name",
|
||||
"department": "HR",
|
||||
"office": "B202"
|
||||
}
|
||||
|
||||
def test_get_nonexistent_employee(client: TestClient, admin_token: str):
|
||||
"""Тест получения несуществующего сотрудника."""
|
||||
response = client.get(
|
||||
"/api/employees/999",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 404
|
||||
assert response.json()["detail"] == "Employee not found"
|
||||
|
||||
def test_update_employee(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест обновления данных сотрудника."""
|
||||
response = client.put(
|
||||
f"/api/employees/{test_employee.id}",
|
||||
json=update_data,
|
||||
headers=admin_auth_header
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
json={
|
||||
"email": "updated@example.com",
|
||||
"full_name": "Updated Employee",
|
||||
"department": "HR",
|
||||
"is_active": True,
|
||||
"is_admin": False
|
||||
}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["first_name"] == update_data["first_name"]
|
||||
assert data["last_name"] == update_data["last_name"]
|
||||
assert data["department"] == update_data["department"]
|
||||
assert data["office"] == update_data["office"]
|
||||
assert "password" not in data
|
||||
assert data["email"] == "updated@example.com"
|
||||
assert data["full_name"] == "Updated Employee"
|
||||
assert data["department"] == "HR"
|
||||
|
||||
def test_delete_employee(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test deleting employee"""
|
||||
def test_delete_employee(client: TestClient, admin_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест удаления сотрудника."""
|
||||
response = client.delete(
|
||||
f"/api/employees/{test_employee.id}",
|
||||
headers=admin_auth_header
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
# Verify employee is deleted
|
||||
get_response = client.get(
|
||||
f"/api/employees/{test_employee.id}",
|
||||
headers=admin_auth_header
|
||||
data = response.json()
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
assert data["department"] == test_employee.department
|
||||
|
||||
def test_employee_me(client: TestClient, employee_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест получения информации о текущем сотруднике."""
|
||||
response = client.get(
|
||||
"/api/employees/me",
|
||||
headers={"Authorization": f"Bearer {employee_token}"}
|
||||
)
|
||||
assert get_response.status_code == 404
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["full_name"] == test_employee.full_name
|
||||
assert data["department"] == test_employee.department
|
||||
|
||||
def test_update_me(client: TestClient, employee_token: str, test_employee: Employee, db: Session):
|
||||
"""Тест обновления информации о текущем сотруднике."""
|
||||
response = client.put(
|
||||
"/api/employees/me",
|
||||
headers={"Authorization": f"Bearer {employee_token}"},
|
||||
json={
|
||||
"full_name": "Updated Name",
|
||||
"department": "Support"
|
||||
}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["full_name"] == "Updated Name"
|
||||
assert data["email"] == test_employee.email
|
||||
assert data["department"] == "Support"
|
||||
@@ -1,164 +1,168 @@
|
||||
"""Request tests."""
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session
|
||||
from app.main import app
|
||||
from app.models.request import RequestStatus, RequestPriority
|
||||
from app.crud import requests
|
||||
from app.schemas.request import RequestCreate
|
||||
from app.models.employee import Employee
|
||||
from app.models.request import Request
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
def test_create_request(test_db: Session, test_employee, test_auth_header):
|
||||
"""Test creating a new request"""
|
||||
request_data = {
|
||||
"department": "IT",
|
||||
"request_type": "hardware",
|
||||
"description": "This is a test request",
|
||||
"priority": RequestPriority.MEDIUM.value
|
||||
}
|
||||
|
||||
def test_create_request(client: TestClient, employee_token: str, db: Session):
|
||||
"""Тест создания заявки."""
|
||||
response = client.post(
|
||||
"/api/requests/",
|
||||
json=request_data,
|
||||
headers=test_auth_header
|
||||
"/api/requests",
|
||||
headers={"Authorization": f"Bearer {employee_token}"},
|
||||
json={
|
||||
"request_type": "support",
|
||||
"description": "Test Description",
|
||||
"priority": "medium"
|
||||
}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["department"] == request_data["department"]
|
||||
assert data["description"] == request_data["description"]
|
||||
assert data["priority"] == request_data["priority"]
|
||||
assert data["status"] == RequestStatus.NEW.value
|
||||
assert "employee_id" in data
|
||||
assert data["request_type"] == "support"
|
||||
assert data["description"] == "Test Description"
|
||||
assert data["priority"] == "medium"
|
||||
assert data["status"] == "new"
|
||||
assert "id" in data
|
||||
|
||||
def test_get_employee_requests(test_db: Session, test_employee, test_auth_header):
|
||||
"""Test getting employee's requests"""
|
||||
# Создаем тестовую заявку
|
||||
request_data = RequestCreate(
|
||||
department="IT",
|
||||
request_type="hardware",
|
||||
description="This is a test request",
|
||||
priority=RequestPriority.MEDIUM.value
|
||||
def test_create_request_unauthorized(client: TestClient):
|
||||
"""Тест создания заявки без авторизации."""
|
||||
response = client.post(
|
||||
"/api/requests",
|
||||
json={
|
||||
"request_type": "support",
|
||||
"description": "Test Description",
|
||||
"priority": "medium"
|
||||
}
|
||||
)
|
||||
test_request = requests.create_request(test_db, request_data, test_employee.id)
|
||||
|
||||
response = client.get("/api/requests/my", headers=test_auth_header)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]["department"] == test_request.department
|
||||
assert data[0]["description"] == test_request.description
|
||||
assert data[0]["priority"] == test_request.priority
|
||||
assert data[0]["status"] == test_request.status
|
||||
assert data[0]["employee_id"] == test_request.employee_id
|
||||
assert response.status_code == 401
|
||||
assert response.json()["detail"] == "Not authenticated"
|
||||
|
||||
def test_update_request_status(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test updating request status"""
|
||||
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_data = RequestCreate(
|
||||
department="IT",
|
||||
request_type="hardware",
|
||||
description="This is a test request",
|
||||
priority=RequestPriority.MEDIUM.value
|
||||
request = Request(
|
||||
request_type="support",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
employee_id=test_employee.id
|
||||
)
|
||||
test_request = requests.create_request(test_db, request_data, test_employee.id)
|
||||
|
||||
update_data = {"status": RequestStatus.IN_PROGRESS.value}
|
||||
response = client.patch(
|
||||
f"/api/requests/{test_request.id}/status",
|
||||
json=update_data,
|
||||
headers=admin_auth_header
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == RequestStatus.IN_PROGRESS.value
|
||||
db.add(request)
|
||||
db.commit()
|
||||
|
||||
def test_get_all_requests_admin(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test getting all requests as admin"""
|
||||
# Создаем тестовую заявку
|
||||
request_data = RequestCreate(
|
||||
department="IT",
|
||||
request_type="hardware",
|
||||
description="This is a test request",
|
||||
priority=RequestPriority.MEDIUM.value
|
||||
)
|
||||
test_request = requests.create_request(test_db, request_data, test_employee.id)
|
||||
|
||||
response = client.get("/api/requests/admin", headers=admin_auth_header)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]["department"] == test_request.department
|
||||
|
||||
def test_get_requests_by_status(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test filtering requests by status"""
|
||||
# Создаем тестовую заявку
|
||||
request_data = RequestCreate(
|
||||
department="IT",
|
||||
request_type="hardware",
|
||||
description="This is a test request",
|
||||
priority=RequestPriority.MEDIUM.value
|
||||
)
|
||||
test_request = requests.create_request(test_db, request_data, test_employee.id)
|
||||
|
||||
response = client.get(
|
||||
f"/api/requests/admin?status={RequestStatus.NEW.value}",
|
||||
headers=admin_auth_header
|
||||
"/api/requests/my",
|
||||
headers={"Authorization": f"Bearer {employee_token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]["status"] == RequestStatus.NEW.value
|
||||
assert isinstance(data, list)
|
||||
assert len(data) > 0
|
||||
assert data[0]["request_type"] == "support"
|
||||
assert data[0]["description"] == "Test Description"
|
||||
|
||||
def test_get_request_statistics(test_db: Session, test_employee, admin_auth_header):
|
||||
"""Test getting request statistics"""
|
||||
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",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
employee_id=test_employee.id
|
||||
)
|
||||
db.add(request)
|
||||
db.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/requests/admin",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert len(data) > 0
|
||||
assert data[0]["request_type"] == "support"
|
||||
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",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
)
|
||||
db.add(request)
|
||||
db.commit()
|
||||
|
||||
response = client.patch(
|
||||
f"/api/requests/{request.id}/status",
|
||||
headers={"Authorization": f"Bearer {admin_token}"},
|
||||
json={"status": "in_progress"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "in_progress"
|
||||
|
||||
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_data = [
|
||||
RequestCreate(
|
||||
department="IT",
|
||||
request_type="hardware",
|
||||
description="Test request 1",
|
||||
priority=RequestPriority.HIGH.value
|
||||
requests = [
|
||||
Request(
|
||||
request_type="support",
|
||||
description="Test Description",
|
||||
priority="medium",
|
||||
status="new",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
),
|
||||
RequestCreate(
|
||||
department="IT",
|
||||
request_type="software",
|
||||
description="Test request 2",
|
||||
priority=RequestPriority.MEDIUM.value
|
||||
Request(
|
||||
request_type="support",
|
||||
description="Test Description",
|
||||
priority="high",
|
||||
status="in_progress",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
),
|
||||
Request(
|
||||
request_type="support",
|
||||
description="Test Description",
|
||||
priority="low",
|
||||
status="completed",
|
||||
employee_id=test_employee.id,
|
||||
department=test_employee.department
|
||||
)
|
||||
]
|
||||
|
||||
for data in requests_data:
|
||||
requests.create_request(test_db, data, test_employee.id)
|
||||
|
||||
response = client.get("/api/requests/statistics", headers=admin_auth_header)
|
||||
|
||||
for req in requests:
|
||||
db.add(req)
|
||||
db.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/statistics",
|
||||
headers={"Authorization": f"Bearer {admin_token}"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "total" in data
|
||||
assert "by_status" in data
|
||||
assert data["total"] == 2
|
||||
assert data["by_status"][RequestStatus.NEW.value] == 2
|
||||
assert data["by_status"][RequestStatus.IN_PROGRESS.value] == 0
|
||||
assert data["by_status"][RequestStatus.COMPLETED.value] == 0
|
||||
assert data["by_status"][RequestStatus.REJECTED.value] == 0
|
||||
|
||||
def test_create_request_unauthorized(test_db: Session):
|
||||
"""Test creating request without authorization"""
|
||||
request_data = {
|
||||
"department": "IT",
|
||||
"request_type": "hardware",
|
||||
"description": "This is a test request",
|
||||
"priority": RequestPriority.MEDIUM.value
|
||||
}
|
||||
response = client.post("/api/requests/", json=request_data)
|
||||
assert response.status_code == 401
|
||||
|
||||
def test_get_requests_unauthorized(test_db: Session):
|
||||
"""Test getting requests without authorization"""
|
||||
response = client.get("/api/requests/my")
|
||||
assert response.status_code == 401
|
||||
assert data["total"] >= 3
|
||||
1
backend/tests/test_statistics.py
Normal file
1
backend/tests/test_statistics.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
Reference in New Issue
Block a user