Buckets:

download
raw
21.1 kB
"""
Performance Benchmark Tests
==========================
Comprehensive performance benchmarks for:
- Database operations
- Tool execution speed
- API response times
- Agent coordination
- Memory usage
Uses pytest-benchmark for consistent measurements.
"""
import asyncio
import gc
import json
import os
import time
import timeit
import tracemalloc
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, List
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
# Try to import pytest-benchmark, fallback to simple timing
try:
import pytest_benchmark
HAS_BENCHMARK = True
except ImportError:
HAS_BENCHMARK = False
# Simple benchmark fixture fallback
@pytest.fixture
def benchmark():
"""Simple benchmark fixture that works without pytest-benchmark"""
class SimpleBenchmark:
def __call__(self, func, *args, **kwargs):
# Run once to warm up
result = func(*args, **kwargs)
# Run timing
timer = timeit.Timer(lambda: func(*args, **kwargs))
# Store stats for potential assertions
self.stats = {"mean": timer.timeit(number=10) / 10}
return result
return SimpleBenchmark()
# =============================================================================
# DATABASE PERFORMANCE BENCHMARKS
# =============================================================================
class TestDatabaseBenchmarks:
"""Database operation benchmarks"""
@pytest.mark.benchmark
def test_insert_single_scan(self, benchmark):
"""Benchmark single scan insert"""
def insert_scan():
# Simulate database insert
data = {
"id": "scan-123",
"name": "Test Scan",
"target": "example.com",
"status": "pending",
"created_at": time.time(),
}
# Simulated DB operation
return data
result = benchmark(insert_scan)
assert result["id"] == "scan-123"
@pytest.mark.benchmark
def test_insert_100_scans(self, benchmark):
"""Benchmark batch scan insert"""
def insert_100():
scans = []
for i in range(100):
scans.append(
{
"id": f"scan-{i}",
"name": f"Scan {i}",
"target": f"target{i}.com",
}
)
return len(scans)
result = benchmark(insert_100)
assert result == 100
@pytest.mark.benchmark
def test_query_by_id(self, benchmark):
"""Benchmark query by ID"""
# Setup mock data
scans = {f"scan-{i}": {"id": f"scan-{i}"} for i in range(1000)}
def query_scan():
return scans.get("scan-500")
result = benchmark(query_scan)
assert result["id"] == "scan-500"
@pytest.mark.benchmark
def test_query_by_status(self, benchmark):
"""Benchmark query by status with filtering"""
scans = [{"id": f"scan-{i}", "status": "completed" if i % 2 == 0 else "pending"} for i in range(1000)]
def filter_by_status():
return [s for s in scans if s["status"] == "completed"]
result = benchmark(filter_by_status)
assert len(result) == 500
@pytest.mark.benchmark
def test_bulk_insert_findings(self, benchmark):
"""Benchmark bulk insert of findings"""
def bulk_insert():
findings = []
for i in range(1000):
findings.append(
{
"id": f"finding-{i}",
"title": f"Finding {i}",
"severity": ["low", "medium", "high", "critical"][i % 4],
}
)
return len(findings)
result = benchmark(bulk_insert)
assert result == 1000
@pytest.mark.asyncio
@pytest.mark.benchmark
async def test_async_query_performance(self, benchmark):
"""Benchmark async query performance"""
async def async_query():
await asyncio.sleep(0.001) # Simulate DB latency
return [{"id": i} for i in range(100)]
# Run benchmark
start = time.perf_counter()
result = await async_query()
elapsed = time.perf_counter() - start
assert len(result) == 100
assert elapsed < 0.1 # Should complete within 100ms
# =============================================================================
# TOOL EXECUTION BENCHMARKS
# =============================================================================
class TestToolBenchmarks:
"""Security tool execution benchmarks"""
@pytest.mark.benchmark
def test_nmap_command_build(self, benchmark):
"""Benchmark Nmap command building"""
import shutil
if not shutil.which("nmap"):
pytest.skip("nmap not installed")
from tools.nmap_integration import NmapScanner
nmap = NmapScanner(target="scanme.nmap.org")
def build_command():
return nmap._build_command(ports="22,80,443,8080", scan_type="syn", service_detection=True)
result = benchmark(build_command)
assert "-sS" in result
@pytest.mark.benchmark
def test_nmap_xml_parsing(self, benchmark):
"""Benchmark Nmap XML parsing"""
import shutil
if not shutil.which("nmap"):
pytest.skip("nmap not installed")
from tools.nmap_integration import NmapScanner
nmap = NmapScanner(target="scanme.nmap.org")
xml = """<?xml version="1.0"?>
<nmaprun>
<host><status state="up"/><address addr="1.2.3.4" addrtype="ipv4"/>
<ports><port portid="80"><state state="open"/><service name="http"/></port></ports>
</host>
</nmaprun>"""
def parse_xml():
return nmap._parse_nmaprun(xml)
result = benchmark(parse_xml)
assert len(result.hosts) == 1
@pytest.mark.benchmark
def test_json_parsing_benchmark(self, benchmark):
"""Benchmark JSON parsing for tool outputs"""
data = {"findings": [{"id": i, "severity": "high", "title": f"Finding {i}"} for i in range(100)]}
json_str = json.dumps(data)
def parse_json():
return json.loads(json_str)
result = benchmark(parse_json)
assert len(result["findings"]) == 100
@pytest.mark.asyncio
@pytest.mark.benchmark
async def test_concurrent_tool_execution(self, benchmark):
"""Benchmark concurrent tool execution"""
async def run_concurrent():
async def mock_tool(duration):
await asyncio.sleep(duration)
return {"status": "completed"}
tasks = [mock_tool(0.01) for _ in range(10)]
results = await asyncio.gather(*tasks)
return len(results)
start = time.perf_counter()
result = await run_concurrent()
elapsed = time.perf_counter() - start
assert result == 10
assert elapsed < 0.5 # Should complete within 500ms
# =============================================================================
# API PERFORMANCE BENCHMARKS
# =============================================================================
class TestAPIBenchmarks:
"""API endpoint performance benchmarks"""
@pytest.mark.benchmark
def test_health_endpoint(self, benchmark):
"""Benchmark health check endpoint"""
def health_check():
return {"status": "healthy", "timestamp": time.time()}
result = benchmark(health_check)
assert result["status"] == "healthy"
@pytest.mark.benchmark
def test_scan_list_serialization(self, benchmark):
"""Benchmark scan list JSON serialization"""
scans = [
{
"id": f"scan-{i}",
"name": f"Scan {i}",
"target": f"target{i}.com",
"status": "completed",
"findings_count": i * 10,
}
for i in range(100)
]
def serialize():
return json.dumps({"scans": scans, "total": len(scans)})
result = benchmark(serialize)
assert len(result) > 1000
@pytest.mark.benchmark
def test_scan_filtering(self, benchmark):
"""Benchmark scan filtering logic"""
scans = [{"id": f"scan-{i}", "status": ["pending", "running", "completed"][i % 3]} for i in range(500)]
def filter_completed():
return [s for s in scans if s["status"] == "completed"]
result = benchmark(filter_completed)
assert len(result) in [166, 167] # ~1/3 of 500
@pytest.mark.benchmark
def test_jwt_encode_decode(self, benchmark):
"""Benchmark JWT token operations"""
import hashlib
import hmac
payload = {"user_id": "123", "exp": time.time() + 3600}
secret = "test-secret-key"
def jwt_operation():
# Simplified JWT-like operation
data = json.dumps(payload)
signature = hmac.new(secret.encode(), data.encode(), hashlib.sha256).hexdigest()
return f"{data}.{signature}"
result = benchmark(jwt_operation)
assert "." in result
# =============================================================================
# AGENT PERFORMANCE BENCHMARKS
# =============================================================================
class TestAgentBenchmarks:
"""Agent coordination performance benchmarks"""
@pytest.mark.benchmark
def test_message_creation(self, benchmark):
"""Benchmark message creation"""
def create_message():
return {
"id": f"msg-{time.time()}",
"sender": "agent1",
"receiver": "agent2",
"type": "request",
"payload": {"action": "scan", "target": "example.com"},
"timestamp": time.time(),
}
result = benchmark(create_message)
assert result["sender"] == "agent1"
@pytest.mark.benchmark
def test_agent_routing_decision(self, benchmark):
"""Benchmark agent routing decision"""
agents = {f"agent-{i}": {"load": i % 10} for i in range(20)}
def route_to_agent():
# Find agent with lowest load
return min(agents.items(), key=lambda x: x[1]["load"])
result = benchmark(route_to_agent)
assert result[0].startswith("agent-")
@pytest.mark.asyncio
@pytest.mark.benchmark
async def test_agent_message_throughput(self, benchmark):
"""Benchmark message throughput"""
async def process_messages():
processed = 0
for i in range(100):
await asyncio.sleep(0.001) # Simulate processing
processed += 1
return processed
start = time.perf_counter()
result = await process_messages()
elapsed = time.perf_counter() - start
assert result == 100
# Should process 100 messages
@pytest.mark.benchmark
def test_findings_aggregation(self, benchmark):
"""Benchmark findings aggregation"""
findings = [{"severity": ["low", "medium", "high", "critical"][i % 4], "title": f"Finding {i}"} for i in range(1000)]
def aggregate():
severity_counts = {"low": 0, "medium": 0, "high": 0, "critical": 0}
for f in findings:
severity_counts[f["severity"]] += 1
return severity_counts
result = benchmark(aggregate)
assert sum(result.values()) == 1000
# =============================================================================
# MEMORY BENCHMARKS
# =============================================================================
class TestMemoryBenchmarks:
"""Memory usage benchmarks"""
@pytest.mark.benchmark
def test_large_scan_result_handling(self, benchmark):
"""Benchmark handling of large scan results"""
def create_large_result():
return {
"hosts": [
{"ip": f"192.168.1.{i}", "ports": [{"port": p, "state": "open"} for p in range(1000)]} for i in range(10)
]
}
result = benchmark(create_large_result)
assert len(result["hosts"]) == 10
@pytest.mark.benchmark
def test_memory_efficient_iteration(self, benchmark):
"""Benchmark memory-efficient iteration"""
def iterate_efficiently():
count = 0
# Generator instead of list
for i in range(10000):
count += 1
return count
result = benchmark(iterate_efficiently)
assert result == 10000
def test_memory_allocation(self):
"""Test memory allocation for key operations"""
tracemalloc.start()
# Operation to measure
data = [{"id": i, "data": "x" * 100} for i in range(1000)]
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
# Memory should be reasonable (< 50MB)
assert peak < 50 * 1024 * 1024
# =============================================================================
# ORCHESTRATOR PERFORMANCE BENCHMARKS
# =============================================================================
class TestOrchestratorBenchmarks:
"""Orchestrator performance benchmarks"""
@pytest.mark.benchmark
def test_backend_selection(self, benchmark):
"""Benchmark backend selection"""
backends = {
"kimi": {"priority": 1, "available": True},
"openai": {"priority": 2, "available": True},
"anthropic": {"priority": 3, "available": False},
}
def select_backend():
available = {k: v for k, v in backends.items() if v["available"]}
return min(available.items(), key=lambda x: x[1]["priority"])[0]
result = benchmark(select_backend)
assert result == "kimi"
@pytest.mark.benchmark
def test_workflow_execution_planning(self, benchmark):
"""Benchmark workflow execution planning"""
def plan_workflow():
steps = [
{"name": "recon", "tools": ["subfinder", "amass"]},
{"name": "scan", "tools": ["nmap", "nuclei"]},
{"name": "exploit", "tools": ["sqlmap"]},
{"name": "report", "tools": ["generate_report"]},
]
return steps
result = benchmark(plan_workflow)
assert len(result) == 4
@pytest.mark.benchmark
def test_consensus_calculation(self, benchmark):
"""Benchmark consensus calculation"""
results = [
{"finding": "SQLi", "confidence": 0.9},
{"finding": "SQLi", "confidence": 0.8},
{"finding": "XSS", "confidence": 0.6},
]
def calculate_consensus():
findings = {}
for r in results:
key = r["finding"]
findings[key] = findings.get(key, 0) + r["confidence"]
return max(findings.items(), key=lambda x: x[1])
result = benchmark(calculate_consensus)
assert result[0] == "SQLi"
# =============================================================================
# THROUGHPUT BENCHMARKS
# =============================================================================
class TestThroughputBenchmarks:
"""System throughput benchmarks"""
@pytest.mark.asyncio
async def test_requests_per_second(self):
"""Test requests per second throughput"""
async def mock_request():
await asyncio.sleep(0.01) # 10ms per request
return {"status": "ok"}
start = time.perf_counter()
tasks = [mock_request() for _ in range(100)]
results = await asyncio.gather(*tasks)
elapsed = time.perf_counter() - start
rps = len(results) / elapsed
assert rps > 50 # At least 50 requests per second
@pytest.mark.asyncio
async def test_concurrent_agent_scaling(self):
"""Test concurrent agent scaling"""
async def agent_task(agent_id):
await asyncio.sleep(0.05) # 50ms work
return f"agent-{agent_id}-done"
start = time.perf_counter()
tasks = [agent_task(i) for i in range(50)]
results = await asyncio.gather(*tasks)
elapsed = time.perf_counter() - start
# 50 agents should complete in ~1 second (with async)
assert elapsed < 2.0
assert len(results) == 50
def test_data_processing_throughput(self):
"""Test data processing throughput"""
data = [{"id": i, "value": i * 2} for i in range(10000)]
start = time.perf_counter()
processed = [d["value"] * 2 for d in data]
elapsed = time.perf_counter() - start
# Should process 10k records quickly
assert elapsed < 1.0
assert len(processed) == 10000
# =============================================================================
# LATENCY BENCHMARKS
# =============================================================================
class TestLatencyBenchmarks:
"""Latency-specific benchmarks"""
@pytest.mark.asyncio
async def test_api_response_latency_p95(self):
"""Test API response latency at P95"""
latencies = []
for _ in range(100):
start = time.perf_counter()
await asyncio.sleep(0.001) # Simulate 1ms operation
elapsed = (time.perf_counter() - start) * 1000
latencies.append(elapsed)
latencies.sort()
p95 = latencies[int(len(latencies) * 0.95)]
assert p95 < 10 # P95 should be under 10ms
@pytest.mark.asyncio
async def test_database_query_latency(self):
"""Test database query latency"""
async def db_query():
await asyncio.sleep(0.005) # Simulate 5ms DB query
return {"rows": 10}
start = time.perf_counter()
result = await db_query()
elapsed = (time.perf_counter() - start) * 1000
assert elapsed < 20 # Should be under 20ms
def test_tool_startup_latency(self):
"""Test tool startup latency"""
start = time.perf_counter()
# Simulate tool initialization
tool = {"name": "nmap", "ready": True}
elapsed = (time.perf_counter() - start) * 1000
assert elapsed < 100 # Should start in under 100ms
# =============================================================================
# COMPARATIVE BENCHMARKS
# =============================================================================
class TestComparativeBenchmarks:
"""Comparative benchmarks (baseline vs current)"""
@pytest.mark.benchmark
def test_dict_vs_dataclass_creation(self, benchmark):
"""Compare dict vs dataclass creation performance"""
from dataclasses import dataclass
@dataclass
class Finding:
id: str
title: str
severity: str
def create_dict():
return {"id": "1", "title": "Test", "severity": "high"}
def create_dataclass():
return Finding("1", "Test", "high")
# Both should be fast
dict_result = benchmark(create_dict)
dc_result = create_dataclass()
assert dict_result["id"] == "1"
assert dc_result.id == "1"
@pytest.mark.benchmark
def test_list_vs_set_lookup(self, benchmark):
"""Compare list vs set lookup performance"""
items_list = [f"item-{i}" for i in range(1000)]
items_set = set(items_list)
def list_lookup():
return "item-999" in items_list
def set_lookup():
return "item-999" in items_set
# Set should be faster, but both should work
list_result = benchmark(list_lookup)
set_result = set_lookup()
assert list_result
assert set_result
@pytest.mark.benchmark
def test_json_vs_msgpack(self, benchmark):
"""Compare JSON vs MessagePack serialization"""
data = {"findings": [{"id": i, "data": "x" * 100} for i in range(100)]}
def json_serialize():
return json.dumps(data)
result = benchmark(json_serialize)
assert len(result) > 0
# =============================================================================
# PERFORMANCE THRESHOLDS
# =============================================================================
PERFORMANCE_THRESHOLDS = {
"max_query_time_ms": 100,
"max_insert_time_ms": 50,
"max_api_latency_ms": 50,
"min_throughput_rps": 50,
"max_memory_mb": 512,
}
def test_performance_thresholds_documented():
"""Verify performance thresholds are documented"""
assert "max_query_time_ms" in PERFORMANCE_THRESHOLDS
assert "max_api_latency_ms" in PERFORMANCE_THRESHOLDS
assert PERFORMANCE_THRESHOLDS["max_query_time_ms"] == 100

Xet Storage Details

Size:
21.1 kB
·
Xet hash:
31d7d3d11fc128b4716c0ee2945d3bdbd94340a33f84bc3aede513493f3dfa73

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.