from starlette.responses import Response
from starlette.background import BackgroundTask
from starlette.testclient import TestClient
import asyncio


def test_async_task():
    async def async_task():
        count = 0
        for num in range(3):
            count += 1
            await asyncio.sleep(1)
        return count

    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"


def test_sync_task():
    def sync_task():
        num = 500
        count = 0
        while count != num:
            count += 1
        return count

    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"

@@ -162,24 +162,51 @@
 ync_task():%0A
+    TASK_COMPLETE = False%0A%0A
     async de
@@ -233,125 +233,59 @@
     
-count = 0%0A        for num in range(3):%0A            count += 1%0A            await asyncio.sleep(1)%0A        return count
+nonlocal TASK_COMPLETE%0A        TASK_COMPLETE = True
 %0A%0A  
@@ -671,16 +671,41 @@
 tiated%22%0A
+    assert TASK_COMPLETE%0A
 %0A%0Adef te
@@ -728,132 +728,111 @@
     
-def sync_task():%0A        num = 500%0A        count = 0%0A        while count != num:%0A            count += 1%0A        return count
+TASK_COMPLETE = False%0A%0A    def sync_task():%0A        nonlocal TASK_COMPLETE%0A        TASK_COMPLETE = True
 %0A%0A  
@@ -1197,28 +1197,53 @@
 se.text == %22task initiated%22%0A
+    assert TASK_COMPLETE%0A

Update background task tests