""" Resource Allocation Service - tests Tests for resource allocation operations with real database. Covers positive and negative scenarios from task 004. """ import pytest from sqlalchemy import create_engine, func from sqlalchemy.orm import sessionmaker from app.models import Base, Resource, ResourceAllocation, SystemModule, System, Guardian, Module, Project, Customer from app.services.resource_allocation_service import ( ResourceAllocationService, InsufficientBalanceError, CoreInCommonError, InvalidGuardianError, ProjectMismatchError, ValidationError, GuardianNotFoundError, SystemNotFoundError, ResourceNotFoundError, CoreAlreadyExistsError ) @pytest.fixture def engine(): """Create in-memory SQLite database for testing.""" engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(engine) return engine @pytest.fixture def session(engine): """Create database session.""" Session = sessionmaker(bind=engine) return Session() @pytest.fixture def db(session, engine): """Full test database with engine and session.""" return {'engine': engine, 'session': session} @pytest.fixture def common_setup(session): """Setup common test data.""" project = Project(name="Test Project") session.add(project) session.flush() customer = Customer(name="Test Customer") session.add(customer) session.flush() session.commit() system = System(name="Test System", project_id=project.id, customer_id=customer.id) session.add(system) session.flush() camera_module = Module(name="Camera") session.add(camera_module) session.flush() resource = Resource( project_id=project.id, module_id=camera_module.id, quantity=100, invoice_number="INV-001", invoice_id=1 # Для SQLite fixture, invoice_id не будет существовать ) session.add(resource) session.flush() session.commit() return { 'project': project, 'customer': customer, 'system': system, 'module': camera_module, 'resource': resource } class TestPositiveScenarios: """Test positive allocation scenarios""" def test_allocate_from_resource_100_to_system_30(self, common_setup, session): """Resource 100 → allocate 30 to System A""" data = common_setup service = ResourceAllocationService(session) allocation = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=30, module_name="Camera" ) assert allocation is not None assert allocation.quantity == 30 system_module = session.query(SystemModule).filter( SystemModule.system_id == data['system'].id, SystemModule.module_id == data['module'].id ).first() assert system_module is not None assert system_module.quantity == 30 allocated = session.query(func.sum(ResourceAllocation.quantity)).filter( ResourceAllocation.resource_id == data['resource'].id ).scalar() or 0 remaining = data['resource'].quantity - allocated assert remaining == 70 def test_allocate_from_same_resource_to_different_system(self, common_setup, session): """From same Resource → allocate 20 to System B""" data = common_setup service = ResourceAllocationService(session) allocation1 = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=30, module_name="Camera" ) customer2 = Customer(name="Test Customer 2") session.add(customer2) session.commit() system2 = System(name="System 2", project_id=data['project'].id, customer_id=customer2.id) session.add(system2) session.commit() allocation2 = service.allocate_resource( resource_id=data['resource'].id, system_id=system2.id, quantity=20, module_name="Camera" ) assert allocation1 is not None assert allocation2 is not None allocated = session.query(func.sum(ResourceAllocation.quantity)).filter( ResourceAllocation.resource_id == data['resource'].id ).scalar() or 0 remaining = data['resource'].quantity - allocated assert remaining == 50 def test_allocate_to_guardian(self, common_setup, session): """Allocation to Guardian""" data = common_setup service = ResourceAllocationService(session) # Camera module already exists from common_setup # Verify it exists camera_module = session.query(Module).filter( Module.name == "Camera" ).first() assert camera_module is not None guardian = Guardian(name="Guardian 1", system_id=data['system'].id) session.add(guardian) session.flush() allocation = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=25, guardian_id=guardian.id, module_name="Camera" ) assert allocation is not None assert allocation.guardian_id == guardian.id # Verify SystemModule was created with Guardian and Camera module guardian_sm = session.query(SystemModule).filter( SystemModule.system_id == data['system'].id, SystemModule.guardian_id == guardian.id, SystemModule.module_id == data['module'].id ).first() assert guardian_sm is not None assert guardian_sm.quantity == 25 def test_allocate_to_common(self, common_setup, session): """Allocation to Common part (guardian_id=NULL)""" data = common_setup service = ResourceAllocationService(session) allocation = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=40, guardian_id=None, module_name="Camera" ) assert allocation is not None assert allocation.guardian_id is None common_sm = session.query(SystemModule).filter( SystemModule.system_id == data['system'].id, SystemModule.guardian_id.is_(None), SystemModule.module_id == data['module'].id ).first() assert common_sm is not None assert common_sm.quantity == 40 def test_multiple_allocations_from_same_resource(self, common_setup, session): """Several allocations from one Resource - provenance tracked separately""" data = common_setup service = ResourceAllocationService(session) customer2 = Customer(name="Test Customer 2") session.add(customer2) session.commit() system2 = System(name="System 2", project_id=data['project'].id, customer_id=customer2.id) session.add(system2) session.commit() alloc1 = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=10, module_name="Camera" ) alloc2 = service.allocate_resource( resource_id=data['resource'].id, system_id=system2.id, quantity=20, module_name="Camera" ) alloc3 = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=5, guardian_id=None, module_name="Camera" ) assert alloc1.id != alloc2.id != alloc3.id allocated = session.query(func.sum(ResourceAllocation.quantity)).filter( ResourceAllocation.resource_id == data['resource'].id ).scalar() or 0 remaining = data['resource'].quantity - allocated assert remaining == 65 class TestNegativeScenarios: """Test negative allocation scenarios""" def test_allocate_more_than_available(self, common_setup, session): """allocate more than remaining balance → error""" data = common_setup service = ResourceAllocationService(session) service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=99, module_name="Camera" ) with pytest.raises(InsufficientBalanceError): service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=2, module_name="Camera" ) allocated = session.query(func.sum(ResourceAllocation.quantity)).filter( ResourceAllocation.resource_id == data['resource'].id ).scalar() or 0 assert allocated == 99 def test_allocate_zero_quantity(self, common_setup, session): """quantity = 0 → error""" data = common_setup service = ResourceAllocationService(session) with pytest.raises(ValidationError): service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=0, module_name="Camera" ) assert session.query(ResourceAllocation).count() == 0 def test_allocate_negative_quantity(self, common_setup, session): """quantity < 0 → error""" data = common_setup service = ResourceAllocationService(session) with pytest.raises(ValidationError): service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=-5, module_name="Camera" ) assert session.query(ResourceAllocation).count() == 0 def test_guardian_from_different_system(self, common_setup, session): """Guardian from different System → error""" data = common_setup service = ResourceAllocationService(session) customer2 = Customer(name="Test Customer 2") session.add(customer2) session.commit() system2 = System(name="System 2", project_id=data['project'].id, customer_id=customer2.id) session.add(system2) session.commit() guardian2 = Guardian(name="Guardian 2", system_id=system2.id) session.add(guardian2) session.flush() with pytest.raises(InvalidGuardianError): service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=10, guardian_id=guardian2.id, module_name="Camera" ) assert session.query(ResourceAllocation).count() == 0 def test_resource_different_project(self, common_setup, session): """Resource from one Project → System from another Project → error""" data = common_setup service = ResourceAllocationService(session) project2 = Project(name="Project 2") session.add(project2) session.flush() customer2 = Customer(name="Customer 2") session.add(customer2) session.commit() system2 = System(name="System 2", project_id=project2.id, customer_id=customer2.id) session.add(system2) session.commit() with pytest.raises(ProjectMismatchError): service.allocate_resource( resource_id=data['resource'].id, system_id=system2.id, quantity=10, module_name="Camera" ) assert session.query(ResourceAllocation).count() == 0 def test_core_to_common(self, common_setup, session): """Core → Common → error""" data = common_setup service = ResourceAllocationService(session) core_module = Module(name="Core") session.add(core_module) session.flush() with pytest.raises(CoreInCommonError): service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=1, guardian_id=None, module_name="Core" ) assert session.query(ResourceAllocation).count() == 0 def test_second_core_to_same_guardian(self, common_setup, session): """Second Core to same Guardian → error""" data = common_setup service = ResourceAllocationService(session) guardian = Guardian(name="Guardian 1", system_id=data['system'].id) session.add(guardian) session.flush() core_module = Module(name="Core") session.add(core_module) session.flush() core1 = SystemModule( system_id=data['system'].id, guardian_id=guardian.id, module_id=core_module.id, quantity=1 ) session.add(core1) session.commit() with pytest.raises(CoreAlreadyExistsError): service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=1, guardian_id=guardian.id, module_name="Core" ) core = session.query(SystemModule).filter( SystemModule.guardian_id == guardian.id, SystemModule.module_id == core_module.id ).first() assert core is not None assert core.quantity == 1 def test_nonexistent_resource(self, common_setup, session): """Nonexistent Resource → error""" service = ResourceAllocationService(session) with pytest.raises(ResourceNotFoundError): service.allocate_resource( resource_id=99999, system_id=1, quantity=10, module_name="Camera" ) def test_nonexistent_system(self, common_setup, session): """Nonexistent System → error""" data = common_setup service = ResourceAllocationService(session) with pytest.raises(SystemNotFoundError): service.allocate_resource( resource_id=data['resource'].id, system_id=99999, quantity=10, module_name="Camera" ) def test_transaction_rollback_on_error(self, common_setup, session): """On error after check, transaction rolled back completely""" data = common_setup service = ResourceAllocationService(session) service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=50, module_name="Camera" ) initial_allocations = session.query(ResourceAllocation).count() initial_system_modules = session.query(SystemModule).count() try: service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=60, module_name="Camera" ) except InsufficientBalanceError: pass final_allocations = session.query(ResourceAllocation).count() final_system_modules = session.query(SystemModule).count() assert final_allocations == initial_allocations assert final_system_modules == initial_system_modules class TestConcurrencyScenarios: """Test concurrent allocation scenarios (conceptual - SQLite doesn't support row-level locking)""" def test_sqlite_no_row_locking(self, common_setup, session): """Verify SQLite doesn't support SELECT FOR UPDATE""" try: session.execute("SELECT quantity FROM resources WHERE id = 1 FOR UPDATE") assert False except Exception: pass service = ResourceAllocationService(session) service.allocate_resource( resource_id=common_setup['resource'].id, system_id=common_setup['system'].id, quantity=10, module_name="Camera" ) remaining = service._calculate_remaining(common_setup['resource'].id) assert remaining == 90 if __name__ == '__main__': pytest.main([__file__, '-v'])