Robert Anthony 2 days ago
committed by GitHub
parent
commit
cc82e943a8
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 14
      docs/de/docs/how-to/custom-docs-ui-assets.md
  2. 14
      docs/en/docs/how-to/custom-docs-ui-assets.md
  3. 14
      docs/es/docs/how-to/custom-docs-ui-assets.md
  4. 14
      docs/pt/docs/how-to/custom-docs-ui-assets.md
  5. 20
      docs_src/custom_docs_ui/tutorial001.py
  6. 26
      docs_src/custom_docs_ui/tutorial002.py
  7. 73
      tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py
  8. 83
      tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py

14
docs/de/docs/how-to/custom-docs-ui-assets.md

@ -18,7 +18,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier
Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *}
### Die benutzerdefinierten Dokumentationen hinzufügen ### Die benutzerdefinierten Dokumentationen hinzufügen
@ -34,7 +34,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei
Und genau so für ReDoc ... Und genau so für ReDoc ...
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *}
/// tip | Tipp /// tip | Tipp
@ -50,7 +50,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U
Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *}
### Es ausprobieren ### Es ausprobieren
@ -118,7 +118,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen:
* Importieren Sie `StaticFiles`. * Importieren Sie `StaticFiles`.
* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad.
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *}
### Die statischen Dateien testen ### Die statischen Dateien testen
@ -144,7 +144,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d
Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *}
### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen
@ -160,7 +160,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di
Und genau so für ReDoc ... Und genau so für ReDoc ...
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *}
/// tip | Tipp /// tip | Tipp
@ -176,7 +176,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U
Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *}
### Benutzeroberfläche, mit statischen Dateien, testen ### Benutzeroberfläche, mit statischen Dateien, testen

14
docs/en/docs/how-to/custom-docs-ui-assets.md

@ -18,7 +18,7 @@ The first step is to disable the automatic docs, as by default, those use the de
To disable them, set their URLs to `None` when creating your `FastAPI` app: To disable them, set their URLs to `None` when creating your `FastAPI` app:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *}
### Include the custom docs ### Include the custom docs
@ -34,7 +34,7 @@ You can reuse FastAPI's internal functions to create the HTML pages for the docs
And similarly for ReDoc... And similarly for ReDoc...
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *}
/// tip /// tip
@ -50,7 +50,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect
Now, to be able to test that everything works, create a *path operation*: Now, to be able to test that everything works, create a *path operation*:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *}
### Test it ### Test it
@ -118,7 +118,7 @@ After that, your file structure could look like:
* Import `StaticFiles`. * Import `StaticFiles`.
* "Mount" a `StaticFiles()` instance in a specific path. * "Mount" a `StaticFiles()` instance in a specific path.
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *}
### Test the static files ### Test the static files
@ -144,7 +144,7 @@ The same as when using a custom CDN, the first step is to disable the automatic
To disable them, set their URLs to `None` when creating your `FastAPI` app: To disable them, set their URLs to `None` when creating your `FastAPI` app:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *}
### Include the custom docs for static files ### Include the custom docs for static files
@ -160,7 +160,7 @@ Again, you can reuse FastAPI's internal functions to create the HTML pages for t
And similarly for ReDoc... And similarly for ReDoc...
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *}
/// tip /// tip
@ -176,7 +176,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect
Now, to be able to test that everything works, create a *path operation*: Now, to be able to test that everything works, create a *path operation*:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *}
### Test Static Files UI ### Test Static Files UI

14
docs/es/docs/how-to/custom-docs-ui-assets.md

@ -18,7 +18,7 @@ El primer paso es desactivar la documentación automática, ya que por defecto,
Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`: Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *}
### Incluye la documentación personalizada ### Incluye la documentación personalizada
@ -34,7 +34,7 @@ Puedes reutilizar las funciones internas de FastAPI para crear las páginas HTML
Y de manera similar para ReDoc... Y de manera similar para ReDoc...
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *}
/// tip | Consejo /// tip | Consejo
@ -50,7 +50,7 @@ Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar d
Ahora, para poder probar que todo funciona, crea una *path operation*: Ahora, para poder probar que todo funciona, crea una *path operation*:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *}
### Pruébalo ### Pruébalo
@ -118,7 +118,7 @@ Después de eso, tu estructura de archivos podría verse así:
* Importa `StaticFiles`. * Importa `StaticFiles`.
* "Monta" una instance de `StaticFiles()` en un path específico. * "Monta" una instance de `StaticFiles()` en un path específico.
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *}
### Prueba los archivos estáticos ### Prueba los archivos estáticos
@ -144,7 +144,7 @@ Igual que cuando usas un CDN personalizado, el primer paso es desactivar la docu
Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`: Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *}
### Incluye la documentación personalizada para archivos estáticos ### Incluye la documentación personalizada para archivos estáticos
@ -160,7 +160,7 @@ Nuevamente, puedes reutilizar las funciones internas de FastAPI para crear las p
Y de manera similar para ReDoc... Y de manera similar para ReDoc...
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *}
/// tip | Consejo /// tip | Consejo
@ -176,7 +176,7 @@ Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar d
Ahora, para poder probar que todo funciona, crea una *path operation*: Ahora, para poder probar que todo funciona, crea una *path operation*:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *}
### Prueba la UI de Archivos Estáticos ### Prueba la UI de Archivos Estáticos

