gpt4 book ai didi

python - PyTest Tornado : 'SimpleAsyncHTTPClient' is not iterable

转载 作者:行者123 更新时间:2023-12-01 01:37:23 24 4
gpt4 key购买 nike

尝试在 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

我做错了什么?

最佳答案

  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

关于python - PyTest Tornado : 'SimpleAsyncHTTPClient' is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com