在 pytest 中,如何访问传递给测试的参数? [英] In pytest, how can I access the parameters passed to a test?
问题描述
在 pytest 中,我可以将参数传递给测试(使用夹具或装饰器 @pytest.fixture(params=list-of-params)
).
In pytest, I can pass parameters to test (using fixtures or the decorator @pytest.fixture(params=list-of-params)
).
测试完成后,如果测试失败,则通过的参数显示在结果中,如 TestCheckoutPage.test_address_edit[True]
或 False
如果这是假的.
When the tests are done, if a test fails, the parameter that was passed is shown on the results, as in TestCheckoutPage.test_address_edit[True]
or False
if it was false.
如何访问这些参数并将它们添加到终结器中?request.param
似乎不起作用,即使这是制作夹具时获取参数的方式:
How can I access those parameters and add them to a finalizer? request.param
doesn't seem to work, even though that is how you would get the parameter when making a fixture:
@pytest.fixture(params=[True, False])
def user(request):
return request.param
那行得通.但是,如果我尝试将其传递给测试:
That works. But if I try to pass it to a test:
class TestClass:
def test_something(self, user):
pass
然后,使用自动使用装置来收集有关它的信息:
And then, using an autouse fixture to collect info on it:
@pytest.fixture(autouse=True)
def set_driver(self, request):
print request.param
这会抛出一个错误,说FixtureRequest
中没有param
.
That throws an error, saying there is no param
in FixtureRequest
.
有什么办法可以恢复那个参数吗?我试图让 Selenium 在测试失败时截取屏幕截图,但是因为带有参数的测试具有相同的名称和类名等等,它正在为第一次执行编写一个文件,然后在第二次、第三次、...,时间.所以我想将参数添加到文件名中以避免这种情况.
Is there a way that I can get that parameter back? I'm trying to have Selenium take a screenshot when tests fail, but because tests with parameters have the same name and classname and all, it is writing a file for the first execution, and then overwriting it the second, third, ..., time around. So I would like to add the parameter to the file name to avoid this.
谢谢!
推荐答案
确实,request.param
仅在定义了参数化的夹具函数中可用.如果您需要 set_driver
固定装置中的 user
,您可以试试这个:
Indeed,request.param
is only available in the fixture function where the parametrization is defined. If you need user
in the set_driver
fixture you can try this:
import pytest
@pytest.fixture(params=[True, False])
def user(request):
return request.param
class TestHello:
@pytest.fixture(autouse=True)
def set_driver(self, user):
print "set_driver sees", user
def test_method(self):
assert 0
如果您只想让 set_driver
在 user
实际参与测试时做一些事情,那么您可以这样做:
If you only want to have set_driver
do something if user
is actually involved in the test, then you could do something like this:
import pytest
@pytest.fixture(params=[True, False], scope="module")
def user(request):
return request.param
@pytest.fixture(autouse=True)
def set_driver(request):
if "user" in request.fixturenames:
user = request.getfuncargvalue("user")
print "set_driver sees", user
def test_function(user):
assert 0
def test_function_nouser():
assert 0
这篇关于在 pytest 中,如何访问传递给测试的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!