PyTest Tornado:'SimpleAsyncHTTPClient' 不可迭代

PyTest Tornado: 'SimpleAsyncHTTPClient' is not iterable

尝试在PyTest、Tornado下制作长轮询的测试代码。

我的测试代码在下面。

conftest.py

from tornado.httpclient import  AsyncHTTPClient


@pytest.fixture
async def tornado_server():
    print("\ntornado_server()")

@pytest.fixture
async def http_client(tornado_server):
    client = AsyncHTTPClient()
    return client


@pytest.yield_fixture(scope='session')
def event_loop(request):
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

test_my.py

from tornado.httpclient import HTTPRequest, HTTPError
def test_http_client(event_loop):
    url = 'http://httpbin.org/get'
    resp = event_loop.run_until_complete(http_client(url))
    assert b'HTTP/1.1 200 OK' in resp

我预计这个结果会成功。 但是失败了。

def test_http_client(event_loop):
    url = 'http://httpbin.org/get'
    resp = event_loop.run_until_complete(http_client(url))
   assert b'HTTP/1.1 200 OK' in resp E       TypeError: argument of type 'SimpleAsyncHTTPClient' is not iterable

我做错了什么?

在 test_http_client() 函数中尝试 assert "200" in resp.codeassert "OK" in resp.reason

分配给 resp 的对象是 AsyncHTTPClient,而不是响应本身。要调用响应消息,您需要 resp.code, resp.reason, resp.body, resp.headers

这是您可以调用的事物的列表http://www.tornadoweb.org/en/stable/httpclient.html#response-objects

  1. 要使用 pytest fixture,您必须将其列为函数的参数:

    def test_http_client(event_loop, http_client):
    
  2. AsyncHTTPClient 不可调用;它有一个 fetch 方法:

    resp = event_loop.run_until_complete(http_client.fetch(url))
    

您的代码中发生的事情是您调用夹具而不是让 pytest 初始化它,并将 url 作为其 tornado_server 参数传递。

还可以考虑使用 pytest-asynciopytest-tornado,这样您就可以使用 await 而不是 run_until_complete(这是将 pytest 与 tornado 或 asyncio 结合使用的常用方法) :

@pytest.mark.asyncio
async def test_http_client(http_client):
    url = 'http://httpbin.org/get'
    resp = await http_client.fetch(url)
    assert resp.code == 200