sanic-org / sanic-testing

Test clients for Sanic
https://sanic.dev/en/plugins/sanic-testing/getting-started.html
MIT License
31 stars 19 forks source link

What is the best way to app.purge_tasks()? #34

Closed Vedant-R closed 2 years ago

Vedant-R commented 2 years ago

For every test I run, my tests pass but I get the following error:

Task was destroyed but it is pending!
task: <Task pending name='Task-22' coro=<ModelRunner.model_runner() running at /opt/url-ml-server/app/request_batching/model_runner.py:77> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f665dd762b0>()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-11' coro=<ModelRunner.model_runner() running at /opt/url-ml-server/app/request_batching/model_runner.py:77> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f665dd762b0>()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-50' coro=<ModelRunner.model_runner() running at /opt/url-ml-server/app/request_batching/model_runner.py:77> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f665dd762b0>()]>>

@ahopkins Is there a way to purge tasks before app/server stops to avoid above warnings?

ahopkins commented 2 years ago

Yes...

@app.after_server_stop
async def cleanup(app: Sanic, _):
    for task in asyncio.all_tasks():
        if task is not asyncio.current_task():
            while not task.done():
                await task
ahopkins commented 2 years ago

app.purge_tasks is meant to be used to just cleanup after tasks that have already run to completion.

If you are on the latest version of Sanic (which I am assuming you are since you brought up purge_tasks, you have another option.

The above snippet is a sort of graceful shutdown. But, Sanic 21.12 will do this for you for any NAMED tasks.

So, if you did app.add_task(something, name="hello"), then Sanic will track that task for you and clean it up.

v22.3 will probably take it one step further and cleanup all tasks. But, I am still working on that.

Vedant-R commented 2 years ago

Thanks for the info @ahopkins I am using Sanic version 21.6.0.

I understood the logic here.