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

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]

The setup and teardown methods seem to be legacy methods for supporting tests written for other frameworks, e.g. nose. The native pytest methods are called setup_method as well as teardown_method which receive the currently executed test method as an argument. Hence, what I want to achieve, can be written like so:

class TestSomething(object):

    def setup_method(self, method):
        print "\n%s:%s" % (type(self).__name__, method.__name__)

    def teardown_method(self, method):
        pass

    def test_the_power(self):
        assert "foo" != "bar"

    def test_something_else(self):
        assert True

The output of py.test -s then is:

============================= test session starts ==============================
platform linux2 -- Python 2.7.3 -- pytest-2.3.3
plugins: cov
collected 2 items 

test_pytest.py 
TestSomething:test_the_power
.
TestSomething:test_something_else
.

=========================== 2 passed in 0.03 seconds ===========================

Tags:

Python

Pytest