你在哪里传递获取查询参数来测试 aiohttp 端点

Where do you pass get query params to to test aiohttp endpoints

我正在测试我创建的 aiohttp 端点。按照文档中给出的一些方法,下面的代码工作正常。但是,我们在哪里传递端点必须测试的 {name} arg?

所以如果假设我的 url 是 localhost/hello/Alice 并且它打印 Hello Alice。现在在测试用例中,我在哪里传递 Alice 作为名称?另外,如果我只允许 AliceBob 作为有效名称,我的逻辑不支持其余名称怎么办。所以在这种情况下,我需要指定某些名称来查看哪些值有效和无效。

我的问题是如何首先传递某些值,因为我所做的只是一个占位符,而不是在下面的测试用例中传递任何实际名称。

subapp_routes = web.RouteTableDef()

@subapp_routes.get('/{name}')
async def hello_name(request):
    name = request.match_info.get('name')
    txt = "Hello {}\n".format(name)
    return web.Response(text=txt)

@pytest.fixture
def cli(loop, test_client):
    app = web.Application()
    app.router.add_get('/', hello)
    app.router.add_get('/{name}', hello_name)
    return loop.run_until_complete(test_client(app))


async def test_hello(cli):
    resp = await cli.get('/{name}')
    assert resp.status == 200
    text = await resp.text()
    assert 'Hello {name}' in text

简单来说有两种选择:

  1. 自己生成 url 例如。只需使用 resp = await cli.get('/Alice')
  2. 使用应用程序的 url_for 方法生成 urls:
    ...
    app.router.add_get('/{name}', hello_name, name='hello-name')
    ...

async def test_hello(cli):
    url = cli.server.app.router['hello-name'].url_for(name='Alice')
    resp = await cli.get(url)
    assert resp.status == 200
    text = await resp.text()
    assert 'Hello {name}' in text

很多例子here

感谢@AndrewSvetlov 和@SColvin。我通过你的两个链接和 Andrew 的实现都提到了我也得到了这个:

@pytest.fixture
def cli(loop, test_client):
    app = web.Application()
    app.router.add_get(r'/{name}', hello_name)
    return loop.run_until_complete(test_client(app))


valid_names = ['Alice', 'Bob']

@pytest.mark.parametrize('name', valid_names)
async def test_hello(name, cli):
    resp = await cli.get('/{}'.format(name))
    assert resp.status == 200
    text = await resp.text()
    print(text)
    assert 'Hello {}'.format(name) in text