AsyncTestCase

Extends unittest.TestCase to support asynchronous tests. Currently the most common solution is to explicitly run asyncio.run_until_complete with test case. Aiounittest AsyncTestCase wraps it, to keep the test as clean and simple as possible.

class aiounittest.AsyncTestCase(methodName='runTest')[source]

AsyncTestCase allows to test asynchoronus function.

The usage is the same as unittest.TestCase. It works with other test frameworks and runners (eg. pytest, nose) as well.

This class can run:
  • test of synchronous code (unittest.TestCase)
  • test of asynchronous code, supports syntax with async/await (Python 3.5+) and asyncio.coroutine/yield from (Python 3.4)

Code to test:

import asyncio

async def async_add(x, y, delay=0.1):
    await asyncio.sleep(delay)
    return x + y

async def async_one():
    await async_nested_exc()

async def async_nested_exc():
    await asyncio.sleep(0.1)
    raise Exception('Test')

Tests:

import aiounittest

class MyTest(aiounittest.AsyncTestCase):

    async def test_await_async_add(self):
        ret = await async_add(1, 5)
        self.assertEqual(ret, 6)

    async def test_await_async_fail(self):
        with self.assertRaises(Exception) as e:
            await async_one()
get_event_loop()[source]

This method provide event loop for the test

It is called before each test, by default aiounittest.AsyncTestCase creates the brand new event loop everytime. After completion, the loop is closed and then recreated, set as default, leaving asyncio clean.

Note

This is the most common and the recommended way. But, if for some reasons you want to provide your own event loop just override it. Note that AsyncTestCase won’t close such a loop

class MyTest(aiounittest.AsyncTestCase):

    def get_event_loop(self):
        self.my_loop = asyncio.get_event_loop()
        return self.my_loop