How to test Python 3.4 asyncio code?

前端 未结 10 1298
遇见更好的自我
遇见更好的自我 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:17

    In addition to pylover's answer, if you intend to use some other asynchronous method from the test class itself, the following implementation will work better -

    import asyncio
    import unittest
    
    class AioTestCase(unittest.TestCase):
    
        # noinspection PyPep8Naming
        def __init__(self, methodName='runTest', loop=None):
            self.loop = loop or asyncio.get_event_loop()
            self._function_cache = {}
            super(AioTestCase, self).__init__(methodName=methodName)
    
        def coroutine_function_decorator(self, func):
            def wrapper(*args, **kw):
                return self.loop.run_until_complete(func(*args, **kw))
            return wrapper
    
        def __getattribute__(self, item):
            attr = object.__getattribute__(self, item)
            if asyncio.iscoroutinefunction(attr) and item.startswith('test_'):
                if item not in self._function_cache:
                    self._function_cache[item] = 
                        self.coroutine_function_decorator(attr)
                return self._function_cache[item]
            return attr
    
    
    class TestMyCase(AioTestCase):
    
        async def multiplier(self, n):
            await asyncio.sleep(1)  # just to show the difference
            return n*2
    
        async def test_dispatch(self):
            m = await self.multiplier(2)
            self.assertEqual(m, 4)
    

    the only change was - and item.startswith('test_') in the __getattribute__ method.

提交回复
热议问题