How to test Python 3.4 asyncio code?

前端 未结 10 1289
遇见更好的自我
遇见更好的自我 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条回答
  •  旧时难觅i
    2020-12-02 06:13

    I temporarily solved the problem using a decorator inspired by Tornado's gen_test:

    def async_test(f):
        def wrapper(*args, **kwargs):
            coro = asyncio.coroutine(f)
            future = coro(*args, **kwargs)
            loop = asyncio.get_event_loop()
            loop.run_until_complete(future)
        return wrapper
    

    Like J.F. Sebastian suggested, this decorator will block until the test method coroutine has finished. This allows me to write test cases like this:

    class TestSocketConnection(unittest.TestCase):
        def setUp(self):
            self.mock_server = MockServer("localhost", 1337)
            self.socket_connection = SocketConnection("localhost", 1337)
    
        @async_test
        def test_sends_handshake_after_connect(self):
            yield from self.socket_connection.connect()
            self.assertTrue(self.mock_server.received_handshake())
    

    This solution probably misses some edge cases.

    I think a facility like this should added to Python's standard library to make asyncio and unittest interaction more convenient out of the box.

提交回复
热议问题