[英]Run tornado.testing.AsyncTestCase using asyncio event loop
I have an asyncio based class which I want to unit test. 我有一个基于asyncio的类,我想进行单元测试。 Using
tornado.testing.AsyncTestCase
this works quite well and easily. 使用
tornado.testing.AsyncTestCase
这非常有效。 However, one specific method of my class uses asyncio.ensure_future
to schedule execution of another method. 但是,我的类的一个特定方法使用
asyncio.ensure_future
来安排另一个方法的执行。 This never finishes in the AsyncTestCase
, because the default test runner uses the tornado KQueueIOLoop
event loop, not an asyncio event loop. 这永远不会在
AsyncTestCase
完成,因为默认测试运行器使用龙卷风KQueueIOLoop
事件循环,而不是asyncio事件循环。
class TestSubject:
def foo(self):
asyncio.ensure_future(self.bar())
async def bar(self):
pass
class TestSubjectTest(AsyncTestCase):
def test_foo(self):
t = TestSubject()
# here be somewhat involved setup with MagicMock and self.stop
t.foo()
self.wait()
$ python -m tornado.testing baz.testsubject_test
...
[E 160627 17:48:22 testing:731] FAIL
[E 160627 17:48:22 base_events:1090] Task was destroyed but it is pending!
task: <Task pending coro=<TestSubject.bar() running at ...>>
.../asyncio/base_events.py:362: RuntimeWarning: coroutine 'TestSubject.bar' was never awaited
How can I use a different event loop to run the tests on to ensure my task will actually be executed? 如何使用不同的事件循环来运行测试以确保我的任务实际执行? Alternatively, how can I make my implementation event loop-independent and cross-compatible?
或者,如何使我的实现事件独立于循环并交叉兼容?
Turns out to be simple enough... 结果很简单......
class TestSubjectTest(AsyncTestCase):
def get_new_ioloop(self): # override this method
return tornado.platform.asyncio.AsyncIOMainLoop()
I was trying this before, but directly returned asyncio.get_event_loop()
, which didn't work. 我之前尝试过这个,但是直接返回了
asyncio.get_event_loop()
,但是没有用。 Returning Tornado's asyncio loop wrapper does the trick. 返回Tornado的asyncio循环包装就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.