File size: 19,545 Bytes
892c7af | 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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 | """
Unit tests for Pydantic models with validation and security tests
"""
import pytest
from datetime import datetime, timezone
from pydantic import ValidationError
from models import (
ReliabilityEvent,
EventSeverity,
HealingPolicy,
HealingAction,
PolicyCondition,
AnomalyResult,
ForecastResult
)
class TestReliabilityEventValidation:
"""Test ReliabilityEvent validation"""
def test_valid_event_creation(self):
"""Test creating a valid event"""
event = ReliabilityEvent(
component="api-service",
latency_p99=150.0,
error_rate=0.05,
throughput=1000.0,
cpu_util=0.7,
memory_util=0.6
)
assert event.component == "api-service"
assert event.latency_p99 == 150.0
assert event.error_rate == 0.05
assert isinstance(event.timestamp, datetime)
assert event.severity == EventSeverity.LOW
def test_component_validation_valid(self):
"""Test valid component IDs"""
valid_ids = ["api-service", "auth-service", "payment-service-v2", "db-01"]
for component_id in valid_ids:
event = ReliabilityEvent(
component=component_id,
latency_p99=100.0,
error_rate=0.01,
throughput=1000.0
)
assert event.component == component_id
def test_component_validation_invalid(self):
"""Test invalid component IDs are rejected"""
invalid_ids = [
"API-SERVICE", # Uppercase
"api_service", # Underscore
"api service", # Space
"api@service", # Special char
"", # Empty
]
for component_id in invalid_ids:
with pytest.raises(ValidationError) as exc_info:
ReliabilityEvent(
component=component_id,
latency_p99=100.0,
error_rate=0.01,
throughput=1000.0
)
assert "component" in str(exc_info.value).lower()
def test_latency_bounds(self):
"""Test latency validation bounds"""
# Valid latency
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.01,
throughput=1000.0
)
assert event.latency_p99 == 100.0
# Negative latency should fail
with pytest.raises(ValidationError):
ReliabilityEvent(
component="test-service",
latency_p99=-10.0,
error_rate=0.01,
throughput=1000.0
)
# Extremely high latency should fail (> 5 minutes)
with pytest.raises(ValidationError):
ReliabilityEvent(
component="test-service",
latency_p99=400000.0, # > 300000ms limit
error_rate=0.01,
throughput=1000.0
)
def test_error_rate_bounds(self):
"""Test error rate validation"""
# Valid error rate
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.5,
throughput=1000.0
)
assert event.error_rate == 0.5
# Negative error rate should fail
with pytest.raises(ValidationError):
ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=-0.1,
throughput=1000.0
)
# Error rate > 1 should fail
with pytest.raises(ValidationError):
ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=1.5,
throughput=1000.0
)
def test_resource_utilization_bounds(self):
"""Test CPU and memory utilization bounds"""
# Valid utilization
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.01,
throughput=1000.0,
cpu_util=0.85,
memory_util=0.75
)
assert event.cpu_util == 0.85
assert event.memory_util == 0.75
# CPU > 1 should fail
with pytest.raises(ValidationError):
ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.01,
throughput=1000.0,
cpu_util=1.5
)
# Memory < 0 should fail
with pytest.raises(ValidationError):
ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.01,
throughput=1000.0,
memory_util=-0.1
)
class TestEventFingerprint:
"""Test event fingerprint generation (SHA-256)"""
def test_fingerprint_is_sha256(self):
"""Test that fingerprint uses SHA-256 (64 hex chars)"""
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
# SHA-256 produces 64 hex characters
assert len(event.fingerprint) == 64
assert all(c in '0123456789abcdef' for c in event.fingerprint)
def test_fingerprint_deterministic(self):
"""Test that same inputs produce same fingerprint"""
event1 = ReliabilityEvent(
component="test-service",
service_mesh="default",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
event2 = ReliabilityEvent(
component="test-service",
service_mesh="default",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
# Should produce same fingerprint (timestamp not included)
assert event1.fingerprint == event2.fingerprint
def test_fingerprint_different_for_different_events(self):
"""Test that different events produce different fingerprints"""
event1 = ReliabilityEvent(
component="service-1",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
event2 = ReliabilityEvent(
component="service-2",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
assert event1.fingerprint != event2.fingerprint
def test_fingerprint_not_md5(self):
"""Test that fingerprint is NOT MD5 (security fix verification)"""
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
# MD5 produces 32 hex chars, SHA-256 produces 64
assert len(event.fingerprint) != 32
assert len(event.fingerprint) == 64
class TestEventImmutability:
"""Test that events are immutable (frozen)"""
def test_event_is_frozen(self):
"""Test that ReliabilityEvent is frozen"""
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
# Attempting to modify should raise ValidationError
with pytest.raises(ValidationError):
event.latency_p99 = 200.0
def test_model_copy_with_update(self):
"""Test that model_copy creates new instance with updates"""
event1 = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0,
severity=EventSeverity.LOW
)
# Create modified copy
event2 = event1.model_copy(update={'severity': EventSeverity.HIGH})
# Original unchanged
assert event1.severity == EventSeverity.LOW
# Copy updated
assert event2.severity == EventSeverity.HIGH
# Other fields same
assert event2.component == event1.component
assert event2.latency_p99 == event1.latency_p99
class TestDependencyValidation:
"""Test dependency cycle detection"""
def test_valid_dependencies(self):
"""Test valid dependency configuration"""
event = ReliabilityEvent(
component="api-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0,
upstream_deps=["auth-service", "database"],
downstream_deps=["frontend", "mobile-app"]
)
assert "auth-service" in event.upstream_deps
assert "frontend" in event.downstream_deps
def test_circular_dependency_detected(self):
"""Test that circular dependencies are detected"""
with pytest.raises(ValidationError) as exc_info:
ReliabilityEvent(
component="api-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0,
upstream_deps=["auth-service", "database"],
downstream_deps=["database", "frontend"] # 'database' in both
)
error_msg = str(exc_info.value).lower()
assert "circular" in error_msg or "database" in error_msg
def test_dependency_name_validation(self):
"""Test that dependency names follow same rules as component IDs"""
# Valid dependency names
event = ReliabilityEvent(
component="api-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0,
upstream_deps=["auth-service", "db-01", "cache-v2"]
)
assert len(event.upstream_deps) == 3
# Invalid dependency names
with pytest.raises(ValidationError):
ReliabilityEvent(
component="api-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0,
upstream_deps=["AUTH_SERVICE"] # Uppercase/underscore
)
class TestPolicyConditionModel:
"""Test PolicyCondition structured model"""
def test_valid_policy_condition(self):
"""Test creating valid policy conditions"""
condition = PolicyCondition(
metric="latency_p99",
operator="gt",
threshold=150.0
)
assert condition.metric == "latency_p99"
assert condition.operator == "gt"
assert condition.threshold == 150.0
def test_policy_condition_frozen(self):
"""Test that PolicyCondition is immutable"""
condition = PolicyCondition(
metric="error_rate",
operator="gt",
threshold=0.1
)
with pytest.raises(ValidationError):
condition.threshold = 0.2
def test_invalid_metric(self):
"""Test that invalid metrics are rejected"""
with pytest.raises(ValidationError):
PolicyCondition(
metric="invalid_metric",
operator="gt",
threshold=100.0
)
def test_invalid_operator(self):
"""Test that invalid operators are rejected"""
with pytest.raises(ValidationError):
PolicyCondition(
metric="latency_p99",
operator="invalid_op",
threshold=100.0
)
def test_negative_threshold(self):
"""Test that negative thresholds are rejected"""
with pytest.raises(ValidationError):
PolicyCondition(
metric="latency_p99",
operator="gt",
threshold=-100.0
)
class TestHealingPolicyModel:
"""Test HealingPolicy model"""
def test_valid_healing_policy(self):
"""Test creating valid healing policy"""
policy = HealingPolicy(
name="high_latency_restart",
conditions=[
PolicyCondition(metric="latency_p99", operator="gt", threshold=300.0)
],
actions=[HealingAction.RESTART_CONTAINER, HealingAction.ALERT_TEAM],
priority=1,
cool_down_seconds=300
)
assert policy.name == "high_latency_restart"
assert len(policy.conditions) == 1
assert len(policy.actions) == 2
assert policy.priority == 1
def test_policy_frozen(self):
"""Test that HealingPolicy is immutable"""
policy = HealingPolicy(
name="test_policy",
conditions=[
PolicyCondition(metric="error_rate", operator="gt", threshold=0.1)
],
actions=[HealingAction.ROLLBACK],
priority=2
)
with pytest.raises(ValidationError):
policy.priority = 5
def test_empty_conditions_rejected(self):
"""Test that policies must have at least one condition"""
with pytest.raises(ValidationError):
HealingPolicy(
name="empty_policy",
conditions=[], # Empty
actions=[HealingAction.ALERT_TEAM],
priority=3
)
def test_empty_actions_rejected(self):
"""Test that policies must have at least one action"""
with pytest.raises(ValidationError):
HealingPolicy(
name="empty_actions",
conditions=[
PolicyCondition(metric="latency_p99", operator="gt", threshold=100.0)
],
actions=[], # Empty
priority=3
)
def test_priority_bounds(self):
"""Test priority validation (1-5)"""
# Valid priority
policy = HealingPolicy(
name="test",
conditions=[PolicyCondition(metric="latency_p99", operator="gt", threshold=100.0)],
actions=[HealingAction.ALERT_TEAM],
priority=3
)
assert policy.priority == 3
# Priority < 1 should fail
with pytest.raises(ValidationError):
HealingPolicy(
name="test",
conditions=[PolicyCondition(metric="latency_p99", operator="gt", threshold=100.0)],
actions=[HealingAction.ALERT_TEAM],
priority=0
)
# Priority > 5 should fail
with pytest.raises(ValidationError):
HealingPolicy(
name="test",
conditions=[PolicyCondition(metric="latency_p99", operator="gt", threshold=100.0)],
actions=[HealingAction.ALERT_TEAM],
priority=10
)
class TestAnomalyResultModel:
"""Test AnomalyResult model"""
def test_valid_anomaly_result(self):
"""Test creating valid anomaly result"""
result = AnomalyResult(
is_anomaly=True,
confidence=0.85,
anomaly_score=0.75,
affected_metrics=["latency", "error_rate"]
)
assert result.is_anomaly is True
assert result.confidence == 0.85
assert isinstance(result.detection_timestamp, datetime)
def test_confidence_bounds(self):
"""Test confidence is bounded 0-1"""
# Valid
result = AnomalyResult(
is_anomaly=True,
confidence=0.5,
anomaly_score=0.6
)
assert result.confidence == 0.5
# Confidence > 1 should fail
with pytest.raises(ValidationError):
AnomalyResult(
is_anomaly=True,
confidence=1.5,
anomaly_score=0.5
)
class TestForecastResultModel:
"""Test ForecastResult model"""
def test_valid_forecast(self):
"""Test creating valid forecast"""
result = ForecastResult(
metric="latency",
predicted_value=250.0,
confidence=0.75,
trend="increasing",
time_to_threshold=15.5,
risk_level="high"
)
assert result.metric == "latency"
assert result.trend == "increasing"
assert result.risk_level == "high"
def test_trend_validation(self):
"""Test that only valid trends are accepted"""
valid_trends = ["increasing", "decreasing", "stable"]
for trend in valid_trends:
result = ForecastResult(
metric="latency",
predicted_value=200.0,
confidence=0.7,
trend=trend,
risk_level="medium"
)
assert result.trend == trend
# Invalid trend
with pytest.raises(ValidationError):
ForecastResult(
metric="latency",
predicted_value=200.0,
confidence=0.7,
trend="invalid_trend",
risk_level="medium"
)
def test_risk_level_validation(self):
"""Test that only valid risk levels are accepted"""
valid_levels = ["low", "medium", "high", "critical"]
for level in valid_levels:
result = ForecastResult(
metric="error_rate",
predicted_value=0.08,
confidence=0.8,
trend="stable",
risk_level=level
)
assert result.risk_level == level
# Invalid risk level
with pytest.raises(ValidationError):
ForecastResult(
metric="error_rate",
predicted_value=0.08,
confidence=0.8,
trend="stable",
risk_level="extreme"
)
class TestTimestampHandling:
"""Test datetime timestamp handling"""
def test_timestamp_is_datetime(self):
"""Test that timestamp is datetime, not string"""
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
# Should be datetime object
assert isinstance(event.timestamp, datetime)
# Should have timezone
assert event.timestamp.tzinfo is not None
def test_timestamp_is_utc(self):
"""Test that timestamp uses UTC"""
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
assert event.timestamp.tzinfo == timezone.utc
def test_timestamp_serialization(self):
"""Test that timestamp can be serialized"""
event = ReliabilityEvent(
component="test-service",
latency_p99=100.0,
error_rate=0.05,
throughput=1000.0
)
# Can convert to ISO format
iso_str = event.timestamp.isoformat()
assert isinstance(iso_str, str)
assert 'T' in iso_str # ISO format
if __name__ == "__main__":
pytest.main([__file__, "-v", "--tb=short"]) |