Import the existing local project snapshot. This commit organizes existing files; it does not represent newly developed functionality.
65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
import pytest
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
def _make_app():
|
|
app = FastAPI()
|
|
|
|
@app.get("/data")
|
|
async def data():
|
|
return {"ok": True}
|
|
|
|
@app.get("/health")
|
|
async def health():
|
|
return {"status": "ok"}
|
|
|
|
return app
|
|
|
|
|
|
def test_auth_skipped_when_no_keys_configured(monkeypatch):
|
|
monkeypatch.setattr("axon.middleware.auth.settings.api_keys", None)
|
|
from axon.middleware.auth import APIKeyMiddleware
|
|
app = _make_app()
|
|
app.add_middleware(APIKeyMiddleware)
|
|
client = TestClient(app, raise_server_exceptions=True)
|
|
assert client.get("/data").status_code == 200
|
|
|
|
|
|
def test_auth_valid_key_accepted(monkeypatch):
|
|
monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret")
|
|
from axon.middleware.auth import APIKeyMiddleware
|
|
app = _make_app()
|
|
app.add_middleware(APIKeyMiddleware)
|
|
client = TestClient(app)
|
|
assert client.get("/data", headers={"X-API-Key": "secret"}).status_code == 200
|
|
|
|
|
|
def test_auth_wrong_key_rejected(monkeypatch):
|
|
monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret")
|
|
from axon.middleware.auth import APIKeyMiddleware
|
|
app = _make_app()
|
|
app.add_middleware(APIKeyMiddleware)
|
|
client = TestClient(app)
|
|
resp = client.get("/data", headers={"X-API-Key": "wrong"})
|
|
assert resp.status_code == 401
|
|
assert "detail" in resp.json()
|
|
|
|
|
|
def test_auth_missing_key_rejected(monkeypatch):
|
|
monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret")
|
|
from axon.middleware.auth import APIKeyMiddleware
|
|
app = _make_app()
|
|
app.add_middleware(APIKeyMiddleware)
|
|
client = TestClient(app)
|
|
assert client.get("/data").status_code == 401
|
|
|
|
|
|
def test_health_exempt_from_auth(monkeypatch):
|
|
monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret")
|
|
from axon.middleware.auth import APIKeyMiddleware
|
|
app = _make_app()
|
|
app.add_middleware(APIKeyMiddleware)
|
|
client = TestClient(app)
|
|
assert client.get("/health").status_code == 200
|