Python Glossary Русский

Python 3.8+unittestterm

unittest.IsolatedAsyncioTestCase

testing

A base class for testing asynchronous code: test_ methods may be async def, and every test runs in its own event loop.

Syntax

class MyTests(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self): ...
    async def test_x(self): ...

Setup that needs await goes into asyncSetUp and asyncTearDown, not setUp, where await is unavailable. A fresh event loop is created for every test, so a loop-bound object (asyncio.Lock, a Queue, a client connection) built in setUpClass or at module level breaks inside the test. Do not call asyncio.run() inside such a test: a loop is already running and you get RuntimeError.

Examples

import asyncio
import sys
import unittest
async def double(x):
    await asyncio.sleep(0)
    return x * 2
class DoubleTests(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self):
        self.value = await double(5)
    async def test_double(self):
        self.assertEqual(self.value, 10)
suite = unittest.TestLoader().loadTestsFromTestCase(DoubleTests)
result = unittest.TextTestRunner(stream=sys.stdout, verbosity=0).run(suite)
print(result.wasSuccessful())  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy