asynctest

0.13.0 · maintenance · verified Mon Apr 06

asynctest is a Python library that enhances the standard `unittest` package with features tailored for testing `asyncio` applications. It reduces boilerplate by providing `TestCase` subclasses and mock objects designed to work seamlessly with coroutines and event loops. While built on `unittest`, it overrides and adds features for asynchronous testing, currently targeting the 'selector' model. The current version is 0.13.0, and its release cadence has been infrequent, indicating a maintenance status.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an asynchronous test case using `asynctest.TestCase`, defining an `async def` test method, and how to use `asynctest.CoroutineMock` to mock asynchronous functions. Tests are automatically run within their own event loop, which is managed by `asynctest`.

import asynctest
import asyncio

class MyAsyncTest(asynctest.TestCase):
    async def my_async_function(self):
        # Simulate an asynchronous operation
        await asyncio.sleep(0.001)
        return "async_result"

    async def test_my_async_method(self):
        result = await self.my_async_function()
        self.assertEqual(result, "async_result")

    async def test_with_coroutine_mock(self):
        mock_return = "mocked_async_data"
        my_mock = asynctest.CoroutineMock(return_value=mock_return)
        
        # Call the mocked coroutine
        data = await my_mock()
        
        self.assertEqual(data, mock_return)
        my_mock.assert_awaited_once()

# To run these tests, save the file (e.g., test_my_module.py) and run:
# python -m unittest test_my_module.py
# asynctest.main() can also be used if explicitly desired, but unittest discovery works.

view raw JSON →