Unit testing 如何进行龙卷风的单元测试+;异步定义?

Unit testing 如何进行龙卷风的单元测试+;异步定义?,unit-testing,asynchronous,tornado,python-3.5,python-unittest,Unit Testing,Asynchronous,Tornado,Python 3.5,Python Unittest,环境:Python 3、tornado 4.4。无法使用普通的单元测试,因为方法是异步的。有ttp://www.tornadoweb.org/en/stable/testing.html 这解释了如何对异步代码进行单元测试。但这只适用于龙卷风协同行动。我要测试的类使用的是async def语句,不能以这种方式测试它们。例如,下面是一个使用ASyncHTTPClient.fetch及其回调参数的测试用例: class MyTestCase2(AsyncTestCase): def test

环境:Python 3、tornado 4.4。无法使用普通的单元测试,因为方法是异步的。有ttp://www.tornadoweb.org/en/stable/testing.html 这解释了如何对异步代码进行单元测试。但这只适用于龙卷风协同行动。我要测试的类使用的是async def语句,不能以这种方式测试它们。例如,下面是一个使用ASyncHTTPClient.fetch及其回调参数的测试用例:

class MyTestCase2(AsyncTestCase):
    def test_http_fetch(self):
        client = AsyncHTTPClient(self.io_loop)
        client.fetch("http://www.tornadoweb.org/", self.stop)
        response = self.wait()
        # Test contents of response
        self.assertIn("FriendFeed", response.body)
但我的方法声明如下:

类连接: 异步def get_数据(url,*args): #

而且没有回调。如何从测试用例中“等待”此方法

更新:根据杰西的回答,我创建了这个MWE:

import unittest

from tornado.httpclient import AsyncHTTPClient
from tornado.testing import AsyncTestCase, gen_test, main


class MyTestCase2(AsyncTestCase):
    @gen_test
    async def test_01(self):
        await self.do_more()

    async def do_more(self):
        self.assertEqual(1+1, 2)

main()
结果是:

>py -3 -m test.py
E
======================================================================
ERROR: all (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'all'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
[E 170205 10:05:43 testing:731] FAIL
没有回溯。但如果我用unittest.main()替换tornado.testing.main(),它就会突然开始工作

但是为什么呢?我猜对于asnyc单元测试,我需要使用tornado.testing.main()

我很困惑

更新2:这是tornado.testing中的一个bug。解决方法:

all = MyTestCase2
main()

不使用self.wait/self.stop回调,您可以在“wait”表达式中使用“fetch”来等待“fetch”完成:

import unittest

from tornado.httpclient import AsyncHTTPClient
from tornado.testing import AsyncTestCase, gen_test


class MyTestCase2(AsyncTestCase):
    @gen_test
    async def test_http_fetch(self):
        client = AsyncHTTPClient(self.io_loop)
        response = await client.fetch("http://www.tornadoweb.org/")
        # Test contents of response
        self.assertIn("FriendFeed", response.body.decode())

unittest.main()

我必须在代码中做的另一个更改是在主体上调用“decode”,以便将主体(字节)与字符串“FriendFeed”进行比较。

尝试用tornado.gen.coroutine修饰测试方法,并使用“yield from”但是这使解释器崩溃了。您可以使用
pytest
调用tornado.testing.main()而不是unittest.main()。非常有趣的是,您的代码可以工作,但我的最小工作示例不起作用。我将更新这个问题如果我用unittest.main()替换tornado.testing.main(),我的例子也会起作用,但我不知道为什么?