Skip to content

Commit

Permalink
Document BackgroundTasks behavior when an error happens (#1605)
Browse files Browse the repository at this point in the history
* Document `BackgroundTasks` behavior when an error happens

* Document `BackgroundTasks` behavior when an error happens
  • Loading branch information
Kludex authored Apr 24, 2022
1 parent 5a9b414 commit decc527
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/background.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,7 @@ routes = [

app = Starlette(routes=routes)
```

!!! important
The tasks are executed in order. In case one of the tasks raises
an exception, the following tasks will not get the opportunity to be executed.
33 changes: 32 additions & 1 deletion tests/test_background.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
from typing import Callable

import pytest

from starlette.background import BackgroundTask, BackgroundTasks
from starlette.responses import Response
from starlette.testclient import TestClient


def test_async_task(test_client_factory):
Expand Down Expand Up @@ -40,7 +45,7 @@ async def app(scope, receive, send):
assert TASK_COMPLETE


def test_multiple_tasks(test_client_factory):
def test_multiple_tasks(test_client_factory: Callable[..., TestClient]):
TASK_COUNTER = 0

def increment(amount):
Expand All @@ -61,3 +66,29 @@ async def app(scope, receive, send):
response = client.get("/")
assert response.text == "tasks initiated"
assert TASK_COUNTER == 1 + 2 + 3


def test_multi_tasks_failure_avoids_next_execution(
test_client_factory: Callable[..., TestClient]
) -> None:
TASK_COUNTER = 0

def increment():
nonlocal TASK_COUNTER
TASK_COUNTER += 1
if TASK_COUNTER == 1:
raise Exception("task failed")

async def app(scope, receive, send):
tasks = BackgroundTasks()
tasks.add_task(increment)
tasks.add_task(increment)
response = Response(
"tasks initiated", media_type="text/plain", background=tasks
)
await response(scope, receive, send)

client = test_client_factory(app)
with pytest.raises(Exception):
client.get("/")
assert TASK_COUNTER == 1

0 comments on commit decc527

Please sign in to comment.