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

Добавления тестов бекенда

This commit is contained in:
MoonTestUse1
2025-01-02 04:30:51 +06:00
parent 7729acaa09
commit 01677cf5df
16 changed files with 903 additions and 328 deletions

View File

@@ -1 +1 @@
"""Test package initialization"""
# Пустой файл для инициализации пакета тестов

View File

@@ -1,72 +1,35 @@
"""Test configuration and fixtures"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
import logging
from fastapi.testclient import TestClient
from app.database import Base, get_db
from app.main import app
# Configure logging for tests
logging.basicConfig(level=logging.INFO)
# Create test database
SQLALCHEMY_TEST_DATABASE_URL = "sqlite:///:memory:"
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_TEST_DATABASE_URL,
connect_args={"check_same_thread": False},
poolclass=StaticPool,
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def override_get_db():
"""Override database dependency"""
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
@pytest.fixture(scope="function")
def test_db():
"""Create test database"""
@pytest.fixture
def db_session():
Base.metadata.create_all(bind=engine)
db = TestingSessionLocal()
session = TestingSessionLocal()
try:
yield db
yield session
finally:
db.close()
session.close()
Base.metadata.drop_all(bind=engine)
@pytest.fixture(scope="function")
def client(test_db):
"""Create test client"""
@pytest.fixture
def client(db_session):
def override_get_db():
try:
yield db_session
finally:
db_session.close()
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as test_client:
yield test_client
app.dependency_overrides.clear()
@pytest.fixture
def test_employee():
"""Test employee data"""
return {
"first_name": "Test",
"last_name": "User",
"department": "general",
"office": "101",
"password": "testpass123"
}
@pytest.fixture
def test_request():
"""Test request data"""
return {
"employee_id": 1,
"department": "general",
"request_type": "hardware",
"priority": "medium",
"description": "Test request"
}
yield TestClient(app)
del app.dependency_overrides[get_db]

View File

@@ -1,47 +1,70 @@
"""Authentication endpoint tests"""
import pytest
from app.crud import employees
from app.models.employee import EmployeeCreate
from app.models.employee import Employee
from app.utils.auth import get_password_hash
def test_login_success(client, test_db, test_employee):
"""Test successful login"""
def test_admin_login(client):
"""Test admin login endpoint"""
response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert response.status_code == 200
assert "access_token" in response.json()
def test_admin_login_invalid_credentials(client):
"""Test admin login with invalid credentials"""
response = client.post("/api/auth/admin", json={
"username": "wrong",
"password": "wrong"
})
assert response.status_code == 401
assert response.json()["detail"] == "Invalid credentials"
def test_employee_login(client, db_session):
"""Test employee login endpoint"""
# Create test employee
employee_data = EmployeeCreate(**test_employee)
employees.create_employee(test_db, employee_data)
# Attempt login
response = client.post(
"/api/auth/login",
json={
"lastName": test_employee["last_name"],
"password": test_employee["password"]
}
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
# Try to login
response = client.post("/api/auth/login", json={
"last_name": "User",
"password": "test123"
})
assert response.status_code == 200
data = response.json()
assert data["lastName"] == test_employee["last_name"]
assert "password" not in data
assert data["first_name"] == "Test"
assert data["last_name"] == "User"
assert data["department"] == "IT"
assert data["office"] == "A101"
assert "access_token" in data
def test_login_invalid_credentials(client):
"""Test login with invalid credentials"""
response = client.post(
"/api/auth/login",
json={
"lastName": "NonExistent",
"password": "wrongpass"
}
def test_employee_login_invalid_credentials(client, db_session):
"""Test employee login with invalid credentials"""
# Create test employee
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
# Try to login with wrong password
response = client.post("/api/auth/login", json={
"last_name": "User",
"password": "wrong"
})
assert response.status_code == 401
assert response.json()["detail"] == "Неверные учетные данные"
def test_login_missing_fields(client):
"""Test login with missing fields"""
response = client.post(
"/api/auth/login",
json={"lastName": "Test"}
)
assert response.status_code == 400
assert "Необходимо указать" in response.json()["detail"]
assert response.json()["detail"] == "Неверный пароль"

View File

@@ -1,68 +1,202 @@
"""Employee management endpoint tests"""
import pytest
from app.models.employee import EmployeeCreate
from app.models.employee import Employee
from app.utils.auth import get_password_hash
def test_create_employee(client, test_employee):
"""Test employee creation"""
response = client.post(
"/api/employees",
json={
"first_name": test_employee["first_name"],
"last_name": test_employee["last_name"],
"department": test_employee["department"],
"office": test_employee["office"],
"password": test_employee["password"]
}
)
def test_create_employee(client):
"""Test creating a new employee"""
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Create employee
employee_data = {
"first_name": "John",
"last_name": "Doe",
"department": "IT",
"office": "B205",
"password": "test123"
}
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.post("/api/employees/", json=employee_data, headers=headers)
assert response.status_code == 200
data = response.json()
assert data["firstName"] == test_employee["first_name"]
assert data["lastName"] == test_employee["last_name"]
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
def test_create_employee_duplicate(client, test_employee):
"""Test creating duplicate employee"""
# Create first employee
client.post(
"/api/employees",
json={
"first_name": test_employee["first_name"],
"last_name": test_employee["last_name"],
"department": test_employee["department"],
"office": test_employee["office"],
"password": test_employee["password"]
}
def test_get_employees(client, db_session):
"""Test getting list of employees"""
# Create test employee
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
# Try to create duplicate
response = client.post(
"/api/employees",
json={
"first_name": test_employee["first_name"],
"last_name": test_employee["last_name"],
"department": test_employee["department"],
"office": test_employee["office"],
"password": test_employee["password"]
}
)
# Сохраняем значения для проверки
expected_first_name = employee.first_name
expected_last_name = employee.last_name
expected_department = employee.department
expected_office = employee.office
assert response.status_code == 400
assert "уже существует" in response.json()["detail"]
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Get employees list
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.get("/api/employees/", headers=headers)
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["first_name"] == expected_first_name
assert data[0]["last_name"] == expected_last_name
assert data[0]["department"] == expected_department
assert data[0]["office"] == expected_office
assert "password" not in data[0]
def test_create_employee_invalid_data(client):
"""Test creating employee with invalid data"""
invalid_employee = {
"first_name": "", # Empty name
"last_name": "Test",
"department": "invalid", # Invalid department
"office": "101",
"password": "test"
def test_create_employee_unauthorized(client):
"""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=invalid_employee
response = client.post("/api/employees/", json=employee_data)
assert response.status_code == 401
def test_get_employees_unauthorized(client):
"""Test getting employees list without authorization"""
response = client.get("/api/employees/")
assert response.status_code == 401
def test_get_employee_by_id(client, db_session):
"""Test getting employee by ID"""
# Create test employee
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
assert response.status_code == 422
employee_id = employee.id
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Get employee
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.get(f"/api/employees/{employee_id}", headers=headers)
assert response.status_code == 200
data = response.json()
assert data["first_name"] == "Test"
assert data["last_name"] == "User"
assert data["department"] == "IT"
assert data["office"] == "A101"
assert "password" not in data
def test_update_employee(client, db_session):
"""Test updating employee data"""
# Create test employee
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
employee_id = employee.id
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Update employee
update_data = {
"first_name": "Updated",
"last_name": "Name",
"department": "HR",
"office": "B202"
}
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.put(f"/api/employees/{employee_id}", json=update_data, headers=headers)
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
def test_delete_employee(client, db_session):
"""Test deleting employee"""
# Create test employee
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
employee_id = employee.id
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Delete employee
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.delete(f"/api/employees/{employee_id}", headers=headers)
assert response.status_code == 200
# Verify employee is deleted
get_response = client.get(f"/api/employees/{employee_id}", headers=headers)
assert get_response.status_code == 404

