single app object

This commit is contained in:
Jeremy Epstein 2025-11-25 09:50:14 +11:00
parent 1ea1ff58be
commit f4767e4854
1 changed files with 10 additions and 12 deletions

View File

@ -3,13 +3,12 @@ from anyio import open_file
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app_reraises = FastAPI()
app_doesnt_reraise = FastAPI()
app = FastAPI()
async def get_username_reraises():
try:
async with await open_file("/non_existing/path.txt", "r") as f:
async with await open_file("/nonexistent/path.txt", "r") as f:
yield await f.read() # pragma: no cover
except OSError as ex:
raise RuntimeError("File read error") from ex
@ -17,37 +16,36 @@ async def get_username_reraises():
async def get_username_doesnt_reraise():
try:
async with await open_file("/path/to/sanchez.txt", "r") as f:
async with await open_file("/nonexistent/path.txt", "r") as f:
yield await f.read() # pragma: no cover
except OSError:
print("We didn't re-raise, wubba lubba dub dub!")
print("Didn't re-raise")
@app_reraises.get("/me")
@app.get("/reraises")
def get_me_reraises(username: str = Depends(get_username_reraises)):
return username # pragma: no cover
@app_doesnt_reraise.get("/me")
@app.get("/doesnt-reraise")
def get_me_doesnt_reraise(username: str = Depends(get_username_doesnt_reraise)):
return username # pragma: no cover
client_reraises = TestClient(app_reraises)
client_doesnt_reraise = TestClient(app_doesnt_reraise)
client = TestClient(app)
@pytest.mark.anyio
def test_runtime_error_reraises():
with pytest.raises(RuntimeError) as exc_info:
client_reraises.get("/me")
assert str(exc_info.value) == "File something something, wubba lubba dub dub!"
client.get("/reraises")
assert str(exc_info.value) == "File read error"
@pytest.mark.anyio
def test_runtime_error_doesnt_reraise():
with pytest.raises(RuntimeError) as exc_info:
client_doesnt_reraise.get("/me")
client.get("/doesnt-reraise")
assert str(exc_info.value).startswith(
"Dependency get_username_doesnt_reraise raised: generator didn't yield. "
"There's a high chance that this is a dependency with yield that catches an "