I am using py.test and wonder if/how it is possible to retrieve the name of the currently executed test within the setup
method that is invoked before running each test. Consider this code:
class TestSomething(object): def setup(self): test_name = ... def teardown(self): pass def test_the_power(self): assert "foo" != "bar" def test_something_else(self): assert True
Right before TestSomething.test_the_power
becomes executed, I would like to have access to this name in setup
as outlined in the code via test_name = ...
so that test_name
== "TestSomething.test_the_power"
.
Actually, in setup
, I allocate some resource for each test. In the end, looking at the resources that have been created by various unit tests, I would like to be able to see which one was created by which test. Best thing would be to just use the test name upon creation of the resource.
With no arguments, pytest looks at the current working directory (or some other preconfigured directory) and all subdirectories for test files and runs the test code it finds. Running all test files in the current directory. We can run a specific test file by giving its name as an argument.
Pytest allows us to use markers on test functions. Markers are used to set various features/attributes to test functions. Pytest provides many inbuilt markers such as xfail, skip and parametrize. Apart from that, users can create their own marker names.
pytest plugins can implement hook wrappers which wrap the execution of other hook implementations. A hook wrapper is a generator function which yields exactly once. When pytest invokes hooks it first executes hook wrappers and passes the same arguments as to the regular hooks.
You can also do this using the Request Fixture like this:
def test_name1(request): testname = request.node.name assert testname == 'test_name1'
You can also use the PYTEST_CURRENT_TEST
environment variable set by pytest for each test case.
PYTEST_CURRENT_TEST environment variable
To get just the test name:
os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With