代码之家  ›  专栏  ›  技术社区  ›  sungyong

pytest tornado:“simpleAsynchHttpClient”不可iterable

  •  1
  • sungyong  · 技术社区  · 6 年前

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

    我做错了什么?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ben Darnell    6 年前
    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
    
        2
  •  1
  •   DJSDev    6 年前

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