14
docs/pt/docs/how-to/custom-docs-ui-assets.md

@ -18,7 +18,7 @@ O primeiro passo é desativar a documentação automática, pois por padrão, el
Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *}
### Incluir a documentação personalizada ### Incluir a documentação personalizada
@ -34,7 +34,7 @@ Você pode reutilizar as funções internas do FastAPI para criar as páginas HT
E de forma semelhante para o ReDoc... E de forma semelhante para o ReDoc...
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *}
/// tip | Dica /// tip | Dica
@ -50,7 +50,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux
Agora, para poder testar se tudo funciona, crie uma *operação de rota*: Agora, para poder testar se tudo funciona, crie uma *operação de rota*:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *}
### Teste ### Teste
@ -118,7 +118,7 @@ Depois disso, sua estrutura de arquivos deve se parecer com:
* Importe `StaticFiles`. * Importe `StaticFiles`.
* "Monte" a instância `StaticFiles()` em um caminho específico. * "Monte" a instância `StaticFiles()` em um caminho específico.
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *}
### Teste os arquivos estáticos ### Teste os arquivos estáticos
@ -144,7 +144,7 @@ Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a
Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *}
### Incluir a documentação personalizada para arquivos estáticos ### Incluir a documentação personalizada para arquivos estáticos
@ -160,7 +160,7 @@ Novamente, você pode reutilizar as funções internas do FastAPI para criar as
E de forma semelhante para o ReDoc... E de forma semelhante para o ReDoc...
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *}
/// tip | Dica /// tip | Dica
@ -176,7 +176,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux
Agora, para poder testar se tudo funciona, crie uma *operação de rota*: Agora, para poder testar se tudo funciona, crie uma *operação de rota*:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *}
### Teste a UI de Arquivos Estáticos ### Teste a UI de Arquivos Estáticos

20
docs_src/custom_docs_ui/tutorial001.py

@ -1,19 +1,24 @@
from fastapi import FastAPI import os
from fastapi import FastAPI, Request
from fastapi.openapi.docs import ( from fastapi.openapi.docs import (
get_redoc_html, get_redoc_html,
get_swagger_ui_html, get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html, get_swagger_ui_oauth2_redirect_html,
) )
app = FastAPI(docs_url=None, redoc_url=None) root_path = os.getenv("ROOT_PATH", "")
app = FastAPI(docs_url=None, redoc_url=None, root_path=root_path)
@app.get("/docs", include_in_schema=False) @app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(): async def custom_swagger_ui_html(req: Request):
root_path = req.scope.get("root_path", "").rstrip("/")
return get_swagger_ui_html( return get_swagger_ui_html(
openapi_url=app.openapi_url, openapi_url=f"{root_path}{app.openapi_url}",
title=app.title + " - Swagger UI", title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, oauth2_redirect_url=f"{root_path}{app.swagger_ui_oauth2_redirect_url}",
swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css", swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
) )
@ -25,9 +30,10 @@ async def swagger_ui_redirect():
@app.get("/redoc", include_in_schema=False) @app.get("/redoc", include_in_schema=False)
async def redoc_html(): async def redoc_html(req: Request):
root_path = req.scope.get("root_path", "").rstrip("/")
return get_redoc_html( return get_redoc_html(
openapi_url=app.openapi_url, openapi_url=f"{root_path}{app.openapi_url}",
title=app.title + " - ReDoc", title=app.title + " - ReDoc",
redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js", redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js",
) )

26
docs_src/custom_docs_ui/tutorial002.py

