How to test Python 3.4 asyncio code?

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

    async_test, suggested by Marvin Killing, definitely can help -- as well as direct calling loop.run_until_complete()

    But I also strongly recommend to recreate new event loop for every test and directly pass loop to API calls (at least asyncio itself accepts loop keyword-only parameter for every call that need it).

    Like

    class Test(unittest.TestCase):
        def setUp(self):
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(None)
    
        def test_xxx(self):
            @asyncio.coroutine
            def go():
                reader, writer = yield from asyncio.open_connection(
                    '127.0.0.1', 8888, loop=self.loop)
                yield from asyncio.sleep(0.01, loop=self.loop)
            self.loop.run_until_complete(go())
    

    that isolates tests in test case and prevents strange errors like longstanding coroutine that has been created in test_a but finished only on test_b execution time.

提交回复
热议问题