File size: 15,156 Bytes
aef804e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | """
Financial Audit API Integration Tests - Phase 94-05
Integration tests for financial audit API endpoints.
Tests verify:
- Compliance validation endpoint (all 5 AUD requirements)
- Compliance report generation (json/summary/detailed)
- Audit trail export with hash chain verification
- Health metrics endpoint (0-100 score)
- Hash chain verification endpoint
- Gap detection endpoint
All endpoints use FinancialAuditOrchestrator for unified operations.
"""
import pytest
from fastapi.testclient import TestClient
from datetime import datetime, timedelta
from decimal import Decimal
from unittest.mock import Mock
import uuid
from sqlalchemy.orm import Session
from core.models import (
FinancialAudit, FinancialAccount, User, AgentRegistry,
AgentExecution
)
from main_api_app import app
from core.database import get_db
# ==================== FIXTURES ====================
@pytest.fixture
def client(db_session):
"""Test client with database override."""
def override_get_db():
try:
yield db_session
finally:
pass
app.dependency_overrides[get_db] = override_get_db
return TestClient(app)
@pytest.fixture
def test_user(db_session: Session):
"""Create test user."""
user = User(
id=str(uuid.uuid4()),
email="api_test@example.com"
)
db_session.add(user)
db_session.commit()
return user
@pytest.fixture
def test_account(db_session: Session, test_user: User):
"""Create test financial account."""
account = FinancialAccount(
id=str(uuid.uuid4()),
user_id=test_user.id,
name="API Test Account",
balance=Decimal("1000.00"),
account_type="checking"
)
db_session.add(account)
db_session.commit()
return account
# ==================== TEST CLASS ====================
@pytest.mark.usefixtures("db_session")
class TestFinancialAuditAPI:
"""Integration tests for financial audit API endpoints."""
@pytest.fixture(autouse=True)
def setup(self, db_session, client):
"""Setup test dependencies."""
self.db = db_session
self.client = client
# ========================================================================
# Test: Compliance Validation Endpoint
# ========================================================================
def test_validate_compliance_endpoint(self, test_account):
"""
Verify: GET /api/v1/financial-audit/validate returns compliance status.
"""
# Call API
response = self.client.get("/api/v1/financial-audit/validate")
assert response.status_code == 200
data = response.json()
# Verify response structure
assert 'validated_at' in data
assert 'overall_compliant' in data
assert 'requirements' in data
assert 'summary' in data
# Verify all 5 AUD requirements present
assert 'AUD-01' in data['requirements']
assert 'AUD-02' in data['requirements']
assert 'AUD-03' in data['requirements']
assert 'AUD-04' in data['requirements']
assert 'AUD-05' in data['requirements']
# Verify each requirement has required fields
for req_id, req_data in data['requirements'].items():
assert 'name' in req_data
assert 'description' in req_data
assert 'compliant' in req_data
def test_validate_compliance_with_account_filter(self, test_account):
"""
Verify: Compliance validation accepts account_id filter.
"""
response = self.client.get(
f"/api/v1/financial-audit/validate?account_id={test_account.id}"
)
assert response.status_code == 200
data = response.json()
# Verify account filter applied
assert data['account_id'] == test_account.id
def test_validate_compliance_with_time_range(self, test_account):
"""
Verify: Compliance validation accepts time range filters.
"""
start_time = datetime.utcnow() - timedelta(days=7)
end_time = datetime.utcnow()
response = self.client.get(
f"/api/v1/financial-audit/validate"
f"?start_time={start_time.isoformat()}"
f"&end_time={end_time.isoformat()}"
)
assert response.status_code == 200
data = response.json()
# Verify time range applied
assert data['time_range']['start'] == start_time.isoformat()
assert data['time_range']['end'] == end_time.isoformat()
# ========================================================================
# Test: Compliance Report Endpoint
# ========================================================================
def test_compliance_report_endpoint_json(self):
"""
Verify: GET /api/v1/financial-audit/compliance returns compliance report.
"""
response = self.client.get("/api/v1/financial-audit/compliance?format=json")
assert response.status_code == 200
data = response.json()
# Verify report structure
assert 'generated_at' in data
assert 'report_type' in data
assert 'format' in data
assert 'statistics' in data
assert 'model_coverage' in data
assert 'compliance' in data
assert 'recommendations' in data
# Verify statistics
stats = data['statistics']
assert 'total_audits' in stats
assert 'by_action_type' in stats
assert 'success_rate' in stats
def test_compliance_report_endpoint_summary(self):
"""
Verify: Compliance report supports summary format.
"""
response = self.client.get("/api/v1/financial-audit/compliance?format=summary")
assert response.status_code == 200
data = response.json()
# Verify simplified report structure
assert 'generated_at' in data
assert 'overall_compliant' in data
assert 'total_audits' in data
assert 'compliant_requirements' in data
assert 'total_requirements' in data
assert 'recommendations' in data
# Verify detailed fields not present in summary
assert 'statistics' not in data
assert 'model_coverage' not in data
# ========================================================================
# Test: Audit Trail Export Endpoint
# ========================================================================
def test_audit_trail_export_endpoint(self, test_account):
"""
Verify: GET /api/v1/financial-audit/trail/{account_id} exports audit trail.
"""
# Call API
response = self.client.get(
f"/api/v1/financial-audit/trail/{test_account.id}"
)
assert response.status_code == 200
data = response.json()
# Verify export structure
assert 'export_metadata' in data
assert 'audit_entries' in data
assert 'verification' in data
# Verify metadata
metadata = data['export_metadata']
assert metadata['account_id'] == test_account.id
assert metadata['total_entries'] >= 0
assert metadata['include_hash_chains'] is True
# Verify entries have required fields (if any exist)
entries = data['audit_entries']
for entry in entries:
assert 'id' in entry
assert 'timestamp' in entry
assert 'sequence_number' in entry
assert 'account_id' in entry
assert 'action_type' in entry
assert 'integrity' in entry # Hash chain data
assert 'entry_hash' in entry['integrity']
def test_audit_trail_export_with_time_range(self, test_account):
"""
Verify: Audit trail export accepts time range filters.
"""
start_time = datetime.utcnow() - timedelta(days=1)
end_time = datetime.utcnow()
response = self.client.get(
f"/api/v1/financial-audit/trail/{test_account.id}"
f"?start_time={start_time.isoformat()}"
f"&end_time={end_time.isoformat()}"
)
assert response.status_code == 200
data = response.json()
# Verify time range in metadata
metadata = data['export_metadata']
assert metadata['time_range']['start'] == start_time.isoformat()
assert metadata['time_range']['end'] == end_time.isoformat()
def test_audit_trail_export_without_hash_chains(self, test_account):
"""
Verify: Audit trail export can exclude hash chain data.
"""
response = self.client.get(
f"/api/v1/financial-audit/trail/{test_account.id}?include_hash_chains=false"
)
assert response.status_code == 200
data = response.json()
# Verify hash chains excluded
assert data['export_metadata']['include_hash_chains'] is False
# Entries should not have integrity field
for entry in data['audit_entries']:
assert 'integrity' not in entry
# ========================================================================
# Test: Health Metrics Endpoint
# ========================================================================
def test_health_metrics_endpoint_default(self):
"""
Verify: GET /api/v1/financial-audit/health returns health metrics.
"""
response = self.client.get("/api/v1/financial-audit/health")
assert response.status_code == 200
data = response.json()
# Verify health structure
assert 'period_days' in data
assert 'period_start' in data
assert 'period_end' in data
assert 'health_score' in data
assert 'total_audits' in data
assert 'success_rate' in data
assert 'issues_detected' in data
# Verify health score is between 0 and 100
assert 0 <= data['health_score'] <= 100
# Verify issues structure
issues = data['issues_detected']
assert 'sequence_gaps' in issues
assert 'hash_chain_breaks' in issues
assert 'tampered_accounts' in issues
def test_health_metrics_endpoint_custom_days(self):
"""
Verify: Health metrics accepts custom period.
"""
response = self.client.get("/api/v1/financial-audit/health?days=7")
assert response.status_code == 200
data = response.json()
# Verify custom period applied
assert data['period_days'] == 7
def test_health_metrics_days_validation(self):
"""
Verify: Health metrics validates days parameter (1-365).
"""
# Test invalid days (too large)
response = self.client.get("/api/v1/financial-audit/health?days=400")
# Should return validation error
assert response.status_code == 422 # Unprocessable Entity
# ========================================================================
# Test: Hash Chain Verification Endpoint
# ========================================================================
def test_hash_chain_verification_endpoint(self, test_account):
"""
Verify: GET /api/v1/financial-audit/verify/{account_id} verifies hash chains.
"""
response = self.client.get(
f"/api/v1/financial-audit/verify/{test_account.id}"
)
assert response.status_code == 200
data = response.json()
# Verify verification structure
assert 'is_valid' in data
assert 'total_entries' in data
assert 'break_count' in data
def test_hash_chain_verification_with_sequence_range(self, test_account):
"""
Verify: Hash chain verification accepts sequence range.
"""
response = self.client.get(
f"/api/v1/financial-audit/verify/{test_account.id}"
f"?start_sequence=1"
f"&end_sequence=10"
)
assert response.status_code == 200
data = response.json()
# Verify response structure
assert 'is_valid' in data
assert 'total_entries' in data
# ========================================================================
# Test: Gap Detection Endpoint
# ========================================================================
def test_gap_detection_endpoint_all_accounts(self):
"""
Verify: GET /api/v1/financial-audit/gaps detects sequence gaps.
"""
response = self.client.get("/api/v1/financial-audit/gaps")
assert response.status_code == 200
data = response.json()
# Verify gap detection structure
assert 'has_gaps' in data
assert 'gaps' in data
assert 'total_gaps' in data
assert 'accounts_with_gaps' in data
assert 'checked_at' in data
def test_gap_detection_endpoint_account_filter(self, test_account):
"""
Verify: Gap detection accepts account filter.
"""
response = self.client.get(
f"/api/v1/financial-audit/gaps?account_id={test_account.id}"
)
assert response.status_code == 200
data = response.json()
# Verify response structure
assert 'has_gaps' in data
assert 'gaps' in data
assert isinstance(data['gaps'], list)
def test_gap_detection_endpoint_with_time_range(self, test_account):
"""
Verify: Gap detection accepts time range filters.
"""
start_time = datetime.utcnow() - timedelta(days=7)
end_time = datetime.utcnow()
response = self.client.get(
f"/api/v1/financial-audit/gaps"
f"?account_id={test_account.id}"
f"&start_time={start_time.isoformat()}"
f"&end_time={end_time.isoformat()}"
)
assert response.status_code == 200
data = response.json()
# Verify response structure
assert 'has_gaps' in data
assert 'checked_at' in data
# ========================================================================
# Test: Error Handling
# ========================================================================
def test_validate_endpoint_handles_errors(self, test_account):
"""
Verify: Compliance validation endpoint handles errors gracefully.
"""
# This test verifies the endpoint doesn't crash on empty database
response = self.client.get("/api/v1/financial-audit/validate")
# Should succeed even with no data
assert response.status_code == 200
def test_export_endpoint_for_nonexistent_account(self):
"""
Verify: Export endpoint handles nonexistent account.
"""
fake_account_id = str(uuid.uuid4())
response = self.client.get(
f"/api/v1/financial-audit/trail/{fake_account_id}"
)
# Should return 200 with empty entries (not 404)
assert response.status_code == 200
data = response.json()
assert data['export_metadata']['total_entries'] == 0
assert len(data['audit_entries']) == 0
|