Looking for an Asyncio-Compatible Time Mocking Library

0
11
Asked By CuriousCoder99 On

I'm testing an asyncio application that involves scheduling, and I'm struggling to find a time mocking library that works well with asyncio. Libraries like freezegun and time-machine don't mesh nicely with `asyncio.sleep`, as they actually cause the program to sleep for real, which isn't suitable for testing scenarios that span long durations—like over 24 hours. I've come up with a workaround using a dummy event loop that utilizes a dummy selector, which bypasses I/O operations. While it's functional, I'm curious if there's a library out there that does this more efficiently or has added functionality, particularly for mocking I/O operations too. Has anyone encountered a good solution for this?

4 Answers

Answered By TrioFanatic On

If you can switch from `asyncio`, the `trio` library has built-in support for this kind of functionality. It's well integrated and might save you a lot of hassle.

PragmaticDev -

That's interesting! We have some dependencies tied to `asyncio`, but I'll check out `trio-asyncio` to see if it can help us bridge that gap.

Answered By InjectiveThinking On

In these cases, I prefer injecting the sleep function as a dependency. For instance, you could structure your code like this: `async def schedule(..., _sleep=asyncio.sleep): await _sleep(300)`. During testing, you inject a version of sleep that does nothing. It may seem a bit unconventional, but it's a straightforward approach for dependency injection.

Answered By SnoozeButton On

I just use MagicMock to override `asyncio.sleep`. By changing it to a no-op, your tests run instantly without any delay, which simplifies everything for testing.

Answered By MockingMaster42 On

I haven't found a dedicated package for this, but we created a custom event loop with a controllable clock. The key was realizing that `asyncio.sleep` uses `loop.call_later` with `loop.time()`. If you override `time()`, you can control how sleep works without needing to fake the selector, which might allow real I/O to remain functional.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.