运行测试 RuntimeError 时收到错误:IOLoop 已在运行。该怎么办?

Ser*_*hiy 2 tornado pytest python-3.x

尝试在 Tornado 中为 Web 身份验证编写测试。但接收错误:

C:\python3\lib\site-packages\tornado\testing.py:402: in fetch
return self.wait()
C:\python3\lib\site-packages\tornado\testing.py:323: in wait
self.io_loop.start()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <tornado.platform.select.SelectIOLoop object at 0x00B73B50>

def start(self):
    if self._running:
Run Code Online (Sandbox Code Playgroud)
      raise RuntimeError("IOLoop is already running")
Run Code Online (Sandbox Code Playgroud)

E RuntimeError: IOLoop 已经在运行

不知道该怎么办。需要帮助。这里是代码:

import pytest
import tornado
from tornado.testing import AsyncTestCase
from tornado.testing import AsyncHTTPTestCase
from tornado.httpclient import AsyncHTTPClient
from tornado.httpserver import HTTPServer
from tests.commons.testUtils import TestUtils
from tornado.web import Application, RequestHandler
import urllib.parse
from handlers.authentication.restAuthHandlers import RESTAuthHandler
import app


class TestRESTAuthHandler(AsyncHTTPTestCase):
def get_app(self):
    return app

@tornado.testing.gen_test
def test_http_fetch_login(self):
    data = urllib.parse.urlencode(dict(username='user', password='123456'))
    response = self.fetch("http://localhost:8888/web/auth/login", method="POST", body=data)
    self.assertIn('http test', response.body)
Run Code Online (Sandbox Code Playgroud)

Ben*_*ell 5

AsyncHTTPTestCase 支持两种模式:使用self.stop和的传统/传统模式self.wait,以及使用 的较新模式@gen_test。为一种模式设计的功能在另一种模式下不起作用;self.fetch专为前一种模式设计。

您可以通过两种方式编写此测试。首先,使用 self.fetch,与您编写的完全一样,但@gen_test移除了装饰器。其次,这是带有@gen_test以下内容的版本:

@tornado.testing.gen_test
def test_http_fetch_login(self):
    data = urllib.parse.urlencode(dict(username='user', password='123456'))
    response = yield self.http_client.fetch("http://localhost:8888/web/auth/login", method="POST", body=data)
    self.assertIn('http test', response.body)
Run Code Online (Sandbox Code Playgroud)

不同之处在于使用了yield self.http_client.fetch而不是self.fetch。该@gen_test版本大多更“现代”,并允许您像编写应用程序一样编写测试,但它有一个很大的缺点:您可以调用self.fetch('/')它,它会自动填写为测试启动的服务器的主机和端口,但在self.http_client.fetch你必须构建完整的 url。