I'm currently writing some async tests with pytest and found myself running into the following situation.
Consider we have an asyncio.Queue
called peer2_subscriber
that we want to check if it received a certain message (after triggering some action, omitted for brevity)
peer, cmd, msg = await asyncio.wait_for(
peer2_subscriber.get(),
timeout=1,
)
assert peer == peer2
assert isinstance(cmd, Transactions)
assert msg[0].hash == txs[0].hash
Now, consider that I want to test that another asyncio.Queue
did NOT something pushed.
I found myself creating such a helper method.
async def wait_with_fallback(fn, fallback):
try:
return await asyncio.wait_for(
fn(),
timeout=1
)
except asyncio.TimeoutError:
return fallback
And then in the test I write something like:
val = await wait_with_fallback(
peer1_subscriber.get,
None
)
assert val == None
I wonder if there's an existing pattern that I'm missing?
Your pattern works, so I would say it's "correct", for certain values of correct… It's mostly stylistic views here. I would write either
await asyncio.sleep(1)
assert peer1_subscriber.empty()
or
await asyncio.sleep(1)
val = peer1_subscriber.get_nowait()
assert val is None