How to test Python 3.4 asyncio code?

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

    Really like the async_test wrapper mentioned in https://stackoverflow.com/a/23036785/350195, here is an updated version for Python 3.5+

    def async_test(coro):
        def wrapper(*args, **kwargs):
            loop = asyncio.new_event_loop()
            return loop.run_until_complete(coro(*args, **kwargs))
        return wrapper
    
    
    
    class TestSocketConnection(unittest.TestCase):
        def setUp(self):
            self.mock_server = MockServer("localhost", 1337)
            self.socket_connection = SocketConnection("localhost", 1337)
    
        @async_test
        async def test_sends_handshake_after_connect(self):
            await self.socket_connection.connect()
            self.assertTrue(self.mock_server.received_handshake())
    

提交回复
热议问题