| 1 |
import importlib |
| 2 |
from types import ModuleType |
| 3 |
|
| 4 |
import pytest |
| 5 |
from fastapi.exceptions import FastAPIError |
| 6 |
from fastapi.testclient import TestClient |
| 7 |
|
| 8 |
|
| 9 |
@pytest.fixture( |
| 10 |
name="mod", |
| 11 |
params=[ |
| 12 |
pytest.param("tutorial008c_py310"), |
| 13 |
pytest.param("tutorial008c_an_py310"), |
| 14 |
], |
| 15 |
) |
| 16 |
def get_mod(request: pytest.FixtureRequest): |
| 17 |
mod = importlib.import_module(f"docs_src.dependencies.{request.param}") |
| 18 |
|
| 19 |
return mod |
| 20 |
|
| 21 |
|
| 22 |
def test_get_no_item(mod: ModuleType): |
| 23 |
client = TestClient(mod.app) |
| 24 |
response = client.get("/items/foo") |
| 25 |
assert response.status_code == 404, response.text |
| 26 |
assert response.json() == {"detail": "Item not found, there's only a plumbus here"} |
| 27 |
|
| 28 |
|
| 29 |
def test_get(mod: ModuleType): |
| 30 |
client = TestClient(mod.app) |
| 31 |
response = client.get("/items/plumbus") |
| 32 |
assert response.status_code == 200, response.text |
| 33 |
assert response.json() == "plumbus" |
| 34 |
|
| 35 |
|
| 36 |
def test_fastapi_error(mod: ModuleType): |
| 37 |
client = TestClient(mod.app) |
| 38 |
with pytest.raises(FastAPIError) as exc_info: |
| 39 |
client.get("/items/portal-gun") |
| 40 |
assert "raising an exception and a dependency with yield" in exc_info.value.args[0] |
| 41 |
|
| 42 |
|
| 43 |
def test_internal_server_error(mod: ModuleType): |
| 44 |
client = TestClient(mod.app, raise_server_exceptions=False) |
| 45 |
response = client.get("/items/portal-gun") |
| 46 |
assert response.status_code == 500, response.text |
| 47 |
assert response.text == "Internal Server Error" |