2018-10-29 14:46:42 +00:00
|
|
|
import asyncio
|
|
|
|
|
2018-10-02 10:40:08 +00:00
|
|
|
from starlette.background import BackgroundTask
|
2018-10-29 14:46:42 +00:00
|
|
|
from starlette.responses import Response
|
2018-10-02 10:40:08 +00:00
|
|
|
from starlette.testclient import TestClient
|
|
|
|
|
|
|
|
|
|
|
|
def test_async_task():
|
2018-10-02 11:29:44 +00:00
|
|
|
TASK_COMPLETE = False
|
|
|
|
|
2018-10-02 10:40:08 +00:00
|
|
|
async def async_task():
|
2018-10-02 11:29:44 +00:00
|
|
|
nonlocal TASK_COMPLETE
|
|
|
|
TASK_COMPLETE = True
|
2018-10-02 10:40:08 +00:00
|
|
|
|
|
|
|
task = BackgroundTask(async_task)
|
|
|
|
|
|
|
|
def app(scope):
|
|
|
|
async def asgi(receive, send):
|
|
|
|
response = Response(
|
|
|
|
"task initiated", media_type="text/plain", background=task
|
|
|
|
)
|
|
|
|
await response(receive, send)
|
|
|
|
|
|
|
|
return asgi
|
|
|
|
|
|
|
|
client = TestClient(app)
|
|
|
|
response = client.get("/")
|
|
|
|
assert response.text == "task initiated"
|
2018-10-02 11:29:44 +00:00
|
|
|
assert TASK_COMPLETE
|
2018-10-02 10:40:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_sync_task():
|
2018-10-02 11:29:44 +00:00
|
|
|
TASK_COMPLETE = False
|
|
|
|
|
2018-10-02 10:40:08 +00:00
|
|
|
def sync_task():
|
2018-10-02 11:29:44 +00:00
|
|
|
nonlocal TASK_COMPLETE
|
|
|
|
TASK_COMPLETE = True
|
2018-10-02 10:40:08 +00:00
|
|
|
|
|
|
|
task = BackgroundTask(sync_task)
|
|
|
|
|
|
|
|
def app(scope):
|
|
|
|
async def asgi(receive, send):
|
|
|
|
response = Response(
|
|
|
|
"task initiated", media_type="text/plain", background=task
|
|
|
|
)
|
|
|
|
await response(receive, send)
|
|
|
|
|
|
|
|
return asgi
|
|
|
|
|
|
|
|
client = TestClient(app)
|
|
|
|
response = client.get("/")
|
|
|
|
assert response.text == "task initiated"
|
2018-10-02 11:29:44 +00:00
|
|
|
assert TASK_COMPLETE
|