Environment-variable configuration that fails fast, database-only health check, JSON request logs with a request id, security headers with a strict CSP, and a multi-stage non-root Docker image with compose file. Ticket 1.1. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Sk72AxLwQnYttF6VFSxQLt
39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
import json
|
|
import logging
|
|
|
|
import pytest
|
|
|
|
from portal.config.logging import JsonFormatter
|
|
|
|
|
|
@pytest.mark.django_db
|
|
def test_request_log_has_id_and_no_query(client, caplog):
|
|
with caplog.at_level(logging.INFO, logger="portal.request"):
|
|
response = client.get("/healthz?token=supersecret")
|
|
records = [r for r in caplog.records if r.name == "portal.request"]
|
|
assert len(records) == 1
|
|
record = records[0]
|
|
assert record.request_id == response["X-Request-ID"]
|
|
assert (record.method, record.path, record.status) == ("GET", "/healthz", 200)
|
|
assert "supersecret" not in caplog.text
|
|
|
|
|
|
def test_json_formatter_emits_json_with_extras():
|
|
record = logging.LogRecord("x", logging.INFO, __file__, 1, "hello %s", ("world",), None)
|
|
record.request_id = "rid-1"
|
|
record.status = 200
|
|
data = json.loads(JsonFormatter().format(record))
|
|
assert data["message"] == "hello world"
|
|
assert data["request_id"] == "rid-1"
|
|
assert data["status"] == 200
|
|
assert data["level"] == "INFO"
|
|
|
|
|
|
def test_404_with_query_writes_one_line_without_query(client, caplog):
|
|
with caplog.at_level(logging.DEBUG):
|
|
client.get("/missing?token=supersecret")
|
|
assert len(caplog.records) == 1
|
|
output = JsonFormatter().format(caplog.records[0])
|
|
assert "supersecret" not in output
|
|
assert json.loads(output)["path"] == "/missing"
|