首页 > 解决方案 > 使用多台服务器进行 aiohttp 测试

问题描述

尝试进行与 Web 服务器的多个实例(也在它们之间进行通信)进行通信的测试。但是第二个似乎覆盖了第一个,但是我尝试了。有关如何解决此问题的任何建议。

到目前为止,我有这个:

import os
from aiohttp.test_utils import TestClient, TestServer, loop_context
import pytest
from http import HTTPStatus as hs

from mycode import main

@pytest.fixture
def cli(loop):
    app = main(["-t", "--location", "global", "-g"])
    srv = TestServer(app, port=40080)
    client = TestClient(srv, loop=loop)
    loop.run_until_complete(client.start_server())
    return client

@pytest.fixture
def cli_edge(loop):
    app = main(["-t", "--location", "edge", "-j", "http://127.0.0.1:40080"])
    srv = TestServer(app, port=40081)
    client = TestClient(srv, loop=loop)
    loop.run_until_complete(client.start_server())
    return client

async def test_edge_namespace(cli, cli_edge):
    resp = await cli.put('/do/something', json={})
    assert resp.status in [hs.OK, hs.CREATED, hs.NO_CONTENT]
    resp = await cli_edge.get('/do/something')
    assert resp.status in [hs.OK, hs.CREATED, hs.NO_CONTENT]

上面的调用cli.put转到用于cli_edge. 我将有更多的测试应该与服务器通信。

使用带有 asyncio 和 aiohttp 扩展的 Python 3.7 和 pytest。

标签: python-3.xaiohttp

解决方案


建议的代码有效,错误出现在服务器实现的其他地方。

你可以加:

def fin():
    loop.run_until_complete(srv.close())
    loop.run_until_complete(client.close())
request.addfinalizer(fin)

requestpytest 固定装置中的参数可以很好地关闭连接。


推荐阅读