[英]In pytest, how can I access the parameters passed to a test?
In pytest, I can pass parameters to test (using fixtures or the decorator @pytest.fixture(params=list-of-params)
). 在pytest中,我可以传递参数以进行测试(使用固定装置或装饰器
@pytest.fixture(params=list-of-params)
)。
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. 当测试完成后,如果测试失败,这是传递的参数显示在结果,如
TestCheckoutPage.test_address_edit[True]
或False
,如果它是假的。
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: request.param
似乎不起作用,即使这是制作固定装置时获取参数的方式:
@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
That throws an error, saying there is no param
in FixtureRequest
. 抛出一个错误,说
FixtureRequest
没有param
。
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.
我试图让Selenium在测试失败时拍摄屏幕截图,但是由于带有参数的测试具有相同的名称,类名以及所有名称,因此它正在为第一次执行写入文件,然后在第二,第三,第三次执行时覆盖它。 ,时间到了。 So I would like to add the parameter to the file name to avoid this.
因此,我想在文件名中添加参数以避免这种情况。
Thanks! 谢谢!
Indeed, request.param
is only available in the fixture function where the parametrization is defined. 实际上,
request.param
仅在定义了参数化的fixture函数中可用。 If you need user
in the set_driver
fixture you can try this: 如果您需要
set_driver
固定装置中的user
,则可以尝试以下操作:
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
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: 如果您只想让
set_driver
在user
确实参与测试的情况下执行某项操作,则可以执行以下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.