Aniworld/tests/conftest.py
2025-10-19 19:57:42 +02:00

55 lines
1.8 KiB
Python

"""Pytest configuration and shared fixtures for all tests."""
import pytest
from src.server.services.auth_service import auth_service
@pytest.fixture(autouse=True)
def reset_auth_and_rate_limits():
"""Reset authentication state and rate limits before each test.
This ensures:
1. Auth service state doesn't leak between tests
2. Rate limit window is reset for test client IP
Applied to all tests automatically via autouse=True.
"""
# Reset auth service state
auth_service._hash = None # noqa: SLF001
auth_service._failed.clear() # noqa: SLF001
# Reset rate limiter - clear rate limit dict if middleware exists
# This prevents tests from hitting rate limits on auth endpoints
try:
from src.server.fastapi_app import app
# Try to find and clear the rate limiter dict
# Middleware is stored in app.middleware_stack or accessible
# through app's internal structure
if hasattr(app, 'middleware_stack'):
# Try to find AuthMiddleware in the stack
stack = app.middleware_stack
while stack is not None:
if hasattr(stack, 'cls'):
# This is a middleware class
pass
if hasattr(stack, 'app') and hasattr(
stack, '_rate'
): # noqa: SLF001
# Found a potential AuthMiddleware instance
stack._rate.clear() # noqa: SLF001
stack = getattr(stack, 'app', None)
except BaseException:
# If middleware reset fails, tests might hit rate limits
# but we continue anyway - they're not critical
pass
yield
# Clean up after test
auth_service._hash = None # noqa: SLF001
auth_service._failed.clear() # noqa: SLF001