我可以以编程方式用参数表示的返回值pytest夹具吗?



我正在为我的应用程序进行一些功能测试。根据登录用户的权限,侧边栏将有不同的链接。我参数化他们(硬编码),并运行一个测试,工作良好(应用程序是一个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

我想避免为每种类型的用户硬编码链接列表。在fixture内部,我实际上可以通过编程方式获得它们,因此理想情况下,我希望对该fixture的返回值进行参数化,以便运行上面的测试函数:


@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

这可能吗?

我建议您使用pytest_configure()钩子,因为该方法将在所有测试方法之前运行。在conftest.py文件中,您可以保留一个全局变量pytest。Endpoints =[],然后在hook方法中继续将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):

嗯,我不完全了解你的设计,所以我不能提出任何进一步的建议,但你可以试一试。