@ -1,4 +1,6 @@
from fastapi import FastAPI import os
from fastapi import FastAPI, Request
from fastapi.openapi.docs import ( from fastapi.openapi.docs import (
get_redoc_html, get_redoc_html,
get_swagger_ui_html, get_swagger_ui_html,
@ -6,19 +8,22 @@ from fastapi.openapi.docs import (
) )
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
app = FastAPI(docs_url=None, redoc_url=None) root_path = os.getenv("ROOT_PATH", "")
app = FastAPI(docs_url=None, redoc_url=None, root_path=root_path)
app.mount("/static", StaticFiles(directory="static"), name="static") app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/docs", include_in_schema=False) @app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(): async def custom_swagger_ui_html(req: Request):
root_path = req.scope.get("root_path", "").rstrip("/")
return get_swagger_ui_html( return get_swagger_ui_html(
openapi_url=app.openapi_url, openapi_url=f"{root_path}{app.openapi_url}",
title=app.title + " - Swagger UI", title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, oauth2_redirect_url=f"{root_path}{app.swagger_ui_oauth2_redirect_url}",
swagger_js_url="/static/swagger-ui-bundle.js", swagger_js_url=f"{root_path}/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css", swagger_css_url=f"{root_path}/static/swagger-ui.css",
) )
@ -28,11 +33,12 @@ async def swagger_ui_redirect():
@app.get("/redoc", include_in_schema=False) @app.get("/redoc", include_in_schema=False)
async def redoc_html(): async def redoc_html(req: Request):
root_path = req.scope.get("root_path", "").rstrip("/")
return get_redoc_html( return get_redoc_html(
openapi_url=app.openapi_url, openapi_url=f"{root_path}{app.openapi_url}",
title=app.title + " - ReDoc", title=app.title + " - ReDoc",
redoc_js_url="/static/redoc.standalone.js", redoc_js_url=f"{root_path}/static/redoc.standalone.js",
) )

73
tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py

@ -1,42 +1,91 @@
import importlib
import os import os
from pathlib import Path from pathlib import Path
from typing import TypedDict
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
@pytest.fixture(scope="module") class Params(TypedDict):
def client(): app_root_path: str
asgi_root_path: str
request_prefix: str
@pytest.fixture(
params=[
Params(app_root_path="", asgi_root_path="", request_prefix=""),
Params(app_root_path="/api", asgi_root_path="", request_prefix="/api"),
Params(app_root_path="/api", asgi_root_path="", request_prefix=""),
Params(app_root_path="", asgi_root_path="/api", request_prefix="/api"),
Params(app_root_path="", asgi_root_path="/api", request_prefix=""),
],
ids=[
"Without root_path, request without prefix",
"FastAPI(root_path=root_path), request with prefix",
"FastAPI(root_path=root_path), request without prefix",
"TestClient(root_path=root_path), request with prefix",
"TestClient(root_path=root_path), request without prefix",
],
)
def params(request: pytest.FixtureRequest):
return request.param
@pytest.fixture
def client(params: Params, monkeypatch):
static_dir: Path = Path(os.getcwd()) / "static" static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir) print(static_dir)
static_dir.mkdir(exist_ok=True) static_dir.mkdir(exist_ok=True)
from docs_src.custom_docs_ui.tutorial001 import app monkeypatch.setenv("ROOT_PATH", params["app_root_path"])
from docs_src.custom_docs_ui import tutorial001
importlib.reload(tutorial001)
app = tutorial001.app
with TestClient(app) as client: with TestClient(app, root_path=params["asgi_root_path"]) as client:
yield client yield client
static_dir.rmdir() static_dir.rmdir()
def test_swagger_ui_html(client: TestClient): def test_swagger_ui_html(client: TestClient, params: Params):
response = client.get("/docs") request_prefix = params["request_prefix"]
root_path = params["app_root_path"] or params["asgi_root_path"]
response = client.get(f"{request_prefix}/docs")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" in response.text assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" in response.text
assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" in response.text assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" in response.text
assert f"{root_path}/docs/oauth2-redirect" in response.text
response = client.get(f"{request_prefix}/openapi.json")
assert response.status_code == 200
def test_swagger_ui_oauth2_redirect_html(client: TestClient, params: Params):
request_prefix = params["request_prefix"]
def test_swagger_ui_oauth2_redirect_html(client: TestClient): response = client.get(f"{request_prefix}/docs/oauth2-redirect")
response = client.get("/docs/oauth2-redirect")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert "window.opener.swaggerUIRedirectOauth2" in response.text assert "window.opener.swaggerUIRedirectOauth2" in response.text
def test_redoc_html(client: TestClient): def test_redoc_html(client: TestClient, params: Params):
response = client.get("/redoc") request_prefix = params["request_prefix"]
response = client.get(f"{request_prefix}/redoc")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert "https://unpkg.com/redoc@2/bundles/redoc.standalone.js" in response.text assert "https://unpkg.com/redoc@2/bundles/redoc.standalone.js" in response.text
response = client.get(f"{request_prefix}/openapi.json")
assert response.status_code == 200
def test_api(client: TestClient, params: Params):
request_prefix = params["request_prefix"]
def test_api(client: TestClient): response = client.get(f"{request_prefix}/users/john")
response = client.get("/users/john")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert response.json()["message"] == "Hello john" assert response.json()["message"] == "Hello john"

