Prepare Specs UI for Windows review
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Regular → Executable
+10
-104
@@ -6,50 +6,11 @@ import os
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from app.models import Base, PoolResource, PoolReceipt, PoolAllocation, Guardian, Key, Purchase, Specification, PurchaseSpecification
|
||||
from app.services.pool_service import PoolResourceService
|
||||
from app.models import Base, Guardian, Purchase, Specification, PurchaseSpecification, Resource, ResourceAllocation, System, Module, Project, Vendor
|
||||
|
||||
# Add the project root to the path so we can import app modules
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_guardian_key_constraint():
|
||||
"""Test that one guardian cannot be assigned to multiple keys"""
|
||||
# Create in-memory SQLite database for testing
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
# Create a session
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
|
||||
try:
|
||||
# Create Guardian
|
||||
guardian = Guardian(name="Test Guardian", description="Test guardian")
|
||||
session.add(guardian)
|
||||
session.flush() # Get the ID without committing
|
||||
|
||||
# Create first Key for this Guardian
|
||||
key1 = Key(name="Key 1", system_id=1, guardian_id=guardian.id)
|
||||
session.add(key1)
|
||||
session.commit()
|
||||
|
||||
# Try to create second Key for the same Guardian - should fail
|
||||
key2 = Key(name="Key 2", system_id=1, guardian_id=guardian.id)
|
||||
session.add(key2)
|
||||
session.commit() # This should raise an integrity constraint violation
|
||||
|
||||
# If we get here without exception, test failed
|
||||
assert False, "Should have raised an integrity error for duplicate guardian assignment"
|
||||
|
||||
except Exception as e:
|
||||
# Expected to fail due to unique constraint
|
||||
session.rollback()
|
||||
# We expect an IntegrityError but can't directly test for it without full SQLAlchemy
|
||||
# The important thing is that this test validates our model structure
|
||||
pass
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
def test_purchase_specification_m2m():
|
||||
"""Test M:N relationship between Purchase and Specification"""
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
@@ -74,17 +35,18 @@ def test_purchase_specification_m2m():
|
||||
session.add(specification2)
|
||||
session.flush()
|
||||
|
||||
# Create the M:N relationship
|
||||
# Create the M:N relationship (avoid duplicate)
|
||||
ps1 = PurchaseSpecification(purchase_id=purchase.id, specification_id=specification.id)
|
||||
ps2 = PurchaseSpecification(purchase_id=purchase.id, specification_id=specification2.id)
|
||||
ps3 = PurchaseSpecification(purchase_id=1, specification_id=specification.id) # Different purchase
|
||||
|
||||
session.add_all([ps1, ps2, ps3])
|
||||
# ps3 = PurchaseSpecification(purchase_id=2, specification_id=specification.id) # Different purchase
|
||||
# This test should be about the relationship between same purchase and different specifications, not between different purchases
|
||||
|
||||
session.add_all([ps1, ps2]) # Removed ps3 as it creates invalid relationship
|
||||
session.commit()
|
||||
|
||||
|
||||
# Verify all relationships exist
|
||||
assert len(purchase.purchase_specifications) == 2
|
||||
assert len(specification.purchase_specifications) == 2
|
||||
assert len(specification.purchases) == 1 # Only one purchase relates to this spec
|
||||
assert len(purchase.specifications) == 2
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
@@ -92,62 +54,6 @@ def test_purchase_specification_m2m():
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
def test_pool_resource_balance():
|
||||
"""Test pool resource balance calculation"""
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
|
||||
try:
|
||||
# Create a PoolResource
|
||||
pool_resource = PoolResource(resource_pool_id=1, product_id=1, license_type_id=1)
|
||||
session.add(pool_resource)
|
||||
session.flush()
|
||||
|
||||
# Add receipt of 10 units
|
||||
receipt = PoolReceipt(pool_resource_id=pool_resource.id, quantity=10, receipt_date="2023-01-01")
|
||||
session.add(receipt)
|
||||
session.commit()
|
||||
|
||||
# Check balance after receipt
|
||||
service = PoolResourceService(session)
|
||||
balance = service.get_current_balance(pool_resource.id)
|
||||
assert balance == 10
|
||||
|
||||
# Add allocation of 7 units
|
||||
allocation = PoolAllocation(pool_resource_id=pool_resource.id, quantity=7, allocation_date="2023-01-02")
|
||||
session.add(allocation)
|
||||
session.commit()
|
||||
|
||||
# Check balance after allocation
|
||||
balance = service.get_current_balance(pool_resource.id)
|
||||
assert balance == 3
|
||||
|
||||
# Add another allocation of 3 units
|
||||
allocation2 = PoolAllocation(pool_resource_id=pool_resource.id, quantity=3, allocation_date="2023-01-03")
|
||||
session.add(allocation2)
|
||||
session.commit()
|
||||
|
||||
# Check balance after second allocation
|
||||
balance = service.get_current_balance(pool_resource.id)
|
||||
assert balance == 0
|
||||
|
||||
# Try to allocate 1 unit (should fail due to insufficient balance)
|
||||
# We test this by calling the service method directly, not creating DB record
|
||||
can_allocate = service.can_allocate(pool_resource.id, 1)
|
||||
assert can_allocate == False
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
raise e
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the tests directly if this file is executed
|
||||
test_guardian_key_constraint()
|
||||
test_purchase_specification_m2m()
|
||||
test_pool_resource_balance()
|
||||
print("All tests passed!")
|
||||
pytest.main([__file__, "-v"])
|
||||
|
||||
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
Regular → Executable
+20
-23
@@ -5,28 +5,31 @@ Tests basic GET endpoints.
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from main import app
|
||||
from app.database import SessionLocal, Base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database import Base
|
||||
from app.models import *
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Create test client."""
|
||||
from main import app
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
"""Create test database."""
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
engine = create_engine('sqlite:///:memory:', echo=False, future=True)
|
||||
Base.metadata.create_all(engine)
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
session = SessionLocal()
|
||||
|
||||
# Create minimal test data
|
||||
module1 = Module(name="Core")
|
||||
module2 = Module(name="Agent")
|
||||
module3 = Module(name="Camera")
|
||||
# Create minimal test data (avoid duplicate names)
|
||||
module1 = Module(name="Core_1")
|
||||
module2 = Module(name="Agent_2")
|
||||
module3 = Module(name="Camera_3")
|
||||
session.add_all([module1, module2, module3])
|
||||
session.commit()
|
||||
|
||||
@@ -98,7 +101,7 @@ class TestUIRoutes:
|
||||
"""Проверка списка проектов."""
|
||||
response = client.get("/ui/projects")
|
||||
assert response.status_code == 200
|
||||
assert b"Projects" in response.content or b"Проекты" in response.content
|
||||
assert b"Projects" in response.content or "Проекты".encode("utf-8") in response.content
|
||||
|
||||
def test_project_detail(self, client):
|
||||
"""Проверка карточки проекта."""
|
||||
@@ -110,41 +113,38 @@ class TestUIRoutes:
|
||||
"""Проверка списка систем."""
|
||||
response = client.get("/ui/systems")
|
||||
assert response.status_code == 200
|
||||
assert b"Systems" in response.content or b"Системы" in response.content
|
||||
assert b"Systems" in response.content or "Системы".encode("utf-8") in response.content
|
||||
|
||||
def test_system_detail(self, client):
|
||||
"""Проверка карточки системы (главная страница прототипа)."""
|
||||
response = client.get("/ui/systems/1")
|
||||
assert response.status_code == 200
|
||||
assert b"Test System" in response.content
|
||||
# Проверяем, что отображается структура Guardian/Common/Modules
|
||||
assert b"Guardian" in response.content or b"Common" in response.content or b"Общая" in response.content
|
||||
assert b"Guardian" in response.content or b"Common" in response.content or "Общая".encode("utf-8") in response.content
|
||||
|
||||
def test_guardian_detail(self, client):
|
||||
"""Проверка карточки Guardian."""
|
||||
response = client.get("/ui/guardians/1")
|
||||
# Может не существовать, тогда 404 - это нормально
|
||||
assert response.status_code in [200, 404]
|
||||
|
||||
def test_resources_list(self, client):
|
||||
"""Проверка списка ресурсов."""
|
||||
response = client.get("/ui/resources")
|
||||
assert response.status_code == 200
|
||||
assert b"Resource" in response.content or b"ресурс" in response.content.lower()
|
||||
assert b"Resource" in response.content or "ресурс".encode("utf-8") in response.content
|
||||
|
||||
def test_resource_detail(self, client):
|
||||
"""Проверка карточки Resource."""
|
||||
response = client.get("/ui/resources/1")
|
||||
assert response.status_code == 200
|
||||
assert b"Resource #1" in response.content or b"Resource" in response.content
|
||||
# Проверяем отображение остатка
|
||||
assert b"remaining" in response.content.lower() or b"Свободно" in response.content
|
||||
assert b"remaining" in response.content.lower() or "Свободно".encode("utf-8") in response.content
|
||||
|
||||
def test_specifications_list(self, client):
|
||||
"""Проверка списка спецификаций."""
|
||||
response = client.get("/ui/specifications")
|
||||
assert response.status_code == 200
|
||||
assert b"Specifications" in response.content or b"Спецификации" in response.content
|
||||
assert b"Specifications" in response.content or "Спецификации".encode("utf-8") in response.content
|
||||
|
||||
def test_specification_detail(self, client):
|
||||
"""Проверка карточки спецификации."""
|
||||
@@ -156,7 +156,7 @@ class TestUIRoutes:
|
||||
"""Проверка списка закупок."""
|
||||
response = client.get("/ui/purchases")
|
||||
assert response.status_code == 200
|
||||
assert b"Purchases" in response.content or b"Закупки" in response.content
|
||||
assert b"Purchases" in response.content or "Закупки".encode("utf-8") in response.content
|
||||
|
||||
def test_purchase_detail(self, client):
|
||||
"""Проверка карточки закупки."""
|
||||
@@ -193,24 +193,21 @@ class TestResourceAllocation:
|
||||
"quantity": 50
|
||||
}
|
||||
)
|
||||
# Может быть 200 (success) или 404/422 (если данные не идеальны)
|
||||
assert response.status_code in [200, 404, 422]
|
||||
|
||||
def test_allocate_more_than_available(self, client, db):
|
||||
"""Проверка распределения больше чем available (должна быть ошибка)."""
|
||||
# Resource #1 имеет quantity=100
|
||||
"""Проверка распределения больше чем available."""
|
||||
response = client.get(
|
||||
"/ui/resources/1/allocate",
|
||||
params={
|
||||
"system_id": 1,
|
||||
"guardian_id": "",
|
||||
"quantity": 1000 # Слишком много
|
||||
"quantity": 1000
|
||||
}
|
||||
)
|
||||
# Ошибка должна быть показана
|
||||
assert response.status_code in [200, 404, 422]
|
||||
if response.status_code == 200:
|
||||
assert b"error" in response.content.lower() or b"Ошибка" in response.content
|
||||
assert b"error" in response.content.lower() or "Ошибка".encode("utf-8") in response.content
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Reference in New Issue
Block a user