mockapi/tests/test_admin.py
2026-03-16 05:47:01 +00:00

89 lines
No EOL
3 KiB
Python

"""
Tests for admin interface authentication and endpoints.
"""
import pytest
from fastapi.testclient import TestClient
from app import app
@pytest.fixture
def client():
"""Test client fixture."""
return TestClient(app)
def test_admin_login_page(client):
"""Login page should be accessible."""
response = client.get("/admin/login")
assert response.status_code == 200
assert "Admin Login" in response.text
def test_admin_dashboard_requires_auth(client):
"""Dashboard should redirect to login if not authenticated."""
response = client.get("/admin", follow_redirects=False)
assert response.status_code == 302
assert response.headers["location"] == "/admin/login"
def test_admin_endpoints_requires_auth(client):
"""Endpoints list should redirect to login if not authenticated."""
response = client.get("/admin/endpoints", follow_redirects=False)
assert response.status_code == 302
assert response.headers["location"] == "/admin/login"
def test_login_with_valid_credentials(client):
"""Successful login should set session and redirect to dashboard."""
response = client.post(
"/admin/login",
data={"username": "admin", "password": "admin123"},
follow_redirects=False,
)
assert response.status_code == 302
assert response.headers["location"] == "/admin"
# Check that session cookie is set
assert "mockapi_session" in response.cookies
def test_login_with_invalid_credentials(client):
"""Invalid credentials should redirect back to login with error."""
response = client.post(
"/admin/login",
data={"username": "admin", "password": "wrong"},
follow_redirects=False,
)
assert response.status_code == 302
assert response.headers["location"] == "/admin/login?error=Invalid+credentials"
# No session cookie
assert "mockapi_session" not in response.cookies
def test_authenticated_access(client):
"""After login, admin routes should be accessible."""
# First login
login_response = client.post(
"/admin/login",
data={"username": "admin", "password": "admin123"},
follow_redirects=False,
)
assert login_response.status_code == 302
# Now request dashboard
dashboard_response = client.get("/admin")
assert dashboard_response.status_code == 200
assert "Dashboard" in dashboard_response.text
def test_logout(client):
"""Logout should clear session and redirect to login."""
# Login first
client.post("/admin/login", data={"username": "admin", "password": "admin123"}, follow_redirects=False)
# Logout
response = client.get("/admin/logout", follow_redirects=False)
assert response.status_code == 302
assert response.headers["location"] == "/admin/login"
# Session cookie should be cleared (or empty)
# Actually Starlette SessionMiddleware sets a new empty session
# We'll just ensure we can't access dashboard after logout
dashboard_response = client.get("/admin", follow_redirects=False)
assert dashboard_response.status_code == 302