如何测试 Python 3.4 异步代码? [英] How to test Python 3.4 asyncio code?

查看:106
本文介绍了如何测试 Python 3.4 异步代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python 3.4 asyncio 库为代码编写单元测试的最佳方法是什么?假设我想测试一个 TCP 客户端(SocketConnection):

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):

import asyncio
import unittest

class TestSocketConnection(unittest.TestCase):
    def setUp(self):
        self.mock_server = MockServer("localhost", 1337)
        self.socket_connection = SocketConnection("localhost", 1337)

    @asyncio.coroutine
    def test_sends_handshake_after_connect(self):
        yield from self.socket_connection.connect()
        self.assertTrue(self.mock_server.received_handshake())

当使用默认测试运行器运行此测试用例时,测试将始终成功,因为该方法只执行到第一个 yield from 指令,之后它在执行任何断言之前返回.这会导致测试总是成功.

When running this test case with the default test runner, the test will always succeed as the method executes only up until the first yield from instruction, after which it returns before executing any assertions. This causes tests to always succeed.

是否有预构建的测试运行器能够处理这样的异步代码?

Is there a prebuilt test runner that is able to handle asynchronous code like this?

推荐答案

自 Python 3.8 unittest 带有 IsolatedAsyncioTestCase 函数,专为此而设计目的.

Since Python 3.8 unittest comes with the IsolatedAsyncioTestCase function, designed for this purpose.

from unittest import IsolatedAsyncioTestCase

class Test(IsolatedAsyncioTestCase):

    async def test_functionality(self):
        result = await functionality()
        self.assertEqual(expected, result)

这篇关于如何测试 Python 3.4 异步代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