""" 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.""" # Create project project = Project(name="Test Project") session.add(project) session.flush() # Create customer customer = Customer(name="Test Customer") session.add(customer) session.flush() # Commit to ensure IDs are available session.commit() # Create System system = System(name="Test System", project_id=project.id, customer_id=customer.id) session.add(system) session.flush() # Create Module camera_module = Module(name="Camera") session.add(camera_module) session.flush() # Create Resource resource = Resource( project_id=project.id, module_id=camera_module.id, quantity=100, invoice_number="INV-001" ) 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" ) # Allocation created assert allocation is not None assert allocation.quantity == 30 assert allocation.resource_id == data['resource'].id assert allocation.system_id == data['system'].id # SystemModule created/updated 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 # Remaining balance = 70 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) # First allocation allocation1 = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=30, module_name="Camera" ) # Create second system 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() # Second allocation allocation2 = service.allocate_resource( resource_id=data['resource'].id, system_id=system2.id, quantity=20, module_name="Camera" ) # Two allocations created assert allocation1 is not None assert allocation2 is not None assert allocation1.quantity == 30 assert allocation2.quantity == 20 # Remaining = 50 allocated = session.query(func.sum(ResourceAllocation.quantity)).filter( ResourceAllocation.resource_id == data['resource'].id ).scalar() assert remaining == 50 def test_allocate_to_guardian(self, common_setup, session): """Allocation to Guardian""" data = common_setup service = ResourceAllocationService(session) # Create Guardian guardian = Guardian(name="Guardian 1", system_id=data['system'].id) session.add(guardian) session.flush() # Create Core module core_module = Module(name="Core") session.add(core_module) session.flush() # Create SystemModule for Core (automatically created when Guardian created) core_sm = SystemModule( system_id=data['system'].id, guardian_id=guardian.id, module_id=core_module.id, quantity=1 ) session.add(core_sm) session.commit() # Allocate to Guardian 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 # SystemModule with Guardian updated 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) # Allocate to Common 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 # SystemModule Common created 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) # Create second system 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() # Allocate 10 to System 1 alloc1 = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=10, module_name="Camera" ) # Allocate 20 to System 2 alloc2 = service.allocate_resource( resource_id=data['resource'].id, system_id=system2.id, quantity=20, module_name="Camera" ) # Allocate 5 to System 1 Common alloc3 = service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=5, guardian_id=None, module_name="Camera" ) # Three separate allocations assert alloc1.id != alloc2.id != alloc3.id assert alloc1.quantity == 10 assert alloc2.quantity == 20 assert alloc3.quantity == 5 # Remaining = 65 allocated = session.query(func.sum(ResourceAllocation.quantity)).filter( ResourceAllocation.resource_id == data['resource'].id ).scalar() assert remaining == 65 # Provenance preserved - each allocation is separate record 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) # Allocate all but 1 service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=99, module_name="Camera" ) # Try to allocate more than remaining with pytest.raises(InsufficientBalanceError): service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=2, # Only 1 remaining module_name="Camera" ) # Database unchanged - only 99 allocated total_allocated = from sqlalchemy import func session.query(func.sum(ResourceAllocation.quantity)).filter( ResourceAllocation.resource_id == data['resource'].id ).scalar() or 0 total_allocated = allocated assert total_allocated == 99 def test_allocate_zero_quantity(self, common_setup, session): """quantity = 0 → error""" data = common_setup service = ResourceAllocationService(session) with pytest.raises(ValidationError) as exc_info: service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=0, module_name="Camera" ) assert "greater than 0" in str(exc_info.value) # No allocation created 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) as exc_info: service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=-5, module_name="Camera" ) assert "greater than 0" in str(exc_info.value) # No allocation created 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) # Create different system and guardian customer2 = Customer(name="Test Customer 2") session.add(customer2) system2 = System(name="System 2", project_id=data['project'].id, customer_id=customer2.id) session.add(system2) session.flush() guardian2 = Guardian(name="Guardian 2", system_id=system2.id) session.add(guardian2) session.flush() # Try to allocate to guardian from different system with pytest.raises(InvalidGuardianError) as exc_info: service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=10, guardian_id=guardian2.id, module_name="Camera" ) assert "belongs to System" in str(exc_info.value) # No allocation created 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) # Create different project project2 = Project(name="Project 2") session.add(project2) session.flush() customer2 = Customer(name="Customer 2") session.add(customer2) system2 = System(name="System 2", project_id=project2.id, customer_id=customer2.id) session.add(system2) session.flush() # Try to allocate resource from Project 1 to System in Project 2 with pytest.raises(ProjectMismatchError) as exc_info: service.allocate_resource( resource_id=data['resource'].id, system_id=system2.id, quantity=10, module_name="Camera" ) assert "belongs to Project" in str(exc_info.value) # No allocation created assert session.query(ResourceAllocation).count() == 0 def test_core_to_common(self, common_setup, session): """Core → Common → error""" data = common_setup service = ResourceAllocationService(session) # Create Core module core_module = Module(name="Core") session.add(core_module) session.flush() # Try to allocate Core to Common with pytest.raises(CoreInCommonError) as exc_info: service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=1, guardian_id=None, module_name="Core" ) assert "Common part" in str(exc_info.value) # No allocation created 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) # Create Guardian guardian = Guardian(name="Guardian 1", system_id=data['system'].id) session.add(guardian) session.flush() # Create Core module core_module = Module(name="Core") session.add(core_module) session.flush() # Create first Core (automatically created when Guardian created) core1 = SystemModule( system_id=data['system'].id, guardian_id=guardian.id, module_id=core_module.id, quantity=1 ) session.add(core1) session.commit() # Try to allocate second Core with pytest.raises(CoreAlreadyExistsError) as exc_info: service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=1, guardian_id=guardian.id, module_name="Core" ) assert "already has Core" in str(exc_info.value) # Core quantity remains 1 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) # Allocate 50 first 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 to allocate more than remaining (should fail and rollback) try: service.allocate_resource( resource_id=data['resource'].id, system_id=data['system'].id, quantity=60, # Only 50 remaining, this will fail module_name="Camera" ) except InsufficientBalanceError: pass # Expected # No changes after failed allocation 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""" import sqlite3 # This test verifies the limitation try: session.execute("SELECT quantity FROM resources WHERE id = 1 FOR UPDATE") assert False, "SQLite should not support FOR UPDATE" except Exception: pass # Expected - SQLite doesn't support FOR UPDATE # Service uses retry logic instead of row-level locking service = ResourceAllocationService(session) # Allocate once service.allocate_resource( resource_id=common_setup['resource'].id, system_id=common_setup['system'].id, quantity=10, module_name="Camera" ) # Remaining = 90 remaining = service._calculate_remaining(common_setup['resource'].id) assert remaining == 90 if __name__ == '__main__': pytest.main([__file__, '-v'])