Files
thisORthat/app/tests/conftest.py
T
IgorVolochay f8a2744492 fix(tests): reliable SecurityMiddleware state reset via app.state reference
- Store direct reference to SecurityMiddleware instance in app.state._security_middleware
  immediately at module load time in main.py (before middleware_stack is built)
- Rewrite conftest.py _reset_all() to use app.state._security_middleware instead of
  fragile middleware stack traversal that failed before the first request was made
- Set explicit client=('127.0.0.1', 50000) on ASGITransport across all test files
  to ensure guard-core always sees a valid IP and can ban/track it correctly
2026-08-25 18:13:16 +03:00

41 lines
1.1 KiB
Python

"""
conftest.py — fixtures for resetting rate-limiter state and IP-ban
between tests so functional tests do not hit 429 errors.
"""
import pytest
from guard import ip_ban_manager
from guard_core.handlers.ratelimit_handler import RateLimitManager
def _reset_all():
"""Full reset of rate-limiter, IP-ban, and suspicious counts."""
# Rate limit timestamps
rl: RateLimitManager | None = RateLimitManager._instance
if rl is not None:
rl.request_timestamps.clear()
# IP bans
ip_ban_manager.banned_ips.clear()
ip_ban_manager.banned_networks.clear()
# Suspicious request counts via direct reference stored in app.state
try:
from main import app
sm = getattr(app.state, '_security_middleware', None)
if sm is not None:
sm.suspicious_request_counts.clear()
except Exception:
pass
@pytest.fixture(autouse=True)
def reset_guard_state():
"""
Synchronous fixture (autouse) that resets guard middleware
state before and after each test.
"""
_reset_all()
yield
_reset_all()