How to test Python 3.4 asyncio code?

前端 未结 10 1283
遇见更好的自我
遇见更好的自我 2020-12-02 05:38

What\'s the best way to write unit tests for code using the Python 3.4 asyncio library? Assume I want to test a TCP client (SocketConnection):

10条回答
  •  情话喂你
    2020-12-02 06:26

    You can also use aiounittest that takes similar approach as @Andrew Svetlov, @Marvin Killing answers and wrap it in easy to use AsyncTestCase class:

    import asyncio
    import aiounittest
    
    
    async def add(x, y):
        await asyncio.sleep(0.1)
        return x + y
    
    class MyTest(aiounittest.AsyncTestCase):
    
        async def test_async_add(self):
            ret = await add(5, 6)
            self.assertEqual(ret, 11)
    
        # or 3.4 way
        @asyncio.coroutine
        def test_sleep(self):
            ret = yield from add(5, 6)
            self.assertEqual(ret, 11)
    
        # some regular test code
        def test_something(self):
            self.assertTrue(true)
    

    As you can see the async case is handled by AsyncTestCase. It supports also synchronous test. There is a possibility to provide custom event loop, just override AsyncTestCase.get_event_loop.

    If you prefer (for some reason) the other TestCase class (eg unittest.TestCase), you might use async_test decorator:

    import asyncio
    import unittest
    from aiounittest import async_test
    
    
    async def add(x, y):
        await asyncio.sleep(0.1)
        return x + y
    
    class MyTest(unittest.TestCase):
    
        @async_test
        async def test_async_add(self):
            ret = await add(5, 6)
            self.assertEqual(ret, 11)
    

提交回复
热议问题