Remove `root_path` from code examples

This commit is contained in:
Yurii Motov 2025-11-20 12:08:14 +01:00
parent ffaebed1a5
commit af4528b40f
9 changed files with 92 additions and 155 deletions

View File

@ -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[12] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
### Die benutzerdefinierten Dokumentationen hinzufügen { #include-the-custom-docs } ### Die benutzerdefinierten Dokumentationen hinzufügen { #include-the-custom-docs }
@ -34,7 +34,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei
Und ähnlich für ReDoc ... Und ähnlich für ReDoc ...
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:20,23:25,28:35] *}
/// 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[42:44] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[38:40] *}
### Es testen { #test-it } ### Es testen { #test-it }
@ -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[9,15] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
### Die statischen Dateien testen { #test-the-static-files } ### Die statischen Dateien testen { #test-the-static-files }
@ -144,7 +144,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d
Um sie zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: Um sie zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
### Die benutzerdefinierten Dokumentationen für statische Dateien hinzufügen { #include-the-custom-docs-for-static-files } ### Die benutzerdefinierten Dokumentationen für statische Dateien hinzufügen { #include-the-custom-docs-for-static-files }
@ -160,7 +160,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di
Und ähnlich für ReDoc ... Und ähnlich für ReDoc ...
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:23,26:28,31:38] *}
/// 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[45:47] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[41:43] *}
### Benutzeroberfläche mit statischen Dateien testen { #test-static-files-ui } ### Benutzeroberfläche mit statischen Dateien testen { #test-static-files-ui }

View File

@ -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[12] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
### Include the custom docs { #include-the-custom-docs } ### 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[4:8,15:24,27:29,32:39] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:20,23:25,28:35] *}
/// 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[42:44] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[38:40] *}
### Test it { #test-it } ### 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[9,15] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
### Test the static files { #test-the-static-files } ### 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[13] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
### Include the custom docs for static files { #include-the-custom-docs-for-static-files } ### 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[4:8,18:27,30:32,35:42] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:23,26:28,31:38] *}
/// 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[45:47] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[41:43] *}
### Test Static Files UI { #test-static-files-ui } ### Test Static Files UI { #test-static-files-ui }

View File

@ -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[12] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
### 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[4:8,15:24,27:29,32:39] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:20,23:25,28:35] *}
/// 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[42:44] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[38:40] *}
### 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[9,15] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
### 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[13] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
### 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[4:8,18:27,30:32,35:42] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:23,26:28,31:38] *}
/// 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[45:47] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[41:43] *}
### Prueba la UI de Archivos Estáticos ### Prueba la UI de Archivos Estáticos

View File

@ -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 sua aplicação FastAPI: Para desativá-los, defina suas URLs como `None` ao criar sua aplicação FastAPI:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
### Incluir a documentação personalizada { #include-the-custom-docs } ### Incluir a documentação personalizada { #include-the-custom-docs }
@ -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[4:8,15:24,27:29,32:39] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:20,23:25,28:35] *}
/// 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[42:44] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[38:40] *}
### Teste { #test-it } ### Teste { #test-it }
@ -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[9,15] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
### Teste os arquivos estáticos { #test-the-static-files } ### Teste os arquivos estáticos { #test-the-static-files }
@ -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 sua aplicação FastAPI: Para desativá-los, defina suas URLs como `None` ao criar sua aplicação FastAPI:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
### Incluir a documentação personalizada para arquivos estáticos { #include-the-custom-docs-for-static-files } ### Incluir a documentação personalizada para arquivos estáticos { #include-the-custom-docs-for-static-files }
@ -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[4:8,18:27,30:32,35:42] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:23,26:28,31:38] *}
/// 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[45:47] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[41:43] *}
### Teste a UI de Arquivos Estáticos { #test-static-files-ui } ### Teste a UI de Arquivos Estáticos { #test-static-files-ui }

View File

@ -34,7 +34,7 @@
Аналогично и для ReDoc... Аналогично и для 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[2:6,11:20,23:25,28:35] *}
/// tip | Совет /// tip | Совет
@ -50,7 +50,7 @@ Swagger UI сделает это за вас «за кулисами», но д
Чтобы убедиться, что всё работает, создайте *операцию пути*: Чтобы убедиться, что всё работает, создайте *операцию пути*:
{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} {* ../../docs_src/custom_docs_ui/tutorial001.py hl[38:40] *}
### Тестирование { #test-it } ### Тестирование { #test-it }
@ -160,7 +160,7 @@ Swagger UI сделает это за вас «за кулисами», но д
Аналогично и для ReDoc... Аналогично и для 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[2:6,14:23,26:28,31:38] *}
/// tip | Совет /// tip | Совет
@ -176,7 +176,7 @@ Swagger UI сделает это за вас «за кулисами», но д
Чтобы убедиться, что всё работает, создайте *операцию пути*: Чтобы убедиться, что всё работает, создайте *операцию пути*:
{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} {* ../../docs_src/custom_docs_ui/tutorial002.py hl[41:43] *}
### Тестирование UI со статическими файлами { #test-static-files-ui } ### Тестирование UI со статическими файлами { #test-static-files-ui }

View File

@ -1,5 +1,3 @@
import os
from fastapi import FastAPI, Request from fastapi import FastAPI, Request
from fastapi.openapi.docs import ( from fastapi.openapi.docs import (
get_redoc_html, get_redoc_html,
@ -7,9 +5,7 @@ from fastapi.openapi.docs import (
get_swagger_ui_oauth2_redirect_html, get_swagger_ui_oauth2_redirect_html,
) )
root_path = os.getenv("ROOT_PATH", "") app = FastAPI(docs_url=None, redoc_url=None)
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)

View File

@ -1,5 +1,3 @@
import os
from fastapi import FastAPI, Request from fastapi import FastAPI, Request
from fastapi.openapi.docs import ( from fastapi.openapi.docs import (
get_redoc_html, get_redoc_html,
@ -8,9 +6,7 @@ from fastapi.openapi.docs import (
) )
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
root_path = os.getenv("ROOT_PATH", "") app = FastAPI(docs_url=None, redoc_url=None)
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")

View File

@ -1,91 +1,65 @@
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
class Params(TypedDict):
app_root_path: str
asgi_root_path: str
request_prefix: str
@pytest.fixture( @pytest.fixture(
params=[ params=["", "/api"],
Params(app_root_path="", asgi_root_path="", request_prefix=""), ids=["Without path prefix", "With /api path 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): def path_prefix(request: pytest.FixtureRequest):
return request.param return request.param
@pytest.fixture @pytest.fixture
def client(params: Params, monkeypatch): def client(path_prefix: str):
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)
monkeypatch.setenv("ROOT_PATH", params["app_root_path"]) from docs_src.custom_docs_ui.tutorial001 import app
from docs_src.custom_docs_ui import tutorial001
importlib.reload(tutorial001) with TestClient(app, root_path=path_prefix, base_url="http://server") as client:
app = tutorial001.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, params: Params): def test_swagger_ui_html(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/docs")
root_path = params["app_root_path"] or params["asgi_root_path"] assert response.request.url == f"http://server{path_prefix}/docs"
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 assert f"{path_prefix}/openapi.json" in response.text
assert f"{path_prefix}/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): def test_openapi_json(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/openapi.json")
assert response.request.url == f"http://server{path_prefix}/openapi.json"
assert response.status_code == 200, response.text
assert response.json()["openapi"] == "3.1.0"
response = client.get(f"{request_prefix}/docs/oauth2-redirect")
def test_swagger_ui_oauth2_redirect_html(client: TestClient, path_prefix: str):
response = client.get(f"{path_prefix}/docs/oauth2-redirect")
assert response.request.url == f"http://server{path_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, params: Params): def test_redoc_html(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/redoc")
assert response.request.url == f"http://server{path_prefix}/redoc"
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
assert f"{path_prefix}/openapi.json" in response.text
response = client.get(f"{request_prefix}/openapi.json")
assert response.status_code == 200
def test_api(client: TestClient, params: Params): def test_api(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/users/john")
assert response.request.url == f"http://server{path_prefix}/users/john"
response = client.get(f"{request_prefix}/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"

View File

@ -1,93 +1,64 @@
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
class Params(TypedDict):
app_root_path: str
asgi_root_path: str
request_prefix: str
@pytest.fixture( @pytest.fixture(
params=[ params=["", "/api"],
Params(app_root_path="", asgi_root_path="", request_prefix=""), ids=["Without path prefix", "With /api path 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): def path_prefix(request: pytest.FixtureRequest):
return request.param return request.param
@pytest.fixture() @pytest.fixture
def client(params: Params, monkeypatch): def client(path_prefix: str):
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
monkeypatch.setenv("ROOT_PATH", params["app_root_path"]) with TestClient(app, root_path=path_prefix, base_url="http://server") as client:
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, params: Params): def test_swagger_ui_html(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/docs")
root_path = params["app_root_path"] or params["asgi_root_path"] assert response.request.url == f"http://server{path_prefix}/docs"
response = client.get(f"{request_prefix}/docs")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert f"{root_path}/static/swagger-ui-bundle.js" in response.text assert f"{path_prefix}/static/swagger-ui-bundle.js" in response.text
assert f"{root_path}/static/swagger-ui.css" in response.text assert f"{path_prefix}/static/swagger-ui.css" in response.text
assert f"{root_path}/docs/oauth2-redirect" in response.text assert f"{path_prefix}/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): def test_openapi_json(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/openapi.json")
assert response.request.url == f"http://server{path_prefix}/openapi.json"
assert response.status_code == 200, response.text
assert response.json()["openapi"] == "3.1.0"
response = client.get(f"{request_prefix}/docs/oauth2-redirect")
def test_swagger_ui_oauth2_redirect_html(client: TestClient, path_prefix: str):
response = client.get(f"{path_prefix}/docs/oauth2-redirect")
assert response.request.url == f"http://server{path_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, params: Params): def test_redoc_html(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/redoc")
root_path = params["app_root_path"] or params["asgi_root_path"] assert response.request.url == f"http://server{path_prefix}/redoc"
response = client.get(f"{request_prefix}/redoc")
assert response.status_code == 200, response.text assert response.status_code == 200, response.text
assert f"{root_path}/static/redoc.standalone.js" in response.text assert f"{path_prefix}/static/redoc.standalone.js" in response.text
assert f"{path_prefix}/openapi.json" in response.text
response = client.get(f"{request_prefix}/openapi.json")
assert response.status_code == 200
def test_api(client: TestClient, params: Params): def test_api(client: TestClient, path_prefix: str):
request_prefix = params["request_prefix"] response = client.get(f"{path_prefix}/users/john")
assert response.request.url == f"http://server{path_prefix}/users/john"
response = client.get(f"{request_prefix}/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"