83
tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py

@ -1,42 +1,93 @@
import importlib
import os import os
from pathlib import Path from pathlib import Path
from typing import TypedDict
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
@pytest.fixture(scope="module") class Params(TypedDict):
def client(): app_root_path: str
asgi_root_path: str
request_prefix: str
@pytest.fixture(
params=[
Params(app_root_path="", asgi_root_path="", request_prefix=""),
Params(app_root_path="/api", asgi_root_path="", request_prefix="/api"),
Params(app_root_path="/api", asgi_root_path="", request_prefix=""),
Params(app_root_path="", asgi_root_path="/api", request_prefix="/api"),
Params(app_root_path="", asgi_root_path="/api", request_prefix=""),
],
ids=[
"Without root_path, request without prefix",
"FastAPI(root_path=root_path), request with prefix",
"FastAPI(root_path=root_path), request without prefix",
"TestClient(root_path=root_path), request with prefix",
"TestClient(root_path=root_path), request without prefix",
],
)
def params(request: pytest.FixtureRequest):
return request.param
@pytest.fixture()
def client(params: Params, monkeypatch):
static_dir: Path = Path(os.getcwd()) / "static" static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir)
static_dir.mkdir(exist_ok=True) static_dir.mkdir(exist_ok=True)
from docs_src.custom_docs_ui.tutorial002 import app
with TestClient(app) as client: monkeypatch.setenv("ROOT_PATH", params["app_root_path"])
from docs_src.custom_docs_ui import tutorial002
importlib.reload(tutorial002)
app = tutorial002.app
with TestClient(app, root_path=params["asgi_root_path"]) as client:
yield client yield client
static_dir.rmdir() static_dir.rmdir()
def test_swagger_ui_html(client: TestClient): def test_swagger_ui_html(client: TestClient, params: Params):
response = client.get("/docs") request_prefix = params["request_prefix"]
root_path = params["app_root_path"] or params["asgi_root_path"]
response = client.get(f"{request_prefix}/docs")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert "/static/swagger-ui-bundle.js" in response.text assert f"{root_path}/static/swagger-ui-bundle.js" in response.text
assert "/static/swagger-ui.css" in response.text assert f"{root_path}/static/swagger-ui.css" in response.text
assert f"{root_path}/docs/oauth2-redirect" in response.text
response = client.get(f"{request_prefix}/openapi.json")
assert response.status_code == 200
def test_swagger_ui_oauth2_redirect_html(client: TestClient): def test_swagger_ui_oauth2_redirect_html(client: TestClient, params: Params):
response = client.get("/docs/oauth2-redirect") request_prefix = params["request_prefix"]
response = client.get(f"{request_prefix}/docs/oauth2-redirect")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert "window.opener.swaggerUIRedirectOauth2" in response.text assert "window.opener.swaggerUIRedirectOauth2" in response.text
def test_redoc_html(client: TestClient): def test_redoc_html(client: TestClient, params: Params):
response = client.get("/redoc") request_prefix = params["request_prefix"]
root_path = params["app_root_path"] or params["asgi_root_path"]
response = client.get(f"{request_prefix}/redoc")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert "/static/redoc.standalone.js" in response.text assert f"{root_path}/static/redoc.standalone.js" in response.text
response = client.get(f"{request_prefix}/openapi.json")
assert response.status_code == 200
def test_api(client: TestClient, params: Params):
request_prefix = params["request_prefix"]
def test_api(client: TestClient): response = client.get(f"{request_prefix}/users/john")
response = client.get("/users/john")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert response.json()["message"] == "Hello john" assert response.json()["message"] == "Hello john"

Loading…
Cancel
Save