View File

@@ -1,75 +1,333 @@
"""Request management endpoint tests"""
import pytest
from unittest.mock import patch
from app.models.request import Request, RequestStatus, RequestPriority
from app.models.employee import Employee
from app.utils.auth import get_password_hash
from datetime import datetime, timedelta
def test_create_request(client, test_db, test_employee, test_request):
"""Test request creation"""
# Create test employee first
employee_response = client.post(
"/api/employees",
json={
"first_name": test_employee["first_name"],
"last_name": test_employee["last_name"],
"department": test_employee["department"],
"office": test_employee["office"],
"password": test_employee["password"]
}
def test_create_request(client, db_session):
"""Test creating a new request"""
# Create test employee
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
assert employee_response.status_code == 200
employee_data = employee_response.json()
test_request["employee_id"] = employee_data["id"]
db_session.add(employee)
db_session.commit()
employee_id = employee.id
# Login as employee
login_response = client.post("/api/auth/login", json={
"last_name": "User",
"password": "test123"
})
assert login_response.status_code == 200
token = login_response.json()["access_token"]
# Create request
with patch('app.bot.notifications.send_notification'): # Mock notification
response = client.post(
"/api/requests",
json=test_request
)
request_data = {
"title": "Test Request",
"description": "This is a test request",
"priority": RequestPriority.MEDIUM.value
}
headers = {"Authorization": f"Bearer {token}"}
response = client.post("/api/requests/", json=request_data, headers=headers)
assert response.status_code == 200
data = response.json()
assert data["employee_id"] == test_request["employee_id"]
assert data["status"] == "new"
assert data["title"] == request_data["title"]
assert data["description"] == request_data["description"]
assert data["priority"] == request_data["priority"]
assert data["status"] == RequestStatus.NEW.value
assert data["employee_id"] == employee_id
def test_create_request_invalid_employee(client, test_request):
"""Test creating request with invalid employee ID"""
test_request["employee_id"] = 999 # Non-existent ID
response = client.post(
"/api/requests",
json=test_request
def test_get_employee_requests(client, db_session):
"""Test getting employee's requests"""
# Create test employee
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
assert response.status_code == 404
assert "не найден" in response.json()["detail"]
db_session.add(employee)
db_session.commit()
employee_id = employee.id
def test_create_request_invalid_priority(client, test_db, test_employee):
"""Test creating request with invalid priority"""
# Create test employee first
employee_response = client.post(
"/api/employees",
json={
"first_name": test_employee["first_name"],
"last_name": test_employee["last_name"],
"department": test_employee["department"],
"office": test_employee["office"],
"password": test_employee["password"]
}
# Create test request and save its data
request = Request(
title="Test Request",
description="This is a test request",
priority=RequestPriority.MEDIUM.value,
status=RequestStatus.NEW.value,
employee_id=employee_id
)
assert employee_response.status_code == 200
employee_data = employee_response.json()
db_session.add(request)
db_session.commit()
invalid_request = {
"employee_id": employee_data["id"],
"department": "general",
"request_type": "hardware",
"priority": "invalid", # Invalid priority
"description": "Test request"
# Сохраняем данные для сравнения
expected_data = {
"title": request.title,
"description": request.description,
"priority": request.priority,
"status": request.status,
"employee_id": request.employee_id
}
# Login as employee
login_response = client.post("/api/auth/login", json={
"last_name": "User",
"password": "test123"
})
assert login_response.status_code == 200
token = login_response.json()["access_token"]
# Get requests
headers = {"Authorization": f"Bearer {token}"}
response = client.get("/api/requests/my", headers=headers)
response = client.post(
"/api/requests",
json=invalid_request
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["title"] == expected_data["title"]
assert data[0]["description"] == expected_data["description"]
assert data[0]["priority"] == expected_data["priority"]
assert data[0]["status"] == expected_data["status"]
assert data[0]["employee_id"] == expected_data["employee_id"]
def test_update_request_status(client, db_session):
"""Test updating request status"""
# Create test employee and request
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
employee_id = employee.id
request = Request(
title="Test Request",
description="This is a test request",
priority=RequestPriority.MEDIUM.value,
status=RequestStatus.NEW.value,
employee_id=employee_id
)
db_session.add(request)
db_session.commit()
request_id = request.id
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Update request status
update_data = {"status": RequestStatus.IN_PROGRESS.value}
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.patch(f"/api/requests/{request_id}/status", json=update_data, headers=headers)
assert response.status_code == 200
data = response.json()
assert data["status"] == RequestStatus.IN_PROGRESS.value
def test_get_all_requests_admin(client, db_session):
"""Test getting all requests as admin"""
# Create test employees and requests
hashed_password = get_password_hash("test123")
employee1 = Employee(
first_name="Test1",
last_name="User1",
department="IT",
office="A101",
password=hashed_password
)
employee2 = Employee(
first_name="Test2",
last_name="User2",
department="HR",
office="B202",
password=hashed_password
)
db_session.add_all([employee1, employee2])
db_session.commit()
request1 = Request(
title="Test Request 1",
description="This is test request 1",
priority=RequestPriority.HIGH.value,
status=RequestStatus.NEW.value,
employee_id=employee1.id
)
request2 = Request(
title="Test Request 2",
description="This is test request 2",
priority=RequestPriority.MEDIUM.value,
status=RequestStatus.IN_PROGRESS.value,
employee_id=employee2.id
)
db_session.add_all([request1, request2])
db_session.commit()
assert response.status_code == 422
# Сохраняем данные для сравнения
expected_titles = {request1.title, request2.title}
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Get all requests
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.get("/api/requests/admin", headers=headers)
assert response.status_code == 200
data = response.json()
assert len(data) == 2
received_titles = {r["title"] for r in data}
assert received_titles == expected_titles
def test_get_requests_by_status(client, db_session):
"""Test filtering requests by status"""
# Create test employee and requests
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
request1 = Request(
title="New Request",
description="This is a new request",
priority=RequestPriority.HIGH.value,
status=RequestStatus.NEW.value,
employee_id=employee.id
)
request2 = Request(
title="In Progress Request",
description="This is an in progress request",
priority=RequestPriority.MEDIUM.value,
status=RequestStatus.IN_PROGRESS.value,
employee_id=employee.id
)
db_session.add_all([request1, request2])
db_session.commit()
# Сохраняем данные для сравнения
expected_data = {
"title": request1.title,
"status": request1.status
}
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Get requests filtered by status
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.get(f"/api/requests/admin?status={RequestStatus.NEW.value}", headers=headers)
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["title"] == expected_data["title"]
assert data[0]["status"] == expected_data["status"]
def test_get_request_statistics(client, db_session):
"""Test getting request statistics"""
# Create test employee and requests
hashed_password = get_password_hash("test123")
employee = Employee(
first_name="Test",
last_name="User",
department="IT",
office="A101",
password=hashed_password
)
db_session.add(employee)
db_session.commit()
# Create requests with different statuses
requests_data = [
{"status": RequestStatus.NEW.value, "priority": RequestPriority.HIGH.value},
{"status": RequestStatus.IN_PROGRESS.value, "priority": RequestPriority.MEDIUM.value},
{"status": RequestStatus.COMPLETED.value, "priority": RequestPriority.LOW.value},
{"status": RequestStatus.NEW.value, "priority": RequestPriority.HIGH.value}
]
for i, data in enumerate(requests_data):
request = Request(
title=f"Request {i+1}",
description=f"This is request {i+1}",
priority=data["priority"],
status=data["status"],
employee_id=employee.id
)
db_session.add(request)
db_session.commit()
# Login as admin
admin_response = client.post("/api/auth/admin", json={
"username": "admin",
"password": "admin123"
})
assert admin_response.status_code == 200
admin_token = admin_response.json()["access_token"]
# Get statistics
headers = {"Authorization": f"Bearer {admin_token}"}
response = client.get("/api/requests/statistics", headers=headers)
assert response.status_code == 200
data = response.json()
# Проверяем статистику
assert "total_requests" in data
assert data["total_requests"] == 4
assert "by_status" in data
assert data["by_status"]["new"] == 2
assert data["by_status"]["in_progress"] == 1
assert data["by_status"]["completed"] == 1
assert "by_priority" in data
assert data["by_priority"]["high"] == 2
assert data["by_priority"]["medium"] == 1
assert data["by_priority"]["low"] == 1
def test_create_request_unauthorized(client):
"""Test creating request without authorization"""
request_data = {
"title": "Test Request",
"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(client):
"""Test getting requests without authorization"""
response = client.get("/api/requests/my")
assert response.status_code == 401