Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

py.test: how to get the current test's name from the setup method?

Tags:

python

pytest

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.

like image 811
Dr. Jan-Philip Gehrcke Avatar asked Jul 18 '13 14:07

Dr. Jan-Philip Gehrcke


People also ask

What is the name of the directory that pytest will look at to detect tests?

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.

What is pytest mark?

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.

What is pytest hook?

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.


2 Answers

You can also do this using the Request Fixture like this:

def test_name1(request):     testname = request.node.name     assert testname == 'test_name1' 
like image 200
danielfrg Avatar answered Sep 18 '22 22:09

danielfrg


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] 
like image 41
Joao Coelho Avatar answered Sep 19 '22 22:09

Joao Coelho