I need to call a task every second (say) to poll some sensor data on a piece of hardware. In the unit test, all I want to do, is to check that the right methods are called and that errors (such as sensor has blown up or vanished) do get caught.
Here is a toy example that mimics the real code:
import pytest
import asyncio
import mock
async def ook(func):
while True:
await asyncio.sleep(1)
func()
@pytest.mark.asyncio
async def test_ook():
func = mock.Mock()
await ook(func)
assert func.called is True
As expected, running this will block forever.
How can I cancel the ook task so that the unit test does not block?
A work around would be to split the loop into another function and define it as no testable. I want to avoid doing that. Note also that messing with func (to call loop.close() or some such) does not work either as it is there just so the toy example test can assert something.