Allow test env and TestClient host
Browse filesAdd TESTING=true to the CI workflow and set APP_ENV=test in tests so test runs are marked as testing. Update TrustedHostMiddleware to treat 'test' like 'development' (allow all hosts) and include 'testserver' in allowed hosts for non-dev cases so FastAPI's TrustedHost won't block TestClient requests.
- .github/workflows/ci.yml +1 -0
- app.py +1 -1
- tests/conftest.py +1 -0
.github/workflows/ci.yml
CHANGED
|
@@ -46,6 +46,7 @@ jobs:
|
|
| 46 |
--tb=short
|
| 47 |
env:
|
| 48 |
APP_ENV: test
|
|
|
|
| 49 |
- name: Upload coverage report
|
| 50 |
uses: codecov/codecov-action@v4
|
| 51 |
if: matrix.python-version == '3.11'
|
|
|
|
| 46 |
--tb=short
|
| 47 |
env:
|
| 48 |
APP_ENV: test
|
| 49 |
+
TESTING: true
|
| 50 |
- name: Upload coverage report
|
| 51 |
uses: codecov/codecov-action@v4
|
| 52 |
if: matrix.python-version == '3.11'
|
app.py
CHANGED
|
@@ -79,7 +79,7 @@ from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
|
|
| 79 |
# 1. Trusted Host (Prevent Host-header injection)
|
| 80 |
app.add_middleware(
|
| 81 |
TrustedHostMiddleware,
|
| 82 |
-
allowed_hosts=["*"] if settings.app_env
|
| 83 |
)
|
| 84 |
|
| 85 |
# 2. Proxy Headers (Support Docker/Reverse-proxy)
|
|
|
|
| 79 |
# 1. Trusted Host (Prevent Host-header injection)
|
| 80 |
app.add_middleware(
|
| 81 |
TrustedHostMiddleware,
|
| 82 |
+
allowed_hosts=["*"] if settings.app_env in ("development", "test") else [f"localhost", "127.0.0.1", "*.github.io", "testserver"]
|
| 83 |
)
|
| 84 |
|
| 85 |
# 2. Proxy Headers (Support Docker/Reverse-proxy)
|
tests/conftest.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import pytest
|
| 2 |
import os
|
| 3 |
os.environ["TESTING"] = "true"
|
|
|
|
| 4 |
from fastapi.testclient import TestClient
|
| 5 |
from sqlmodel import SQLModel, Session, create_engine
|
| 6 |
from sqlmodel.pool import StaticPool
|
|
|
|
| 1 |
import pytest
|
| 2 |
import os
|
| 3 |
os.environ["TESTING"] = "true"
|
| 4 |
+
os.environ["APP_ENV"] = "test"
|
| 5 |
from fastapi.testclient import TestClient
|
| 6 |
from sqlmodel import SQLModel, Session, create_engine
|
| 7 |
from sqlmodel.pool import StaticPool
|