How to test Python 3.4 asyncio code?

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

    I usually define my async tests as coroutines and use a decorator for "syncing" them:

    import asyncio
    import unittest
    
    def sync(coro):
        def wrapper(*args, **kwargs):
            loop = asyncio.get_event_loop()
            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)
    
        @sync
        async def test_sends_handshake_after_connect(self):
            await self.socket_connection.connect()
            self.assertTrue(self.mock_server.received_handshake())
    

提交回复
热议问题