问题
In pytest, I can pass parameters to test (using fixtures or the decorator @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.
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
That throws an error, saying there is no param
in FixtureRequest
.
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.
Thanks!
回答1:
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
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
来源:https://stackoverflow.com/questions/13501761/in-pytest-how-can-i-access-the-parameters-passed-to-a-test