"""Comprehensive Coverage Gap Closure Unit Tests for UP-AI v1.5 Statement Budget Enforcement (≥95.0%). Explicitly tests boundary conditions, validation failures, invariant checks, error handling branches, and unauthenticated/cross-tenant paths across Iterations 01-07 modules. """ from datetime import datetime, date, timedelta, timezone from decimal import Decimal import unittest import sys from pathlib import Path code_root = Path(__file__).resolve().parents[2] repo_root = Path(__file__).resolve().parents[3] if str(code_root) not in sys.path: sys.path.insert(0, str(code_root)) if str(repo_root) not in sys.path: sys.path.insert(0, str(repo_root)) # Iteration 01 & Auth from backend.app.auth import oidc from backend.app.auth.oidc import auth_service from backend.app.auth.session import session_manager from backend.app.api.auth import auth_controller from sandbox.identity_mock import mock_idp, TEST_PERSONAS # Iteration 02 & Tenancy from backend.app.db.session import storage from backend.app.models.tenant import ( Tenant, TenantMembership, validate_lifecycle_transition, PRD_BUSINESS_ROLES ) from backend.app.api.tenants import tenant_controller # Iteration 03 & Trading Desk / Inward from backend.app.models.market import MarketObservation, validate_market_observation from backend.app.api.market import market_controller from backend.app.models.procurement import ( ProcurementSauda, calculate_sauda_commercials ) from backend.app.api.procurement import procurement_controller from backend.app.models.receiving import ( InwardGateEntry, WeighbridgeSlip, GoodsReceiptNote, ) from backend.app.api.receiving import receiving_controller from backend.app.models.quality import ( InventoryLot, QualityInspection, calculate_quality_rebates ) from backend.app.api.quality import quality_controller # Iteration 04 & Logistics / Inventory / Sales from backend.app.models.inventory import ( StockLedgerEntry, StockAdjustment, StockTransfer, TRANSACTION_TYPES ) from backend.app.api.inventory import inventory_controller from backend.app.models.sales import ( CustomerSalesOrder, SalesOrderAllocation ) from backend.app.api.sales import sales_controller from backend.app.models.logistics import ( TransportVehicle, OutboundDispatch, OutwardWeighment, SalesCreditNote ) from backend.app.api.logistics import logistics_controller # Iteration 05 & Finance from backend.app.models.finance import ( CustomerPaymentReceipt, SupplierPayable, compute_customer_aging, CreditDispatchLock, compute_exposure_metrics ) from backend.app.api.finance import finance_controller, CUSTOMERS # Iteration 06 & Analytics / Alerts / Reporting from backend.app.api.analytics import analytics_controller # Iteration 07 & Master Data / Policies / Support from backend.app.models.master_data import ( Commodity, CommodityVariety, TradingCounterparty, Godown ) from backend.app.api.master_data import master_data_controller from backend.app.models.policy import ( TenantOperatingPolicy, check_policy_intervals_overlap ) from backend.app.api.policies import policy_controller from backend.app.models.support import PrivilegedSupportGrant from backend.app.api.support import support_controller # Sandboxes from sandbox.customer_credit_mock import CustomerCreditMock, CUSTOMERS as SANDBOX_CUSTOMERS from sandbox.notification_mock import notification_mock class TestCoverageGapClosure(unittest.TestCase): """Targeted tests closing AST statement coverage gaps to exceed UP-AI v1.5 budget (≥95%).""" def setUp(self): self.tenant_id = "tenant-alpha" session_manager.clear() # Pre-seed active tenant and memberships in core session storage storage.save_tenant( Tenant( tenant_id=self.tenant_id, business_name="Alpha Agro Trading", legal_identifier="23AAACA1234A1Z5", contact_email="admin@alpha.com", primary_mandi="Kota APMC", status="ACTIVE" ) ) storage.save_membership( TenantMembership( tenant_id=self.tenant_id, user_id="admin@alpha.com", email="admin@alpha.com", role="Tenant Administrator", status="ACTIVE" ) ) storage.save_membership( TenantMembership( tenant_id=self.tenant_id, user_id="buyer@alpha.com", email="buyer@alpha.com", role="Mandi Buyer", status="ACTIVE" ) ) storage.save_membership( TenantMembership( tenant_id=self.tenant_id, user_id="partner@alpha.com", email="partner@alpha.com", role="Partner / MD", status="ACTIVE" ) ) # Mint tokens for diverse personas self.sysadmin_token = mock_idp.mint_jwt( subject="sysadmin@platform.com", email="sysadmin@platform.com", name="System Admin", roles=["System Administrator"], tenant_id="platform" ) self.sysadmin_auth = f"Bearer {self.sysadmin_token}" self.admin_token = mock_idp.mint_jwt( subject="admin@alpha.com", email="admin@alpha.com", name="Admin User", roles=["Tenant Administrator"], tenant_id=self.tenant_id ) self.admin_auth = f"Bearer {self.admin_token}" self.buyer_token = mock_idp.mint_jwt( subject="buyer@alpha.com", email="buyer@alpha.com", name="Mandi Buyer", roles=["Mandi Buyer"], tenant_id=self.tenant_id ) self.buyer_auth = f"Bearer {self.buyer_token}" self.partner_token = mock_idp.mint_jwt( subject="partner@alpha.com", email="partner@alpha.com", name="Partner User", roles=["Partner / MD", "PARTNER"], tenant_id=self.tenant_id ) self.partner_auth = f"Bearer {self.partner_token}" # ========================================================================= # 1. OIDC Token Verification Branches # ========================================================================= def test_oidc_verification_fallback_branches(self): """Covers oidc.py fallback branches when USE_IDENTITY_MOCK is False.""" orig_mock = auth_service.settings.USE_IDENTITY_MOCK orig_jwt = getattr(oidc, "jwt", None) try: auth_service.settings.USE_IDENTITY_MOCK = False # Branch 1: jwt is None oidc.jwt = None payload = auth_service.verify_token(self.buyer_token) self.assertEqual(payload["email"], "buyer@alpha.com") # Branch 2: jwt is available import jwt oidc.jwt = jwt payload2 = auth_service.verify_token(self.buyer_token) self.assertEqual(payload2["email"], "buyer@alpha.com") finally: auth_service.settings.USE_IDENTITY_MOCK = orig_mock oidc.jwt = orig_jwt # ========================================================================= # 2. Tenancy Models and Controllers # ========================================================================= def test_tenants_api_and_model_validation(self): """Covers missing validation paths in tenants.py and tenant models.""" # Missing required fields in create_tenant res1 = tenant_controller.create_tenant(self.sysadmin_auth, { "legal_identifier": "L1", "contact_email": "e@a.com", "primary_mandi": "M1" }) self.assertEqual(res1["status_code"], 400) self.assertIn("business_name", res1["error"]) res2 = tenant_controller.create_tenant(self.sysadmin_auth, { "business_name": "B1", "legal_identifier": "L1", "primary_mandi": "M1" }) self.assertEqual(res2["status_code"], 400) self.assertIn("contact_email", res2["error"]) res3 = tenant_controller.create_tenant(self.sysadmin_auth, { "business_name": "B1", "legal_identifier": "L1", "contact_email": "e@a.com" }) self.assertEqual(res3["status_code"], 400) self.assertIn("primary_mandi", res3["error"]) # Non-admin access to membership endpoints res_roster = tenant_controller.list_memberships(self.buyer_auth, self.tenant_id) self.assertEqual(res_roster["status_code"], 403) res_add = tenant_controller.add_membership(self.buyer_auth, self.tenant_id, { "email": "x@x.com", "role": "Mandi Buyer" }) self.assertEqual(res_add["status_code"], 403) res_update_perm = tenant_controller.update_membership( self.buyer_auth, self.tenant_id, "mem-1", {"status": "REVOKED"} ) self.assertEqual(res_update_perm["status_code"], 403) res_update_ctx = tenant_controller.update_membership( self.admin_auth, self.tenant_id, "mem-1", {"status": "REVOKED"}, header_tenant_id="invalid-tenant-does-not-exist" ) self.assertEqual(res_update_ctx["status_code"], 403) # ========================================================================= # 3. Market Desk Models & Controller # ========================================================================= def test_market_desk_validation_and_controller(self): """Covers market.py invariants and market controller error paths.""" today = datetime.now(timezone.utc).date() # Closed market with negative arrival with self.assertRaises(ValueError): validate_market_observation( today, Decimal("-1.0"), Decimal("100"), Decimal("100"), Decimal("100"), is_market_closed=True ) # Open market missing rates with self.assertRaises(ValueError): validate_market_observation( today, Decimal("10.0"), None, Decimal("100"), Decimal("100"), is_market_closed=False ) # Min rate <= 0 with self.assertRaises(ValueError): validate_market_observation( today, Decimal("10.0"), Decimal("-1.0"), Decimal("100"), Decimal("100"), is_market_closed=False ) # Max rate < Min rate with self.assertRaises(ValueError): validate_market_observation( today, Decimal("10.0"), Decimal("200.0"), Decimal("100.0"), Decimal("150.0"), is_market_closed=False ) # Controller auth failures res_list = market_controller.list_observations(None, None) self.assertFalse(res_list.get("authenticated", True)) res_rates = market_controller.get_latest_rates(None, None, commodity_id="COMM-SOYBEAN") self.assertFalse(res_rates.get("authenticated", True)) # Controller validation error on record_observation res_record = market_controller.record_observation( self.admin_auth, self.tenant_id, { "mandi_id": "MANDI-01", "observation_date": today.isoformat(), "commodity_id": "COMM-SOYBEAN", "variety": "Yellow", "arrival_mt": -10.0 } ) self.assertEqual(res_record["status_code"], 422) # Context resolution error res_ctx = market_controller.record_observation( self.buyer_auth, "non-existent-tenant-xyz", {} ) self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 4. Procurement Contracts Models & Controller # ========================================================================= def test_procurement_validation_and_controller(self): """Covers procurement.py invariants and procurement controller error paths.""" today = datetime.now(timezone.utc).date() # Commercial calculations validation with self.assertRaises(ValueError): calculate_sauda_commercials( booked_quantity_mt=Decimal("-1.0"), trade_rate_per_qtl=Decimal("4500.00"), contract_date=today, credit_period_days=10 ) with self.assertRaises(ValueError): calculate_sauda_commercials( booked_quantity_mt=Decimal("10.0"), trade_rate_per_qtl=Decimal("-10.00"), contract_date=today, credit_period_days=10 ) with self.assertRaises(ValueError): calculate_sauda_commercials( booked_quantity_mt=Decimal("10.0"), trade_rate_per_qtl=Decimal("4500.00"), contract_date=today, credit_period_days=-5 ) # ProcurementSauda model receipt validation sauda = ProcurementSauda( tenant_id=self.tenant_id, sauda_number="SDA-TEST-001", contract_date=today, delivery_due_date=today + timedelta(days=7), supplier_id="SUPP-01", mandi_id="MANDI-01", commodity_id="COMM-SOYBEAN", variety="Yellow", trade_type="MANDI_PURCHASE", booked_quantity_mt=Decimal("50.0"), trade_rate_per_qtl=Decimal("4500.0") ) with self.assertRaises(ValueError): sauda.record_receipt(Decimal("-5.0")) # Pre-seed market observation to hit lines 131-133 in book_sauda procurement_controller.store.insert("market_observations", self.tenant_id, { "commodity_id": "COMM-WHEAT", "is_market_closed": False, "observation_date": today.isoformat(), "modal_rate": 2800.0 }) res_book = procurement_controller.book_sauda(self.admin_auth, self.tenant_id, { "contract_date": today.isoformat(), "delivery_due_date": (today + timedelta(days=5)).isoformat(), "supplier_id": "SUPP-01", "mandi_id": "MANDI-01", "commodity_id": "COMM-WHEAT", "variety": "Lokwan", "grade": "FAQ", "trade_type": "MANDI_PURCHASE", "booked_quantity_mt": 20.0, "trade_rate_per_qtl": 2850.0, "credit_period_days": 7 }) self.assertEqual(res_book["status_code"], 201) # Controller auth and resolution failures res_list = procurement_controller.list_saudas(None, None) self.assertFalse(res_list.get("authenticated", True)) res_get = procurement_controller.get_sauda(None, None, "s-1") self.assertFalse(res_get.get("authenticated", True)) res_ctx = procurement_controller.book_sauda(self.buyer_auth, "invalid-tenant", {}) self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 5. Inward Receiving Models & Controller # ========================================================================= def test_receiving_validation_and_controller(self): """Covers receiving.py invariants and controller edge cases.""" # Gate entry status transition validation ge = InwardGateEntry( tenant_id=self.tenant_id, gate_pass_number="GP-TEST-001", vehicle_number="MP09AB1234", eway_bill_number="123456789012", driver_name="Ramesh", driver_mobile="9876543210", sauda_id="sauda-1", supplier_invoice_no="INV-001", supplier_dispatch_weight_mt=Decimal("25.0"), supplier_dispatch_bags=250 ) with self.assertRaises(ValueError): ge.transition_status("INVALID_STATUS") # Weighbridge slip validations with self.assertRaises(ValueError): WeighbridgeSlip( tenant_id=self.tenant_id, slip_number="WB-001", gate_pass_id=ge.id, gross_weight_mt=Decimal("0.0") ) slip = WeighbridgeSlip( tenant_id=self.tenant_id, slip_number="WB-001", gate_pass_id=ge.id, gross_weight_mt=Decimal("25.0") ) with self.assertRaises(ValueError): slip.record_tare( tare_weight_mt=Decimal("25.0"), bag_packaging_type="JUTE_GUNNY_NEW", actual_bag_count=200, billed_weight_mt=Decimal("20.0") ) # GRN quantity validation with self.assertRaises(ValueError): GoodsReceiptNote( tenant_id=self.tenant_id, grn_number="GRN-001", weighment_slip_id=slip.id, sauda_id="s-1", godown_id="g-1", godown_stack_id="stk-1", accepted_quantity_mt=Decimal("0.0"), accepted_bags=0 ) # Controller auth failures self.assertFalse(receiving_controller.list_gate_entries(None, None).get("authenticated", True)) self.assertFalse(receiving_controller.create_weighment_gross(None, None, {}).get("authenticated", True)) self.assertFalse(receiving_controller.record_weighment_tare(None, None, "s-1", {}).get("authenticated", True)) self.assertFalse(receiving_controller.post_grn(None, None, {}).get("authenticated", True)) # Controller validation failures receiving_controller.store.insert("procurement_sauda", self.tenant_id, {"id": "s-1", "status": "ACTIVE"}) res_ge_val = receiving_controller.create_gate_entry(self.admin_auth, self.tenant_id, { "vehicle_number": "MP09AB1234", "eway_bill_number": "123456789012", "driver_name": "Ramesh", "driver_mobile": "9876543210", "sauda_id": "s-1", "supplier_dispatch_weight_mt": -1.0 }) self.assertEqual(res_ge_val["status_code"], 422) receiving_controller.store.insert("inward_gate_entries", self.tenant_id, ge.to_dict()) res_wb_val = receiving_controller.create_weighment_gross(self.admin_auth, self.tenant_id, { "gate_pass_id": ge.id, "gross_weight_mt": -1.0 }) self.assertEqual(res_wb_val["status_code"], 422) # Post GRN missing dependencies (gate entry not found, sauda not found) receiving_controller.store.insert("weighbridge_slips", self.tenant_id, { "id": "slip-missing-ge", "gate_pass_id": "nonexistent-ge", "gross_weight_mt": 25.0, "tare_weight_mt": 10.0, "final_net_weight_mt": 15.0, "actual_bag_count": 150 }) res_grn_ge = receiving_controller.post_grn(self.admin_auth, self.tenant_id, { "weighment_slip_id": "slip-missing-ge", "godown_id": "g-1", "godown_stack_id": "s-1" }) self.assertEqual(res_grn_ge["status_code"], 404) receiving_controller.store.insert("inward_gate_entries", self.tenant_id, { "id": "ge-missing-sauda", "sauda_id": "nonexistent-sauda", "supplier_dispatch_weight_mt": 15.0 }) receiving_controller.store.insert("weighbridge_slips", self.tenant_id, { "id": "slip-missing-sauda", "gate_pass_id": "ge-missing-sauda", "gross_weight_mt": 25.0, "tare_weight_mt": 10.0, "final_net_weight_mt": 15.0, "actual_bag_count": 150 }) res_grn_sda = receiving_controller.post_grn(self.admin_auth, self.tenant_id, { "weighment_slip_id": "slip-missing-sauda", "godown_id": "g-1", "godown_stack_id": "s-1" }) self.assertEqual(res_grn_sda["status_code"], 404) # Tare validation error in controller (line 291) receiving_controller.store.insert("weighbridge_slips", self.tenant_id, { "id": "slip-tare-val", "slip_number": "WS-VAL-1", "gate_pass_id": ge.id, "gross_weight_mt": 25.0 }) res_tare_val = receiving_controller.record_weighment_tare(self.admin_auth, self.tenant_id, "slip-tare-val", { "tare_weight_mt": 30.0, "actual_bag_count": 100 }) self.assertEqual(res_tare_val["status_code"], 422) # GRN validation error in controller (line 434) receiving_controller.store.insert("procurement_sauda", self.tenant_id, { "id": "s-val-grn", "status": "ACTIVE", "quantity_mt": 50.0, "fulfilled_quantity_mt": 0.0, "commodity_id": "COMM-SOYBEAN", "variety": "Yellow" }) receiving_controller.store.insert("inward_gate_entries", self.tenant_id, { "id": "ge-val-grn", "sauda_id": "s-val-grn", "supplier_dispatch_weight_mt": 25.0 }) receiving_controller.store.insert("weighbridge_slips", self.tenant_id, { "id": "slip-val-grn", "gate_pass_id": "ge-val-grn", "gross_weight_mt": 25.0, "tare_weight_mt": 10.0, "final_net_weight_mt": 0.0, "actual_bag_count": 0 }) res_grn_val = receiving_controller.post_grn(self.admin_auth, self.tenant_id, { "weighment_slip_id": "slip-val-grn", "godown_id": "g-1", "godown_stack_id": "s-1" }) self.assertEqual(res_grn_val["status_code"], 422) # Context error res_ctx = receiving_controller.create_gate_entry(self.buyer_auth, "invalid-tenant", {}) self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 6. Quality & Lot Control Models & Controller # ========================================================================= def test_quality_validation_and_controller(self): """Covers quality.py invariants and quality controller paths.""" # InventoryLot initial qty with self.assertRaises(ValueError): InventoryLot( tenant_id=self.tenant_id, lot_number="LOT-001", grn_id="grn-1", commodity_id="c-1", variety="v-1", godown_stack_id="stk-1", initial_quantity_mt=Decimal("0.0") ) lot = InventoryLot( tenant_id=self.tenant_id, lot_number="LOT-001", grn_id="grn-1", commodity_id="c-1", variety="v-1", godown_stack_id="stk-1", initial_quantity_mt=Decimal("20.0") ) # Invalid QC status with self.assertRaises(ValueError): lot.transition_qc_status("INVALID_QC") # Same status early return lot.transition_qc_status("QUALITY_HOLD") self.assertEqual(lot.qc_status, "QUALITY_HOLD") # Lot split exceeding balance lot.transition_qc_status("RELEASED") with self.assertRaises(ValueError): lot.split_lot([Decimal("50.0")]) # Quality inspection invalid decision with self.assertRaises(ValueError): QualityInspection( tenant_id=self.tenant_id, lot_id=lot.id, sample_code="SMP-001", inspector_email="inspector@alpha.com", lot_quantity_mt=Decimal("20.0"), trade_rate_per_qtl=Decimal("4500.0"), moisture_pct=Decimal("11.0"), foreign_matter_pct=Decimal("1.0"), decision="INVALID_DECISION" ) # Quality inspection rejected missing reason with self.assertRaises(ValueError): QualityInspection( tenant_id=self.tenant_id, lot_id=lot.id, sample_code="SMP-001", inspector_email="inspector@alpha.com", lot_quantity_mt=Decimal("20.0"), trade_rate_per_qtl=Decimal("4500.0"), moisture_pct=Decimal("11.0"), foreign_matter_pct=Decimal("1.0"), decision="REJECTED", rejection_reason=None ) # Controller auth failures self.assertFalse(quality_controller.execute_lot_decision(None, None, "l-1", {}).get("authenticated", True)) self.assertFalse(quality_controller.get_lot_lineage(None, None, "l-1").get("authenticated", True)) # Controller validation error quality_controller.store.insert("inventory_lots", self.tenant_id, lot.to_dict()) res_insp = quality_controller.record_inspection(self.admin_auth, self.tenant_id, { "lot_id": lot.id, "sample_code": "SMP-001", "lot_quantity_mt": 20.0, "trade_rate_per_qtl": 4500.0, "moisture_pct": -10.0, "foreign_matter_pct": 1.0, "decision": "RELEASED" }) self.assertEqual(res_insp["status_code"], 422) # Context error res_ctx = quality_controller.record_inspection(self.buyer_auth, "invalid-tenant", {}) self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 7. Inventory & Warehouse Management # ========================================================================= def test_inventory_validation_and_controller(self): """Covers inventory.py ledger/adjustment models and controller branches.""" # StockLedgerEntry other transaction type (lines 87-88) TRANSACTION_TYPES.add("OTHER_CUSTOM") try: sle = StockLedgerEntry( tenant_id=self.tenant_id, warehouse_id="WH-01", commodity_id="COMM-SOYBEAN", variety="Yellow", grade="FAQ", transaction_type="OTHER_CUSTOM", reference_id="ref-1", opening_mt=Decimal("10.0"), opening_bags=100, quantity_mt=Decimal("2.0"), bags=20 ) self.assertEqual(sle.closing_mt, Decimal("12.0")) finally: TRANSACTION_TYPES.discard("OTHER_CUSTOM") # StockAdjustment zero balance before adj = StockAdjustment( tenant_id=self.tenant_id, warehouse_id="WH-01", commodity_id="COMM-SOYBEAN", variety="Yellow", grade="FAQ", variance_mt=Decimal("5.0"), variance_bags=50, reason_code="Handling Spillage", balance_before_mt=Decimal("0.0"), balance_before_bags=0 ) self.assertEqual(adj.variance_pct, Decimal("100.00")) self.assertTrue(adj.partner_approval_required) # Partner approval of adjustment adj.approve_and_commit("partner-user-1") self.assertEqual(adj.status, "COMMITTED") self.assertEqual(adj.partner_approved_by, "partner-user-1") # Controller unauthenticated paths self.assertFalse(inventory_controller.get_ledger(None, None).get("authenticated", True)) self.assertFalse(inventory_controller.approve_adjustment(None, None, "adj-1").get("authenticated", True)) self.assertFalse(inventory_controller.get_capacity(None, None).get("authenticated", True)) self.assertFalse(inventory_controller.initiate_transfer(None, None, {}).get("authenticated", True)) self.assertFalse(inventory_controller.receive_transfer(None, None, "trf-1", {}).get("authenticated", True)) # Ledger filtering with non-matching params res_ledger = inventory_controller.get_ledger( self.buyer_auth, self.tenant_id, warehouse_id="NO_MATCH", commodity_id="NO_MATCH" ) self.assertEqual(res_ledger["status_code"], 200) # Adjustment auto-approval by Partner res_partner_adj = inventory_controller.record_adjustment( self.partner_auth, self.tenant_id, { "warehouse_id": "WH-01", "commodity_id": "COMM-SOYBEAN", "variety": "Yellow", "variance_mt": 10.0, "variance_bags": 100, "reason_code": "Handling Spillage", "balance_before_mt": 50.0, "balance_before_bags": 500 } ) self.assertEqual(res_partner_adj["status_code"], 201) self.assertEqual(res_partner_adj["adjustment"]["status"], "COMMITTED") # Transfer validation errors res_trf_err = inventory_controller.initiate_transfer(self.buyer_auth, self.tenant_id, { "dispatched_mt": -5.0 }) self.assertEqual(res_trf_err["status_code"], 400) res_recv_notfound = inventory_controller.receive_transfer( self.buyer_auth, self.tenant_id, "nonexistent-trf", { "received_mt": 10.0, "received_bags": 100 } ) self.assertEqual(res_recv_notfound["status_code"], 404) # Context error res_ctx = inventory_controller.get_ledger(self.buyer_auth, "invalid-tenant") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 8. Sales Contracts Models & Controller # ========================================================================= def test_sales_validation_and_controller(self): """Covers sales.py invariants and controller branches.""" order = CustomerSalesOrder( tenant_id=self.tenant_id, sales_order_number="SAL-001", customer_id="CUST-001", destination_city="Indore", customer_segment="Processor", commodity_id="COMM-SOYBEAN", variety="Yellow", contract_qty_mt=Decimal("20.0"), contract_rate_per_qtl=Decimal("5200.0"), payment_terms="30 Days", credit_exposure_ratio=Decimal("50.0") ) # Allocation transitions order.apply_allocation(Decimal("10.0")) self.assertEqual(order.status, "PARTIALLY_ALLOCATED") order.apply_allocation(Decimal("10.0")) self.assertEqual(order.status, "FULLY_ALLOCATED") # Exceeding allocation with self.assertRaises(ValueError): order.apply_allocation(Decimal("5.0")) # SalesOrderAllocation exceeding available unreserved with self.assertRaises(ValueError): SalesOrderAllocation( tenant_id=self.tenant_id, sales_order_id=order.id, lot_id="lot-1", warehouse_id="wh-1", allocated_qty_mt=Decimal("50.0"), allocated_bags=500, lot_qc_status="RELEASED", available_unreserved_mt=Decimal("20.0") ) # Controller auth failures self.assertFalse(sales_controller.get_sales_order(None, None, "o-1").get("authenticated", True)) self.assertFalse(sales_controller.list_sales_orders(None, None).get("authenticated", True)) self.assertFalse(sales_controller.allocate_lot(None, None, "o-1", {}).get("authenticated", True)) # Controller validation failures res_create_err = sales_controller.create_sales_order(self.buyer_auth, self.tenant_id, { "customer_id": "CUST-001", "destination_city": "Indore", "commodity_id": "COMM-SOYBEAN", "variety": "Yellow", "contract_qty_mt": "not-a-number", "contract_rate_per_qtl": 5000.0 }) self.assertEqual(res_create_err["status_code"], 400) # List filtering with non-matching customer and status res_list = sales_controller.list_sales_orders( self.buyer_auth, self.tenant_id, customer_id="NO_CUST", status="NO_STATUS" ) self.assertEqual(res_list["status_code"], 200) # Context error res_ctx = sales_controller.list_sales_orders(self.buyer_auth, "invalid-tenant") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 9. Logistics & Fleet Registry Models & Controller # ========================================================================= def test_logistics_validation_and_controller(self): """Covers logistics.py invariants and controller branches.""" # Vehicle invalid status with self.assertRaises(ValueError): TransportVehicle( tenant_id=self.tenant_id, reg_no="MP-09-HH-1111", make_model="Tata 1613", payload_capacity_mt=Decimal("15.0"), ownership_type="Own", transporter_name="Alpha Fleet", fitness_expiry="2027-12-31", status="InvalidStatus" ) # Vehicle On Route gating vehicle = TransportVehicle( tenant_id=self.tenant_id, reg_no="MP-09-HH-2222", make_model="Tata 1613", payload_capacity_mt=Decimal("15.0"), ownership_type="Own", transporter_name="Alpha Fleet", fitness_expiry="2027-12-31", status="Available" ) vehicle.status = "On Route" with self.assertRaises(ValueError): vehicle.assert_can_assign() # Outbound dispatch invalid status dispatch = OutboundDispatch( tenant_id=self.tenant_id, dispatch_number="DSP-001", sales_order_id="s-1", allocation_id="a-1", vehicle_id=vehicle.id, origin_warehouse_id="wh-1", destination_city="Indore" ) with self.assertRaises(ValueError): dispatch.transition_status("INVALID_STATUS") # Outward weighment bag and bilty invariants with self.assertRaises(ValueError): OutwardWeighment( tenant_id=self.tenant_id, dispatch_id=dispatch.id, tare_weight_kg=Decimal("8000.0"), gross_weight_kg=Decimal("25000.0"), allocated_mt=Decimal("17.0"), loaded_bags=0, transporter_bilty_no="BLT-1", eway_bill_no="EW-1" ) with self.assertRaises(ValueError): OutwardWeighment( tenant_id=self.tenant_id, dispatch_id=dispatch.id, tare_weight_kg=Decimal("8000.0"), gross_weight_kg=Decimal("25000.0"), allocated_mt=Decimal("17.0"), loaded_bags=170, transporter_bilty_no="", eway_bill_no="EW-1" ) # Credit note sign-off cn = SalesCreditNote( tenant_id=self.tenant_id, credit_note_number="CN-001", sales_order_id="so-1", dispatch_id=dispatch.id, customer_id="c-1", shortage_mt=Decimal("0.5"), shortage_pct=Decimal("2.5"), rate_per_qtl=Decimal("5000.0") ) cn.approve_credit_note("sales-manager-1") self.assertTrue(cn.manager_approved) self.assertEqual(cn.approved_by, "sales-manager-1") # Controller auth failures self.assertFalse(logistics_controller.register_vehicle(None, None, {}).get("authenticated", True)) self.assertFalse(logistics_controller.create_dispatch(None, None, {}).get("authenticated", True)) self.assertFalse(logistics_controller.record_outward_weighment(None, None, "d-1", {}).get("authenticated", True)) self.assertFalse(logistics_controller.list_dispatches(None, None).get("authenticated", True)) self.assertFalse(logistics_controller.record_proof_of_delivery(None, None, "d-1", {}).get("authenticated", True)) self.assertFalse(logistics_controller.approve_credit_note(None, None, "cn-1").get("authenticated", True)) # Confirm delivery missing dispatch res_deliv_nf = logistics_controller.record_proof_of_delivery(self.buyer_auth, self.tenant_id, "nonexistent-dispatch", { "delivered_date": "2026-10-12", "destination_net_weight_mt": 15.0, "destination_bag_count": 150 }) self.assertEqual(res_deliv_nf["status_code"], 404) # Dispatch with vehicle lookup by reg_no and SO customer lookup (lines 195, 212-219) logistics_controller.store.insert("customer_sales_orders", self.tenant_id, { "id": "so-lookup-1", "customer_id": "CUST-001" }) res_disp_reg = logistics_controller.create_dispatch(self.admin_auth, self.tenant_id, { "sales_order_id": "so-lookup-1", "allocation_id": "alloc-1", "vehicle_id": "MP-43-G-1234", "origin_warehouse_id": "WH-01", "destination_city": "Indore" }) self.assertEqual(res_disp_reg["status_code"], 201) # Missing required fields in outward weighment (line 294) disp_id = res_disp_reg["dispatch"]["id"] res_weigh_req = logistics_controller.record_outward_weighment(self.admin_auth, self.tenant_id, disp_id, {}) self.assertEqual(res_weigh_req["status_code"], 400) # Missing required fields in POD (line 375) res_pod_req = logistics_controller.record_proof_of_delivery(self.admin_auth, self.tenant_id, disp_id, {}) self.assertEqual(res_pod_req["status_code"], 400) # POD validation error (line 393) res_pod_val = logistics_controller.record_proof_of_delivery(self.admin_auth, self.tenant_id, disp_id, { "dest_weighbridge_net_mt": -1.0, "dispatched_net_mt": 10.0, "consignee_ack_note": "Ack", "pod_ref": "ref-1" }) self.assertEqual(res_pod_val["status_code"], 400) # Context error res_ctx = logistics_controller.list_fleet(self.buyer_auth, "invalid-tenant") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 10. Finance & Settlement Models & Controller # ========================================================================= def test_finance_validation_and_controller(self): """Covers finance.py models and controller paths.""" today = datetime.now(timezone.utc) # CustomerPaymentReceipt bounced transition receipt = CustomerPaymentReceipt( tenant_id=self.tenant_id, receipt_number="RCP-001", customer_id="CUST-001", receipt_date=today, amount_inr=Decimal("100000.0"), payment_mode="CHEQUE", instrument_ref="CHQ-123456" ) receipt.mark_bounced("Cheque bounced - signature mismatch") self.assertEqual(receipt.status, "BOUNCED") self.assertEqual(receipt.bounce_reason, "Cheque bounced - signature mismatch") # SupplierPayable payment recording and status payable = SupplierPayable( tenant_id=self.tenant_id, supplier_id="SUPP-01", grn_number="GRN-001", sauda_reference="SDA-001", invoice_amount_inr=Decimal("200000.0"), grn_date=today, credit_days=10 ) payable.record_payment(Decimal("50000.0")) self.assertEqual(payable.status, "PARTIALLY_PAID") payable.record_payment(Decimal("150000.0")) self.assertEqual(payable.status, "PAID") # Aging computation with non-datetime / non-str date (line 714) aging = compute_customer_aging([ {"balance_inr": 5000.0, "date": 1234567890} ]) self.assertEqual(aging["bucket_0_to_7_days_inr"], 5000.0) # Controller auth failures self.assertEqual(finance_controller.get_customer_aging(None, None, "CUST-001").get("status_code"), 401) self.assertFalse(finance_controller.get_credit_exposure(None, None, "CUST-001").get("authenticated", True)) self.assertFalse(finance_controller.list_credit_locks(None, None).get("authenticated", True)) self.assertFalse(finance_controller.override_credit_lock(None, None, "l-1", {}).get("authenticated", True)) self.assertFalse(finance_controller.post_payment_receipt(None, None, {}).get("authenticated", True)) self.assertFalse(finance_controller.clear_payment_receipt(None, None, "r-1").get("authenticated", True)) self.assertFalse(finance_controller.bounce_payment_receipt(None, None, "r-1", {}).get("authenticated", True)) self.assertFalse(finance_controller.get_supplier_payables(None, None).get("authenticated", True)) self.assertFalse(finance_controller.record_supplier_disbursement(None, None, {}).get("authenticated", True)) self.assertFalse(finance_controller.get_payables_snapshot(None, None).get("authenticated", True)) self.assertFalse(finance_controller.post_expense_voucher(None, None, {}).get("authenticated", True)) self.assertFalse(finance_controller.list_expense_vouchers(None, None).get("authenticated", True)) # Supplier payable overdue > 15 days in list and snapshot old_due = (datetime.now(timezone.utc) - timedelta(days=20)).isoformat() finance_controller.store.insert("supplier_payables", self.tenant_id, { "id": "pay-overdue-15", "supplier_id": "SUPP-OLD", "invoice_amount_inr": 300000.0, "paid_amount_inr": 0.0, "outstanding_amount_inr": 300000.0, "due_date": old_due, "status": "UNPAID" }) res_payables = finance_controller.get_supplier_payables(self.buyer_auth, self.tenant_id, supplier_id="SUPP-OLD") self.assertEqual(res_payables["status_code"], 200) self.assertEqual(res_payables["payables"][0]["aging_bucket"], "OVER_15_DAYS") res_snap = finance_controller.get_payables_snapshot(self.buyer_auth, self.tenant_id) self.assertEqual(res_snap["status_code"], 200) self.assertGreater(res_snap["aging_summary"]["OVER_15_DAYS"], 0.0) # Context error res_ctx = finance_controller.get_customer_aging(self.buyer_auth, "invalid-tenant", "CUST-001") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 11. Analytics Controller # ========================================================================= def test_analytics_controller_branches(self): """Covers analytics.py predicate and modal rate normalization branches.""" # Seeding early return when already >= 20 analytics_controller._seed_historical_observations(self.tenant_id) # Query with modal_rate normalization and non-matching commodities res_analytics = analytics_controller.get_market_trends( self.buyer_auth, self.tenant_id, commodity_id="COMM-SOYBEAN", window_days=10 ) self.assertEqual(res_analytics["status_code"], 200) # Context error res_ctx = analytics_controller.get_market_trends(self.buyer_auth, "invalid-tenant") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 12. Policies & Governance Models & Controller # ========================================================================= def test_policies_validation_and_controller(self): """Covers policy.py naive datetimes and policy controller fallback branches.""" # Naive datetimes in TenantOperatingPolicy and is_effective_at naive_from = datetime(2026, 1, 1, 0, 0, 0) naive_to = datetime(2026, 12, 31, 23, 59, 59) pol = TenantOperatingPolicy( tenant_id=self.tenant_id, created_by="admin@alpha.com", change_reason="Annual update", effective_from=naive_from, effective_to=naive_to, credit_watch_threshold_pct=Decimal("80.0"), credit_lock_threshold_pct=Decimal("100.0") ) self.assertTrue(pol.is_effective_at(datetime(2026, 6, 1))) # Effective policy fallback to latest published version (lines 253-256) res_eff = policy_controller.get_effective_policy( self.buyer_auth, self.tenant_id, as_of="2020-01-01T00:00:00Z" ) self.assertEqual(res_eff["status_code"], 200) # Context error res_ctx = policy_controller.list_policies(self.buyer_auth, "invalid-tenant") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 13. Master Data Models & Controller # ========================================================================= def test_master_data_validation_and_controller(self): """Covers master_data.py models and master data controller branches.""" # Commodity empty code with self.assertRaises(ValueError): Commodity(tenant_id=self.tenant_id, code="", name="Soybean") # Variety empty tenant with self.assertRaises(ValueError): CommodityVariety(tenant_id="", commodity_id="c-1", code="YEL", name="Yellow") # TradingCounterparty empty tenant, invalid GSTIN, negative credit limit with self.assertRaises(ValueError): TradingCounterparty( tenant_id="", name="Kisan", counterparty_type="FARMER", pan_number="ABCDE1234F", bank_account_number="12345", bank_ifsc_code="SBIN0001", bank_name="SBI" ) with self.assertRaises(ValueError): TradingCounterparty( tenant_id=self.tenant_id, name="Kisan", counterparty_type="FARMER", pan_number="ABCDE1234F", bank_account_number="12345", bank_ifsc_code="SBIN0001", bank_name="SBI", gstin="INVALID_GST_NUMBER" ) with self.assertRaises(ValueError): TradingCounterparty( tenant_id=self.tenant_id, name="Kisan", counterparty_type="FARMER", pan_number="ABCDE1234F", bank_account_number="12345", bank_ifsc_code="SBIN0001", bank_name="SBI", credit_limit_inr=-500.0 ) # Godown empty tenant and zero chambers with self.assertRaises(ValueError): Godown(tenant_id="", code="GD-01", name="Main", capacity_mt=1000.0, address="Kota") with self.assertRaises(ValueError): Godown(tenant_id=self.tenant_id, code="GD-01", name="Main", capacity_mt=1000.0, address="Kota", chambers_count=0) # Controller create commodity with nested invalid variety (line 135) res_nested = master_data_controller.create_commodity(self.admin_auth, self.tenant_id, { "code": "COMM-BARLEY", "name": "Barley", "varieties": [{"code": "", "name": "Invalid"}] }) self.assertEqual(res_nested["status_code"], 201) # Add variety invalid data (line 306) res_add_var = master_data_controller.add_variety( self.admin_auth, self.tenant_id, res_nested["id"], {"code": "BAR-1", "name": ""} ) self.assertEqual(res_add_var["status_code"], 422) # Safe delete commodity (lines 262-263) res_del = master_data_controller.delete_commodity(self.admin_auth, self.tenant_id, res_nested["id"]) self.assertEqual(res_del["status_code"], 200) # Counterparty invalid credit terms string (line 350) res_cp_terms = master_data_controller.create_counterparty(self.admin_auth, self.tenant_id, { "name": "Test Partner", "counterparty_type": "SUPPLIER_AGGREGATOR", "pan_number": "ABCDE5678G", "credit_terms_days": "invalid-days" }) self.assertEqual(res_cp_terms["status_code"], 422) # Context error res_ctx = master_data_controller.list_commodities(self.admin_auth, "invalid-tenant") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 14. Privileged Support Grants & Controller # ========================================================================= def test_support_validation_and_controller(self): """Covers support.py naive datetimes and support controller expired branches.""" # Grant missing expires_at or naive datetime grant = PrivilegedSupportGrant( tenant_id=self.tenant_id, engineer_user_id="eng-1", requested_by="admin-1", reason="Investigate timeout INC-101", duration_minutes=60, access_scope="READ_ONLY_SUPPORT", is_break_glass=False ) grant.expires_at = None self.assertFalse(grant.is_valid()) # Naive expires_at grant.expires_at = datetime(2027, 1, 1, 0, 0, 0) grant.status = "ACTIVE" self.assertTrue(grant.is_valid(datetime(2026, 6, 1))) # Dynamic expiration check in list_grants with naive date and invalid date support_controller.store.insert("privileged_support_grants", self.tenant_id, { "id": "grant-naive-exp", "status": "ACTIVE", "expires_at": "2026-01-01T00:00:00" }) support_controller.store.insert("privileged_support_grants", self.tenant_id, { "id": "grant-invalid-exp", "status": "ACTIVE", "expires_at": "not-a-date" }) res_grants = support_controller.list_grants(self.admin_auth, self.tenant_id) self.assertEqual(res_grants["status_code"], 200) # Context error res_ctx = support_controller.list_grants(self.admin_auth, "invalid-tenant") self.assertEqual(res_ctx["status_code"], 403) # ========================================================================= # 15. Sandbox Mocks Edge Cases # ========================================================================= def test_sandbox_mocks_edge_cases(self): """Covers customer credit mock zero limit and notification filter.""" # Customer credit mock zero credit limit (line 102) zero_cust = { "id": "CUST-ZERO-LIMIT", "name": "Zero Limit Firm", "segment": "Processor", "city": "Indore", "state": "Madhya Pradesh", "credit_limit_inr": Decimal("0.00"), "outstanding_inr": Decimal("0.00"), "payment_terms": "Advance", "is_active": True, } SANDBOX_CUSTOMERS.append(zero_cust) try: res_proj = CustomerCreditMock.calculate_projected_exposure("CUST-ZERO-LIMIT", Decimal("50000.0")) self.assertEqual(res_proj["exposure_ratio_pct"], Decimal("100.00")) finally: if zero_cust in SANDBOX_CUSTOMERS: SANDBOX_CUSTOMERS.remove(zero_cust) # Notification mock channel filter (line 83) notification_mock.dispatch_alert_notification( tenant_id=self.tenant_id, alert_id="ALT-001", category="CREDIT", severity="WARNING", title="Credit Warning", message="Test SMS", recipients=["admin@alpha.com"], channels=["SMS"] ) sms_list = notification_mock.get_dispatched_notifications(channel="SMS") self.assertTrue(len(sms_list) >= 1) if __name__ == "__main__": unittest.main()