Py学习  »  tornado

pytest tornado:“simpleAsynchHttpClient”不可iterable

sungyong • 7 年前 • 2279 次点击  

尝试在pytest,tornado下为长轮询生成测试代码。

我的测试代码在下面。

混杂的事物

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

TestMy.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

我做错了什么?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/31576
文章 [ 2 ]  |  最新文章 7 年前
jesse
Reply   •   1 楼
jesse    7 年前

尝试 assert "200" in resp.code assert "OK" in resp.reason 在您的测试\u http_client()函数中。

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

这是你可以打电话给我的东西的清单 http://www.tornadoweb.org/en/stable/httpclient.html#response-objects

Ben Darnell
Reply   •   2 楼
Ben Darnell    7 年前
  1. 要使用pytest fixture,必须将其作为函数的参数列出:

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

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

您的代码中发生的事情是您正在调用fixture,而不是让pytest初始化它,并通过 url 作为其 tornado_server 争论。

同时考虑使用 pytest-asyncio pytest-tornado ,允许您使用 await 而不是 run_until_complete (这是在Tornado或Asyncio中使用Pytest的常用方法):

@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