1

我正在为我的应用程序进行一些功能测试。根据登录用户的权限,侧边栏会有不同的链接。我正在参数化它们(硬编码)并运行一个运行良好的测试(应用程序是一个 webtest 应用程序):

endpoints = [
'/',
'/endpoint1', 
'endpoint2',
...
]

@pytest.mark.parametrize('endpoint', endpoints)
def test_endpoints(endpoint, app):
  res = app.get(endpoint).maybe_follow()
  assert res.status_code == 200

我想避免为每种类型的用户硬编码链接列表。在一个夹具中,我实际上可以通过编程方式获取它们,所以理想情况下,我想参数化这个夹具的返回值,以便运行上面的测试函数:


@pytest.fixture
def endpoints(app):
    res = app.get('/login').follow()
    sidebar_links = []
    for link in res.html.ul.find_all('a'):
        if link.has_attr('href') and not link['href'].startswith('#'):
            sidebar_links.append(link['href'])

    return sidebar_links

这可能吗?

4

1 回答 1

0

我建议您改用 pytest_configure() 挂钩,因为此方法将在您的所有测试方法之前运行。在 conftest.py 文件中,您可以将全局变量保留为 pytest.endpoints= [] 然后稍后在钩子方法中继续将端点的值附加到该变量中,如下所示

pytest.endpoints= []

def pytest_configure(config,app):

    res = app.get('/login').follow()

    for link in res.html.ul.find_all('a'):
        if link.has_attr('href') and not link['href'].startswith('#'):
            pytest.endpoints.append(link['href'])

在测试方法中使用相同的变量作为参数,如下所示

@pytest.mark.parametrize("endpoint",pytest.endpoints)
def test_endpoints(endpoint):

好吧,我并不完全了解您的设计,因此我无法提供任何进一步的建议,但您可以尝试一下。

于 2021-09-29T17:59:19.177 回答