I’m looking to test an app that performs some work in background tasks. And I’m using the ReusableClient because I need to test scenarios that are made up of a sequence of requests. But it’s not working:
import asyncio
import time
from sanic import Sanic, json
from sanic_testing.reusable import ReusableClient
app = Sanic("Demo")
@app.before_server_start
async def init(app):
app.ctx.val = False
async def setval(app):
await asyncio.sleep(1)
app.ctx.val = True
@app.get("/val")
async def getval(request):
request.app.add_task(setval)
return json(app.ctx.val)
def test_app():
client = ReusableClient(app)
with client:
_, resp = client.get("/val")
assert resp.json is False
time.sleep(3)
_, resp = client.get("/val")
assert resp.json is True, resp.json
Running the test_app()
test through pytest
fails, because val
is never updated to True
. I don’t think the background tasks are being launched here, and I can’t figure out why…
Would greatly appreciate any pointers or suggestions on how to test such apps.