c_agri_trade_code/tests/backend/test_master_data_policies.py

1028 lines
51 KiB
Python

"""Unit & Domain Verification Suite for Iteration 07 (Master Data, Support Security & Operating Policies).
Fulfills:
- UC-016: Commodity & Counterparty Master Data (FR-MASTERDATA-001, FR-MASTERDATA-002)
- UC-020: Tenant Resource Isolation & Privileged Support Access (FR-TENANTSUPPORTSECURITY-001, FR-TENANTSUPPORTSECURITY-002)
- UC-026: Tenant Operating Policy Configuration (FR-TENANTOPERATINGPOLICIES-001)
Adheres to UP-AI v1.5 testing standards:
- 4 Test Dimensions: Happy Path, Boundary Conditions, Negative / Error Paths, and FSM Invariant Checks.
- Strict anti-placeholder rule: Genuine domain calculations and mathematical invariants.
"""
from datetime import datetime, timezone, timedelta
from decimal import Decimal
import sys
import unittest
import uuid
from pathlib import Path
from typing import Dict, Any
# Ensure code_root is in sys.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))
from backend.app.db.session import InMemoryTenantStorage
from backend.app.auth.tenant_context import TenantContextResolver
from backend.app.models.tenant import Tenant, TenantMembership
from backend.app.models.master_data import (
Commodity,
CommodityVariety,
TradingCounterparty,
Godown,
COUNTERPARTY_TYPES,
ALLOWED_CREDIT_TERMS_DAYS,
)
from backend.app.models.support import (
PrivilegedSupportGrant,
MissingTenantContextException,
run_with_tenant_context,
SUPPORT_GRANT_STATUSES,
SUPPORT_ACCESS_SCOPES,
MIN_GRANT_MINUTES,
MAX_GRANT_MINUTES,
)
from backend.app.models.policy import (
TenantOperatingPolicy,
check_policy_intervals_overlap,
)
from backend.app.api.master_data import MasterDataController
from backend.app.api.support import SupportController
from backend.app.api.policies import PolicyController
from sandbox.identity_mock import mock_idp
from sandbox.notification_mock import NotificationMock
class TestMasterDataAndPoliciesSuite(unittest.TestCase):
"""Exhaustive unit test suite covering Master Data, Support Security, and Operating Policies."""
def setUp(self):
self.store = InMemoryTenantStorage()
self.resolver = TenantContextResolver(store=self.store)
self.notifier = NotificationMock()
# Seed test tenant and memberships
self.tenant_id = "tenant-master-01"
self.tenant = Tenant(
tenant_id=self.tenant_id,
business_name="Malwa Agro Trading Co",
legal_identifier="23AABCT9999F1Z0",
contact_email="admin@malwa.test",
primary_mandi="Neemuch APMC",
status="ACTIVE",
)
self.store.save_tenant(self.tenant)
# Admin User & Membership
self.admin_user_id = "user-admin-01"
self.admin_email = "admin@malwa.test"
self.admin_membership = TenantMembership(
tenant_id=self.tenant_id,
user_id=self.admin_user_id,
email=self.admin_email,
role="Tenant Admin",
status="ACTIVE",
)
self.store.save_membership(self.admin_membership)
# Support Engineer User & Membership
self.support_user_id = "user-support-01"
self.support_email = "support.ravi@platform.local"
self.support_membership = TenantMembership(
tenant_id=self.tenant_id,
user_id=self.support_user_id,
email=self.support_email,
role="Operations Supervisor",
status="ACTIVE",
)
self.store.save_membership(self.support_membership)
# Second Tenant for Isolation Testing
self.other_tenant_id = "tenant-other-02"
self.other_tenant = Tenant(
tenant_id=self.other_tenant_id,
business_name="Bhopal Grain Processors",
legal_identifier="23BBCDT1111G1Z1",
contact_email="admin@bhopal.test",
primary_mandi="Bhopal APMC",
status="ACTIVE",
)
self.store.save_tenant(self.other_tenant)
self.other_membership = TenantMembership(
tenant_id=self.other_tenant_id,
user_id="user-other-01",
email="admin@bhopal.test",
role="Tenant Admin",
status="ACTIVE",
)
self.store.save_membership(self.other_membership)
# Mint Auth Tokens
self.admin_token = mock_idp.mint_jwt(
subject=self.admin_user_id,
email=self.admin_email,
name="Admin User",
roles=["Tenant Admin", "Partner"],
tenant_id=self.tenant_id,
)
self.admin_auth_header = f"Bearer {self.admin_token}"
self.support_token = mock_idp.mint_jwt(
subject=self.support_user_id,
email=self.support_email,
name="Support Ravi",
roles=["Operations Supervisor"],
tenant_id=self.tenant_id,
)
self.support_auth_header = f"Bearer {self.support_token}"
self.other_token = mock_idp.mint_jwt(
subject="user-other-01",
email="admin@bhopal.test",
name="Other Admin",
roles=["Tenant Admin"],
tenant_id=self.other_tenant_id,
)
self.other_auth_header = f"Bearer {self.other_token}"
# Initialize Controllers
self.master_ctrl = MasterDataController(store=self.store, resolver=self.resolver)
self.support_ctrl = SupportController(store=self.store, resolver=self.resolver, notifier=self.notifier)
self.policy_ctrl = PolicyController(store=self.store, resolver=self.resolver, notifier=self.notifier)
# =========================================================================
# Dimension 1: Happy Path Tests
# =========================================================================
def test_commodity_and_variety_creation_and_listing(self):
"""Happy Path: Create commodity with varieties, query catalog, and fetch by ID."""
payload = {
"code": "SOYA",
"name": "Soybean Yellow",
"hsn_code": "12019000",
"standard_bag_weight_kg": 50.0,
"moisture_baseline_pct": 10.0,
"foreign_matter_max_pct": 2.0,
"damaged_grain_max_pct": 3.0,
"qc_required": True,
"varieties": [
{"code": "JS-335", "name": "Jawahar Soya 335"},
{"code": "JS-9560", "name": "Jawahar Soya 9560"},
],
}
res = self.master_ctrl.create_commodity(self.admin_auth_header, self.tenant_id, payload)
self.assertEqual(res.get("status_code"), 201)
self.assertEqual(res.get("code"), "SOYA")
self.assertEqual(len(res.get("varieties", [])), 2)
comm_id = res["id"]
# List commodities
list_res = self.master_ctrl.list_commodities(self.admin_auth_header, self.tenant_id)
self.assertEqual(list_res.get("status_code"), 200)
self.assertEqual(list_res.get("count"), 1)
self.assertEqual(len(list_res["commodities"][0]["varieties"]), 2)
# Get by ID
get_res = self.master_ctrl.get_commodity(self.admin_auth_header, self.tenant_id, comm_id)
self.assertEqual(get_res.get("status_code"), 200)
self.assertEqual(get_res.get("name"), "Soybean Yellow")
# Add additional variety
var_payload = {"code": "NRC-37", "name": "Ahilya 2"}
var_res = self.master_ctrl.add_variety(self.admin_auth_header, self.tenant_id, comm_id, var_payload)
self.assertEqual(var_res.get("status_code"), 201)
self.assertEqual(var_res.get("code"), "NRC-37")
# Update commodity
patch_res = self.master_ctrl.update_commodity(
self.admin_auth_header, self.tenant_id, comm_id, {"standard_bag_weight_kg": 60.0}
)
self.assertEqual(patch_res.get("status_code"), 200)
self.assertEqual(patch_res.get("standard_bag_weight_kg"), 60.0)
def test_counterparty_registration_and_listing(self):
"""Happy Path: Register Farmers, Agents, Processors with valid statutory PAN and credit terms."""
payload_farmer = {
"name": "Ramesh Patel",
"counterparty_type": "FARMER",
"pan_number": "ABCDE1234F",
"credit_terms_days": 7,
"credit_limit_inr": 500000.0,
"bank_account_number": "123456789012",
"bank_ifsc_code": "SBIN0001234",
"bank_name": "State Bank of India",
}
res_farmer = self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, payload_farmer)
self.assertEqual(res_farmer.get("status_code"), 201)
self.assertEqual(res_farmer.get("counterparty_type"), "FARMER")
payload_agent = {
"name": "Balaji Mandi Traders",
"counterparty_type": "COMMISSION_AGENT",
"pan_number": "BCDEF2345G",
"gstin": "23BCDEF2345G1Z5",
"credit_terms_days": 15,
"credit_limit_inr": 2500000.0,
"bank_account_number": "987654321098",
"bank_ifsc_code": "HDFC0001234",
"bank_name": "HDFC Bank",
}
res_agent = self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, payload_agent)
self.assertEqual(res_agent.get("status_code"), 201)
payload_buyer = {
"name": "ITC Agro Processing Ltd",
"counterparty_type": "PROCESSOR",
"pan_number": "CDEFG3456H",
"gstin": "27CDEFG3456H1Z2",
"credit_terms_days": 21,
"credit_limit_inr": 5000000.0,
"bank_account_number": "555566667777",
"bank_ifsc_code": "ICIC0001234",
"bank_name": "ICICI Bank",
}
res_buyer = self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, payload_buyer)
self.assertEqual(res_buyer.get("status_code"), 201)
# List all
list_all = self.master_ctrl.list_counterparties(self.admin_auth_header, self.tenant_id)
self.assertEqual(list_all.get("status_code"), 200)
self.assertEqual(list_all.get("count"), 3)
# Filter by type
list_farmers = self.master_ctrl.list_counterparties(self.admin_auth_header, self.tenant_id, "FARMER")
self.assertEqual(list_farmers.get("status_code"), 200)
self.assertEqual(list_farmers.get("count"), 1)
def test_godown_creation_and_listing(self):
"""Happy Path: Create and list storage godowns with MT capacities."""
payload = {
"code": "WH-01",
"name": "Neemuch Central Godown",
"capacity_mt": 2500.0,
"address": "Yard 4, Neemuch APMC Yard, MP",
"chambers_count": 4,
}
res = self.master_ctrl.create_godown(self.admin_auth_header, self.tenant_id, payload)
self.assertEqual(res.get("status_code"), 201)
self.assertEqual(res.get("code"), "WH-01")
list_res = self.master_ctrl.list_godowns(self.admin_auth_header, self.tenant_id)
self.assertEqual(list_res.get("status_code"), 200)
self.assertEqual(list_res.get("count"), 1)
def test_privileged_support_dual_authorization_lifecycle(self):
"""Happy Path: Request grant -> Tenant Admin approves -> ephemeral token issued -> verify expiry."""
req_payload = {
"reason": "Investigating weighbridge decimal roundoff in ticket INC-4411",
"duration_minutes": 60,
"access_scope": "FULL_SUPPORT",
}
req_res = self.support_ctrl.request_grant(self.support_auth_header, self.tenant_id, req_payload)
self.assertEqual(req_res.get("status_code"), 201)
self.assertEqual(req_res.get("status"), "PENDING")
grant_id = req_res["id"]
# Dual authorization: Admin approves
appr_res = self.support_ctrl.approve_grant(self.admin_auth_header, self.tenant_id, grant_id)
self.assertEqual(appr_res.get("status_code"), 200)
self.assertEqual(appr_res.get("status"), "ACTIVE")
self.assertTrue(appr_res.get("ephemeral_token", "").startswith("mock-support-impersonation-token-"))
# List grants
list_res = self.support_ctrl.list_grants(self.admin_auth_header, self.tenant_id)
self.assertEqual(list_res.get("status_code"), 200)
self.assertEqual(list_res.get("count"), 1)
self.assertEqual(list_res["grants"][0]["status"], "ACTIVE")
def test_tenant_operating_policy_creation_and_as_of_lookup(self):
"""Happy Path: Publish versioned operating policies and perform as-of historical lookup."""
# Publish v1
v1_payload = {
"weighbridge_tolerance_pct": 0.50,
"moisture_deduction_threshold_pct": 12.00,
"credit_watch_threshold_pct": 80.00,
"credit_lock_threshold_pct": 100.00,
"qc_required_default": True,
"partner_dispatch_override_ceiling_inr": 5000000.00,
"effective_from": "2026-01-01T00:00:00Z",
"effective_to": "2026-06-30T23:59:59Z",
"change_reason": "Baseline H1 2026 trading policy",
}
res_v1 = self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, v1_payload)
self.assertEqual(res_v1.get("status_code"), 201)
self.assertEqual(res_v1.get("version"), 1)
# Publish v2
v2_payload = {
"weighbridge_tolerance_pct": 0.40,
"moisture_deduction_threshold_pct": 11.50,
"credit_watch_threshold_pct": 75.00,
"credit_lock_threshold_pct": 95.00,
"qc_required_default": True,
"partner_dispatch_override_ceiling_inr": 7500000.00,
"effective_from": "2026-07-01T00:00:00Z",
"effective_to": None,
"change_reason": "Monsoon procurement risk tightening",
}
res_v2 = self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, v2_payload)
self.assertEqual(res_v2.get("status_code"), 201)
self.assertEqual(res_v2.get("version"), 2)
# As-of query for March 2026 (should return v1)
as_of_v1 = self.policy_ctrl.get_effective_policy(
self.admin_auth_header, self.tenant_id, as_of="2026-03-15T12:00:00Z"
)
self.assertEqual(as_of_v1.get("status_code"), 200)
self.assertEqual(as_of_v1.get("version"), 1)
self.assertEqual(as_of_v1.get("moisture_deduction_threshold_pct"), 12.0)
# Current effective query (should return v2)
curr_pol = self.policy_ctrl.get_effective_policy(self.admin_auth_header, self.tenant_id)
self.assertEqual(curr_pol.get("status_code"), 200)
self.assertEqual(curr_pol.get("version"), 2)
self.assertEqual(curr_pol.get("moisture_deduction_threshold_pct"), 11.5)
# =========================================================================
# Dimension 2: Boundary & Edge Value Tests
# =========================================================================
def test_credit_terms_strictly_7_15_21_days(self):
"""Boundary: Credit terms strictly in [7, 15, 21] days; any other rejected."""
base_payload = {
"name": "Kisan Credit Test",
"counterparty_type": "FARMER",
"pan_number": "XXXXX1234F",
"bank_account_number": "123456789012",
"bank_ifsc_code": "SBIN0001234",
"bank_name": "SBI",
}
# Invalid terms: 0, 10, 14, 30, -5
for invalid_days in [0, 10, 14, 30, -5]:
p = dict(base_payload)
p["pan_number"] = f"ABCDE{abs(invalid_days):04d}F"
p["credit_terms_days"] = invalid_days
res = self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, p)
self.assertEqual(res.get("status_code"), 422, f"Expected 422 for credit days {invalid_days}")
self.assertEqual(res.get("error"), "INVALID_CREDIT_TERMS")
# Valid terms: 7, 15, 21
for valid_days in [7, 15, 21]:
p = dict(base_payload)
p["pan_number"] = f"VALAB{valid_days:02d}99F"
p["credit_terms_days"] = valid_days
res = self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, p)
self.assertEqual(res.get("status_code"), 201, f"Expected 201 for credit days {valid_days}")
def test_commodity_parameter_boundaries(self):
"""Boundary: Moisture [0, 30%], Foreign Matter [0, 15%], Damaged [0, 20%]."""
# Moisture upper boundary 30.0% valid; 30.01% invalid
comm_valid = Commodity(
tenant_id=self.tenant_id,
code="COMM-OK",
name="Valid Commodity",
moisture_baseline_pct=30.0,
foreign_matter_max_pct=15.0,
damaged_grain_max_pct=20.0,
)
self.assertEqual(float(comm_valid.moisture_baseline_pct), 30.0)
with self.assertRaises(ValueError):
Commodity(tenant_id=self.tenant_id, code="COMM-ERR", name="Err", moisture_baseline_pct=30.01)
with self.assertRaises(ValueError):
Commodity(tenant_id=self.tenant_id, code="COMM-ERR", name="Err", foreign_matter_max_pct=15.01)
with self.assertRaises(ValueError):
Commodity(tenant_id=self.tenant_id, code="COMM-ERR", name="Err", damaged_grain_max_pct=20.01)
with self.assertRaises(ValueError):
Commodity(tenant_id=self.tenant_id, code="COMM-ERR", name="Err", standard_bag_weight_kg=0.0)
def test_support_grant_duration_boundaries(self):
"""Boundary: Duration must be between 15 and 120 minutes."""
# 15 minutes is valid minimum
g_min = PrivilegedSupportGrant(
tenant_id=self.tenant_id,
engineer_user_id="eng@test.local",
requested_by="eng@test.local",
reason="Minimum 15 mins test ticket",
duration_minutes=15,
)
self.assertEqual(g_min.duration_minutes, 15)
# 120 minutes is valid maximum
g_max = PrivilegedSupportGrant(
tenant_id=self.tenant_id,
engineer_user_id="eng@test.local",
requested_by="eng@test.local",
reason="Maximum 120 mins test ticket",
duration_minutes=120,
)
self.assertEqual(g_max.duration_minutes, 120)
# 14 mins rejected
with self.assertRaises(ValueError):
PrivilegedSupportGrant(
tenant_id=self.tenant_id,
engineer_user_id="eng@test.local",
requested_by="eng@test.local",
reason="Sub-minimum test ticket",
duration_minutes=14,
)
# 121 mins rejected
with self.assertRaises(ValueError):
PrivilegedSupportGrant(
tenant_id=self.tenant_id,
engineer_user_id="eng@test.local",
requested_by="eng@test.local",
reason="Over-maximum test ticket",
duration_minutes=121,
)
def test_policy_parameter_boundaries_and_ordering_invariant(self):
"""Boundary: Credit watch must be strictly less than credit lock threshold."""
# watch >= lock fails
with self.assertRaises(ValueError):
TenantOperatingPolicy(
tenant_id=self.tenant_id,
created_by="admin@test.local",
change_reason="Invalid threshold ordering",
effective_from=datetime.now(timezone.utc),
credit_watch_threshold_pct=90.0,
credit_lock_threshold_pct=85.0, # Watch > Lock
)
with self.assertRaises(ValueError):
TenantOperatingPolicy(
tenant_id=self.tenant_id,
created_by="admin@test.local",
change_reason="Equal threshold ordering",
effective_from=datetime.now(timezone.utc),
credit_watch_threshold_pct=90.0,
credit_lock_threshold_pct=90.0, # Watch == Lock
)
# Valid ordering
p = TenantOperatingPolicy(
tenant_id=self.tenant_id,
created_by="admin@test.local",
change_reason="Valid threshold ordering",
effective_from=datetime.now(timezone.utc),
credit_watch_threshold_pct=80.0,
credit_lock_threshold_pct=100.0,
)
self.assertEqual(float(p.credit_watch_threshold_pct), 80.0)
# =========================================================================
# Dimension 3: Negative & Security Rejection Tests
# =========================================================================
def test_duplicate_pan_in_same_tenant_rejected_across_tenants_allowed(self):
"""Negative: Duplicate PAN within same tenant returns 409; allowed across different tenants."""
payload = {
"name": "Kisan Unique PAN",
"counterparty_type": "FARMER",
"pan_number": "ABCDE9999F",
"credit_terms_days": 7,
"bank_account_number": "123456789012",
"bank_ifsc_code": "SBIN0001234",
"bank_name": "SBI",
}
# First creation in tenant-master-01
res1 = self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, payload)
self.assertEqual(res1.get("status_code"), 201)
# Duplicate creation in same tenant -> 409
res2 = self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, payload)
self.assertEqual(res2.get("status_code"), 409)
self.assertEqual(res2.get("error"), "DUPLICATE_PAN_IN_TENANT")
# Same PAN in tenant-other-02 -> 201
res3 = self.master_ctrl.create_counterparty(self.other_auth_header, self.other_tenant_id, payload)
self.assertEqual(res3.get("status_code"), 201)
def test_dual_authorization_enforced_self_approval_blocked(self):
"""Security: Requester cannot approve own support grant."""
req_payload = {
"reason": "Debugging permission escalation ticket INC-9900",
"duration_minutes": 60,
}
res_req = self.support_ctrl.request_grant(self.admin_auth_header, self.tenant_id, req_payload)
self.assertEqual(res_req.get("status_code"), 201)
grant_id = res_req["id"]
# Requester attempts self-approval -> 403 Forbidden
appr_res = self.support_ctrl.approve_grant(self.admin_auth_header, self.tenant_id, grant_id)
self.assertEqual(appr_res.get("status_code"), 403)
self.assertEqual(appr_res.get("error"), "DUAL_AUTHORIZATION_REQUIRED")
def test_overlapping_policy_intervals_rejected(self):
"""Negative: Overlapping policy intervals rejected with 409 Conflict."""
# Create v1 from 2026-01-01 to 2026-06-30
self.policy_ctrl.create_policy(
self.admin_auth_header,
self.tenant_id,
{
"effective_from": "2026-01-01T00:00:00Z",
"effective_to": "2026-06-30T23:59:59Z",
"change_reason": "Policy H1 2026",
},
)
# Attempt to create conflicting policy from 2026-04-01 to 2026-09-30 -> 409
conflict_res = self.policy_ctrl.create_policy(
self.admin_auth_header,
self.tenant_id,
{
"effective_from": "2026-04-01T00:00:00Z",
"effective_to": "2026-09-30T23:59:59Z",
"change_reason": "Conflicting overlap",
},
)
self.assertEqual(conflict_res.get("status_code"), 409)
self.assertEqual(conflict_res.get("error"), "OVERLAPPING_POLICY_INTERVAL")
def test_statutory_validation_pan_ifsc_gstin_rejections(self):
"""Negative: Malformed PAN, IFSC, and GSTIN rejected."""
base = {
"name": "Statutory Test",
"counterparty_type": "FARMER",
"credit_terms_days": 7,
"bank_account_number": "123456789012",
"bank_name": "SBI",
}
# Malformed PAN
with self.assertRaises(ValueError):
TradingCounterparty(
tenant_id=self.tenant_id,
name="Bad PAN",
counterparty_type="FARMER",
pan_number="BADPAN123",
bank_account_number="12345678",
bank_ifsc_code="SBIN0001234",
bank_name="SBI",
)
# Malformed IFSC
with self.assertRaises(ValueError):
TradingCounterparty(
tenant_id=self.tenant_id,
name="Bad IFSC",
counterparty_type="FARMER",
pan_number="ABCDE1234F",
bank_account_number="12345678",
bank_ifsc_code="INVALID_IFSC",
bank_name="SBI",
)
# =========================================================================
# Dimension 4: FSM Invariants & Referential Integrity Tests
# =========================================================================
def test_commodity_deletion_reference_guard_against_active_lots(self):
"""FSM Invariant: Deleting a commodity referenced by active stock lots returns 409."""
comm_res = self.master_ctrl.create_commodity(
self.admin_auth_header,
self.tenant_id,
{"code": "MUSTARD", "name": "Mustard Seed", "standard_bag_weight_kg": 50.0},
)
comm_id = comm_res["id"]
# Insert active inventory lot referencing this commodity
self.store.insert(
"inventory_lots",
self.tenant_id,
{"id": "LOT-MUSTARD-01", "commodity_id": comm_id, "commodity": "MUSTARD", "gross_mt": 25.0},
)
# Attempt deletion -> 409 Conflict
del_res = self.master_ctrl.delete_commodity(self.admin_auth_header, self.tenant_id, comm_id)
self.assertEqual(del_res.get("status_code"), 409)
self.assertEqual(del_res.get("error"), "REFERENCE_CONSTRAINT_VIOLATION")
# Soft deactivation succeeds
deact_res = self.master_ctrl.update_commodity(
self.admin_auth_header, self.tenant_id, comm_id, {"is_active": False}
)
self.assertEqual(deact_res.get("status_code"), 200)
self.assertFalse(deact_res.get("is_active"))
def test_emergency_break_glass_access_and_revocation(self):
"""FSM Invariant: Break-glass generates emergency token, logs audit alarm, and allows revocation."""
bg_payload = {
"emergency_justification": "Production market desk unresponsive due to locking deadlock in ticket INC-9999",
"duration_minutes": 30,
}
res_bg = self.support_ctrl.break_glass(self.admin_auth_header, self.tenant_id, bg_payload)
self.assertEqual(res_bg.get("status_code"), 201)
self.assertEqual(res_bg.get("status"), "BREAK_GLASS_ACTIVE")
self.assertTrue(res_bg.get("is_break_glass"))
self.assertTrue(res_bg.get("ephemeral_token", "").startswith("emergency-break-glass-token-"))
grant_id = res_bg["id"]
# Revoke session immediately
rev_res = self.support_ctrl.revoke_grant(self.admin_auth_header, self.tenant_id, grant_id)
self.assertEqual(rev_res.get("status_code"), 200)
self.assertEqual(rev_res.get("status"), "REVOKED")
def test_async_worker_fail_closed_without_tenant_context(self):
"""FSM Invariant: Background worker without tenant context raises MissingTenantContextException."""
def dummy_job():
return "SUCCESS"
# Missing tenant context -> fail closed
with self.assertRaises(MissingTenantContextException):
run_with_tenant_context(None, dummy_job)
with self.assertRaises(MissingTenantContextException):
run_with_tenant_context("", dummy_job)
# With tenant context -> succeeds
res = run_with_tenant_context(self.tenant_id, dummy_job)
self.assertEqual(res, "SUCCESS")
def test_default_policy_synthesis_when_empty(self):
"""FSM Invariant: Synthesize default baseline policy v1 when tenant has no records."""
eff_res = self.policy_ctrl.get_effective_policy(self.admin_auth_header, self.tenant_id)
self.assertEqual(eff_res.get("status_code"), 200)
self.assertEqual(eff_res.get("version"), 1)
self.assertEqual(eff_res.get("weighbridge_tolerance_pct"), 0.5)
self.assertEqual(eff_res.get("moisture_deduction_threshold_pct"), 12.0)
self.assertEqual(eff_res.get("credit_watch_threshold_pct"), 80.0)
self.assertEqual(eff_res.get("credit_lock_threshold_pct"), 100.0)
self.assertTrue(eff_res.get("qc_required_default"))
self.assertEqual(eff_res.get("partner_dispatch_override_ceiling_inr"), 5000000.0)
def test_privileged_support_grant_model_lifecycle(self):
"""Domain: PrivilegedSupportGrant validation, dual-auth, expiry, and dict conversion."""
# 1. Constructor validations
with self.assertRaises(ValueError):
PrivilegedSupportGrant(tenant_id="", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Valid Reason")
with self.assertRaises(ValueError):
PrivilegedSupportGrant(tenant_id="t1", engineer_user_id=" ", requested_by="req@test.com", reason="Valid Reason")
with self.assertRaises(ValueError):
PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="bad")
with self.assertRaises(ValueError):
PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Valid Reason", duration_minutes=10)
with self.assertRaises(ValueError):
PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Valid Reason", duration_minutes=180)
with self.assertRaises(ValueError):
PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Valid Reason", access_scope="SUPERUSER")
with self.assertRaises(ValueError):
PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Valid Reason", is_break_glass=True, break_glass_justification="short")
# 2. Grant lifecycle & approval validation
grant = PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Incident INC-101 debug")
self.assertFalse(grant.is_valid())
self.assertIsNone(grant.approved_by)
with self.assertRaises(ValueError):
grant.approve("") # empty approver
with self.assertRaises(ValueError):
grant.approve("req@test.com") # self-approval rejected
with self.assertRaises(ValueError):
grant.approve("admin@test.com", duration_minutes=5) # invalid duration
token_jti = grant.approve("admin@test.com", duration_minutes=45)
self.assertTrue(bool(token_jti))
self.assertEqual(grant.status, "ACTIVE")
self.assertTrue(grant.is_valid())
# Cannot approve or reject already active grant
with self.assertRaises(ValueError):
grant.approve("another@test.com")
with self.assertRaises(ValueError):
grant.reject("another@test.com")
# Verify expiry check
future_time = datetime.now(timezone.utc) + timedelta(hours=3)
self.assertFalse(grant.is_valid(as_of=future_time))
self.assertEqual(grant.status, "EXPIRED")
# 3. Reject & revoke lifecycle
grant2 = PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Incident INC-102 investigation")
grant2.reject("security@test.com")
self.assertEqual(grant2.status, "REJECTED")
with self.assertRaises(ValueError):
grant2.revoke("security@test.com")
grant3 = PrivilegedSupportGrant(tenant_id="t1", engineer_user_id="eng@test.com", requested_by="req@test.com", reason="Incident INC-103 investigation")
grant3.approve("admin@test.com")
grant3.revoke("admin@test.com")
self.assertEqual(grant3.status, "REVOKED")
d = grant3.to_dict()
self.assertEqual(d["status"], "REVOKED")
self.assertEqual(d["tenant_id"], "t1")
def test_tenant_operating_policy_model_validation(self):
"""Domain: TenantOperatingPolicy threshold checks, interval overlaps, and effective-date logic."""
now = datetime.now(timezone.utc)
valid_args = {
"tenant_id": "tenant-p1",
"created_by": "admin@test.com",
"change_reason": "Baseline policy setup",
"effective_from": now,
"version": 1,
}
# Constructor validation exceptions
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "tenant_id": ""})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "created_by": " "})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "change_reason": "bad"})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "version": 0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "weighbridge_tolerance_pct": 0.00})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "weighbridge_tolerance_pct": 6.00})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "moisture_deduction_threshold_pct": 4.5})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "moisture_deduction_threshold_pct": 26.0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "credit_watch_threshold_pct": 40.0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "credit_watch_threshold_pct": 96.0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "credit_lock_threshold_pct": 75.0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "credit_lock_threshold_pct": 160.0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "credit_watch_threshold_pct": 85.0, "credit_lock_threshold_pct": 80.0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "partner_dispatch_override_ceiling_inr": -1.0})
with self.assertRaises(ValueError):
TenantOperatingPolicy(**{**valid_args, "effective_from": now, "effective_to": now - timedelta(days=1)})
# is_effective_at checks
ef = datetime(2026, 6, 1, 0, 0, 0, tzinfo=timezone.utc)
et = datetime(2026, 6, 30, 23, 59, 59, tzinfo=timezone.utc)
pol = TenantOperatingPolicy(**{**valid_args, "effective_from": ef, "effective_to": et})
self.assertFalse(pol.is_effective_at(datetime(2026, 5, 31, 0, 0, 0, tzinfo=timezone.utc)))
self.assertTrue(pol.is_effective_at(datetime(2026, 6, 15, 0, 0, 0, tzinfo=timezone.utc)))
self.assertFalse(pol.is_effective_at(datetime(2026, 7, 1, 0, 0, 0, tzinfo=timezone.utc)))
d = pol.to_dict()
self.assertEqual(d["version"], 1)
self.assertEqual(d["created_by"], "admin@test.com")
# check_policy_intervals_overlap checks
pol_open = TenantOperatingPolicy(**{**valid_args, "effective_from": datetime(2026, 1, 1, tzinfo=timezone.utc), "effective_to": None})
self.assertTrue(check_policy_intervals_overlap([pol_open], datetime(2026, 3, 1, tzinfo=timezone.utc), datetime(2026, 5, 1, tzinfo=timezone.utc)))
self.assertFalse(check_policy_intervals_overlap([pol_open], datetime(2025, 1, 1, tzinfo=timezone.utc), datetime(2025, 12, 31, tzinfo=timezone.utc)))
pol_bounded = TenantOperatingPolicy(**{**valid_args, "effective_from": datetime(2026, 3, 1, tzinfo=timezone.utc), "effective_to": datetime(2026, 6, 1, tzinfo=timezone.utc)})
self.assertTrue(check_policy_intervals_overlap([pol_bounded], datetime(2026, 4, 1, tzinfo=timezone.utc), None))
self.assertFalse(check_policy_intervals_overlap([pol_bounded], datetime(2026, 7, 1, tzinfo=timezone.utc), None))
self.assertTrue(check_policy_intervals_overlap([pol_bounded], datetime(2026, 4, 1, tzinfo=timezone.utc), datetime(2026, 5, 1, tzinfo=timezone.utc)))
self.assertFalse(check_policy_intervals_overlap([pol_bounded], datetime(2026, 7, 1, tzinfo=timezone.utc), datetime(2026, 8, 1, tzinfo=timezone.utc)))
def test_master_data_models_and_variety_godown(self):
"""Domain: CommodityVariety, TradingCounterparty, and Godown validations and to_dict."""
# Variety
with self.assertRaises(ValueError):
CommodityVariety(tenant_id="t1", commodity_id="", code="VAR1", name="Variety 1")
with self.assertRaises(ValueError):
CommodityVariety(tenant_id="t1", commodity_id="c1", code="", name="Variety 1")
with self.assertRaises(ValueError):
CommodityVariety(tenant_id="t1", commodity_id="c1", code="VAR1", name="")
var = CommodityVariety(tenant_id="t1", commodity_id="c1", code="VAR-OK", name="Sharbati")
self.assertEqual(var.to_dict()["code"], "VAR-OK")
# Counterparty
cp_valid = {
"tenant_id": "t1",
"name": "Kisan Farmer",
"counterparty_type": "FARMER",
"pan_number": "ABCDE1234F",
"bank_account_number": "123456789",
"bank_ifsc_code": "SBIN0001234",
"bank_name": "SBI",
"credit_terms_days": 7,
}
with self.assertRaises(ValueError):
TradingCounterparty(**{**cp_valid, "name": ""})
with self.assertRaises(ValueError):
TradingCounterparty(**{**cp_valid, "counterparty_type": "UNKNOWN"})
with self.assertRaises(ValueError):
TradingCounterparty(**{**cp_valid, "pan_number": "INVALIDPAN"})
with self.assertRaises(ValueError):
TradingCounterparty(**{**cp_valid, "bank_account_number": ""})
with self.assertRaises(ValueError):
TradingCounterparty(**{**cp_valid, "bank_ifsc_code": ""})
with self.assertRaises(ValueError):
TradingCounterparty(**{**cp_valid, "bank_name": ""})
with self.assertRaises(ValueError):
TradingCounterparty(**{**cp_valid, "credit_terms_days": 10})
cp = TradingCounterparty(**cp_valid)
self.assertEqual(cp.to_dict()["pan_number"], "ABCDE1234F")
# Godown
g_valid = {
"tenant_id": "t1",
"code": "GDN-01",
"name": "Main Godown",
"address": "Indore Mandi Yard",
"capacity_mt": 1000.0,
}
with self.assertRaises(ValueError):
Godown(**{**g_valid, "code": ""})
with self.assertRaises(ValueError):
Godown(**{**g_valid, "name": ""})
with self.assertRaises(ValueError):
Godown(**{**g_valid, "address": ""})
with self.assertRaises(ValueError):
Godown(**{**g_valid, "capacity_mt": -50.0})
g = Godown(**g_valid)
self.assertEqual(g.to_dict()["capacity_mt"], 1000.0)
def test_support_controller_error_and_edge_paths(self):
"""API Negative & Edge: SupportController unauthenticated, 404, 409, 422, and auto-expire."""
# 401 Unauthenticated
self.assertEqual(self.support_ctrl.request_grant(None, self.tenant_id, {})["status_code"], 401)
self.assertEqual(self.support_ctrl.approve_grant(None, self.tenant_id, "g1")["status_code"], 401)
self.assertEqual(self.support_ctrl.reject_grant(None, self.tenant_id, "g1")["status_code"], 401)
self.assertEqual(self.support_ctrl.revoke_grant(None, self.tenant_id, "g1")["status_code"], 401)
self.assertEqual(self.support_ctrl.break_glass(None, self.tenant_id, {})["status_code"], 401)
self.assertEqual(self.support_ctrl.list_grants(None, self.tenant_id)["status_code"], 401)
# 404 Not Found
self.assertEqual(self.support_ctrl.approve_grant(self.admin_auth_header, self.tenant_id, "nonexistent")["status_code"], 404)
self.assertEqual(self.support_ctrl.reject_grant(self.admin_auth_header, self.tenant_id, "nonexistent")["status_code"], 404)
self.assertEqual(self.support_ctrl.revoke_grant(self.admin_auth_header, self.tenant_id, "nonexistent")["status_code"], 404)
# 422 Validation Errors
res_v1 = self.support_ctrl.request_grant(self.admin_auth_header, self.tenant_id, {"reason": "bad", "duration_minutes": 5})
self.assertEqual(res_v1["status_code"], 422)
res_v2 = self.support_ctrl.break_glass(self.admin_auth_header, self.tenant_id, {"emergency_justification": "short"})
self.assertEqual(res_v2["status_code"], 422)
# State transition 409 Conflict
res_g = self.support_ctrl.request_grant(self.support_auth_header, self.tenant_id, {"reason": "L3 ticket 9982 investigation", "duration_minutes": 60})
self.assertEqual(res_g["status_code"], 201)
g_id = res_g["id"]
# Reject grant
rej_res = self.support_ctrl.reject_grant(self.admin_auth_header, self.tenant_id, g_id)
self.assertEqual(rej_res["status_code"], 200)
# Cannot reject or approve rejected grant -> 409
self.assertEqual(self.support_ctrl.reject_grant(self.admin_auth_header, self.tenant_id, g_id)["status_code"], 409)
self.assertEqual(self.support_ctrl.approve_grant(self.admin_auth_header, self.tenant_id, g_id)["status_code"], 409)
self.assertEqual(self.support_ctrl.revoke_grant(self.admin_auth_header, self.tenant_id, g_id)["status_code"], 409)
# Approve with custom duration validations
res_g2 = self.support_ctrl.request_grant(self.support_auth_header, self.tenant_id, {"reason": "L3 ticket 9983 investigation", "duration_minutes": 60})
g_id2 = res_g2["id"]
self.assertEqual(self.support_ctrl.approve_grant(self.admin_auth_header, self.tenant_id, g_id2, {"duration_minutes": 5})["status_code"], 422)
self.assertEqual(self.support_ctrl.approve_grant(self.admin_auth_header, self.tenant_id, g_id2, {"duration_minutes": "invalid"})["status_code"], 422)
app_res = self.support_ctrl.approve_grant(self.admin_auth_header, self.tenant_id, g_id2, {"duration_minutes": 45})
self.assertEqual(app_res["status_code"], 200)
self.assertEqual(app_res["duration_minutes"], 45)
# Auto-expiry in list_grants
raw_grant = self.store.get("privileged_support_grants", self.tenant_id, g_id2)
raw_grant["expires_at"] = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
self.store.update("privileged_support_grants", self.tenant_id, g_id2, raw_grant)
list_res = self.support_ctrl.list_grants(self.admin_auth_header, self.tenant_id)
self.assertEqual(list_res["status_code"], 200)
found = [g for g in list_res["grants"] if g["id"] == g_id2][0]
self.assertEqual(found["status"], "EXPIRED")
def test_policy_controller_error_and_edge_paths(self):
"""API Negative & Edge: PolicyController unauthenticated, 409 overlap, 422 formatting, and auto_close."""
# 401 Unauthenticated
self.assertEqual(self.policy_ctrl.create_policy(None, self.tenant_id, {})["status_code"], 401)
self.assertEqual(self.policy_ctrl.get_effective_policy(None, self.tenant_id)["status_code"], 401)
self.assertEqual(self.policy_ctrl.list_policies(None, self.tenant_id)["status_code"], 401)
# 422 Validation
self.assertEqual(self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, {})["status_code"], 422)
self.assertEqual(self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, {"effective_from": "not-a-date"})["status_code"], 422)
self.assertEqual(self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, {"effective_from": "2026-01-01T00:00:00Z", "effective_to": "bad-date"})["status_code"], 422)
self.assertEqual(self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, {
"effective_from": "2026-01-01T00:00:00Z",
"change_reason": "bad threshold",
"weighbridge_tolerance_pct": 15.0,
})["status_code"], 422)
self.assertEqual(self.policy_ctrl.get_effective_policy(self.admin_auth_header, self.tenant_id, as_of="bad-as-of")["status_code"], 422)
# Create open-ended policy v1
p1_res = self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, {
"effective_from": "2026-01-01T00:00:00Z",
"change_reason": "Policy version 1 baseline",
"weighbridge_tolerance_pct": 0.50,
})
self.assertEqual(p1_res["status_code"], 201)
# Overlapping policy without auto_close_prior -> 409 Conflict
p2_fail = self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, {
"effective_from": "2026-07-01T00:00:00Z",
"change_reason": "Policy version 2 attempt without autoclose",
})
self.assertEqual(p2_fail["status_code"], 409)
# Overlapping policy WITH auto_close_prior -> 201 Success
p2_ok = self.policy_ctrl.create_policy(self.admin_auth_header, self.tenant_id, {
"effective_from": "2026-07-01T00:00:00Z",
"change_reason": "Policy version 2 with auto close",
"auto_close_prior": True,
"weighbridge_tolerance_pct": 0.40,
})
self.assertEqual(p2_ok["status_code"], 201)
# Verify list_policies
list_res = self.policy_ctrl.list_policies(self.admin_auth_header, self.tenant_id)
self.assertEqual(list_res["status_code"], 200)
self.assertGreaterEqual(list_res["count"], 2)
# Effective as-of query
eff_past = self.policy_ctrl.get_effective_policy(self.admin_auth_header, self.tenant_id, as_of="2026-03-01T00:00:00Z")
self.assertEqual(eff_past["weighbridge_tolerance_pct"], 0.50)
eff_new = self.policy_ctrl.get_effective_policy(self.admin_auth_header, self.tenant_id, as_of="2026-08-01T00:00:00Z")
self.assertEqual(eff_new["weighbridge_tolerance_pct"], 0.40)
def test_master_data_controller_error_and_edge_paths(self):
"""API Negative & Edge: MasterDataController unauthenticated, 404, 409, 422, and filters."""
# 401 Unauthenticated
self.assertEqual(self.master_ctrl.create_commodity(None, self.tenant_id, {})["status_code"], 401)
self.assertEqual(self.master_ctrl.get_commodity(None, self.tenant_id, "c1")["status_code"], 401)
self.assertEqual(self.master_ctrl.update_commodity(None, self.tenant_id, "c1", {})["status_code"], 401)
self.assertEqual(self.master_ctrl.delete_commodity(None, self.tenant_id, "c1")["status_code"], 401)
self.assertEqual(self.master_ctrl.list_commodities(None, self.tenant_id)["status_code"], 401)
self.assertEqual(self.master_ctrl.add_variety(None, self.tenant_id, "c1", {})["status_code"], 401)
self.assertEqual(self.master_ctrl.create_counterparty(None, self.tenant_id, {})["status_code"], 401)
self.assertEqual(self.master_ctrl.list_counterparties(None, self.tenant_id)["status_code"], 401)
self.assertEqual(self.master_ctrl.create_godown(None, self.tenant_id, {})["status_code"], 401)
self.assertEqual(self.master_ctrl.list_godowns(None, self.tenant_id)["status_code"], 401)
# 404 Not Found
self.assertEqual(self.master_ctrl.get_commodity(self.admin_auth_header, self.tenant_id, "nonexistent")["status_code"], 404)
self.assertEqual(self.master_ctrl.update_commodity(self.admin_auth_header, self.tenant_id, "nonexistent", {})["status_code"], 404)
self.assertEqual(self.master_ctrl.delete_commodity(self.admin_auth_header, self.tenant_id, "nonexistent")["status_code"], 404)
self.assertEqual(self.master_ctrl.add_variety(self.admin_auth_header, self.tenant_id, "nonexistent", {})["status_code"], 404)
# 422 Validation
self.assertEqual(self.master_ctrl.create_commodity(self.admin_auth_header, self.tenant_id, {})["status_code"], 422)
self.assertEqual(self.master_ctrl.create_commodity(self.admin_auth_header, self.tenant_id, {"code": "SOY-ERR", "name": ""})["status_code"], 422)
self.assertEqual(self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, {})["status_code"], 422)
self.assertEqual(self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, {"pan_number": "ABCDE1234F", "name": ""})["status_code"], 422)
self.assertEqual(self.master_ctrl.create_godown(self.admin_auth_header, self.tenant_id, {})["status_code"], 422)
self.assertEqual(self.master_ctrl.create_godown(self.admin_auth_header, self.tenant_id, {"code": "GDN-ERR", "name": ""})["status_code"], 422)
# 409 Conflict checks (duplicates)
c_res = self.master_ctrl.create_commodity(self.admin_auth_header, self.tenant_id, {"code": "MUSTARD-TEST", "name": "Mustard Test"})
self.assertEqual(c_res["status_code"], 201)
c_id = c_res["id"]
# Duplicate commodity code
self.assertEqual(self.master_ctrl.create_commodity(self.admin_auth_header, self.tenant_id, {"code": "MUSTARD-TEST", "name": "Mustard 2"})["status_code"], 409)
# Varieties
self.assertEqual(self.master_ctrl.add_variety(self.admin_auth_header, self.tenant_id, c_id, {})["status_code"], 422)
v_res = self.master_ctrl.add_variety(self.admin_auth_header, self.tenant_id, c_id, {"code": "PUSA-BOLD", "name": "Pusa Bold"})
self.assertEqual(v_res["status_code"], 201)
# Duplicate variety code
self.assertEqual(self.master_ctrl.add_variety(self.admin_auth_header, self.tenant_id, c_id, {"code": "PUSA-BOLD", "name": "Pusa Bold 2"})["status_code"], 409)
# Duplicate counterparty PAN
cp_payload = {
"name": "Patel Traders",
"counterparty_type": "PROCESSOR",
"pan_number": "PATEL1234F",
"bank_account_number": "9876543210",
"bank_ifsc_code": "HDFC0001234",
"bank_name": "HDFC Bank",
"credit_terms_days": 15,
}
self.assertEqual(self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, cp_payload)["status_code"], 201)
self.assertEqual(self.master_ctrl.create_counterparty(self.admin_auth_header, self.tenant_id, cp_payload)["status_code"], 409)
# Duplicate godown code
g_payload = {
"code": "GDN-INDORE-01",
"name": "Indore Godown 1",
"address": "Sector 4",
"capacity_mt": 5000.0,
}
self.assertEqual(self.master_ctrl.create_godown(self.admin_auth_header, self.tenant_id, g_payload)["status_code"], 201)
self.assertEqual(self.master_ctrl.create_godown(self.admin_auth_header, self.tenant_id, g_payload)["status_code"], 409)
# Search & Filtering
comm_list = self.master_ctrl.list_commodities(self.admin_auth_header, self.tenant_id)
self.assertEqual(comm_list["status_code"], 200)
cp_list = self.master_ctrl.list_counterparties(self.admin_auth_header, self.tenant_id, counterparty_type="PROCESSOR")
self.assertEqual(cp_list["status_code"], 200)
self.assertEqual(len(cp_list["counterparties"]), 1)
g_list = self.master_ctrl.list_godowns(self.admin_auth_header, self.tenant_id)
self.assertEqual(g_list["status_code"], 200)
self.assertEqual(len(g_list["godowns"]), 1)
if __name__ == "__main__":
unittest.main()