59

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.

2
  • 1
    How about this unittest.TestCase.id()
    – Nam G VU
    Dec 19, 2018 at 13:01
  • Does that work with pytest-style tests (ie standalone functions rather than methods on a class which inherits from TestCase)? Feb 8, 2019 at 19:27

9 Answers 9

118

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

def test_name1(request):
    testname = request.node.name
    assert testname == 'test_name1'
7
  • 18
    This is the general-purpose answer, equally applicable to both test functions and test methods. While py.test documentation is usually spectacular, its documentation for the request fixture is unusually awful. The request.node attribute is documented only as "underlying collection node (depends on current request scope)." That's it. I absolutely never would have found this – and doubt anyone else would have either. Bravo, froggy Daniel! May 23, 2016 at 3:46
  • 25
    Note however when the test function has been parametrized, request.node.name contains the unique name with parameters, e.g. test_name[param-other_param]. Therefore it is safer to always use request.node.originalname, which provides the original function name intact. Also note this is available starting from py.test 3.0.
    – julen
    Dec 12, 2016 at 10:46
  • 4
    There is no mention of the request fixture at your link.
    – OrangeDog
    May 4, 2018 at 14:28
  • 5
    You can also get the module name with request.module.__name__. Jan 18, 2019 at 20:56
  • 1
    Just noting that the documentation is now much clearer on the use of this: docs.pytest.org/en/documentation-restructure/how-to/…
    – robo
    Mar 25, 2021 at 13:55
59

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]
9
  • 7
    Wow, this should be the simplest answer and should be accepted
    – Nam G VU
    Dec 19, 2018 at 12:33
  • Just tested with pytest 4.0.2 and it does work. You might also want to add .strip('[]') to remove more extraneous info. PS: You need to add the code inside the test case. Dec 19, 2018 at 22:02
  • I mean the env varia le not define. Do we need to config pytest somewhere for this?
    – Nam G VU
    Dec 20, 2018 at 0:45
  • 1
    Oh, now I see that it's from the setup method.. not sure if that env var is defined at that point. an alternative is to just run that piece of code (or call it as a separate function) in the beginning of the test. Dec 20, 2018 at 23:43
  • 2
    Note The contents of PYTEST_CURRENT_TEST is meant to be human readable and the actual format can be changed between releases (even bug fixes) so it shouldn’t be relied on for scripting or automation.
    – zowers
    Mar 16, 2021 at 15:56
22

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 ===========================
10

Short answer:

  • Use fixture called request
  • This fixture has the following interesting attributes:
    • request.node.originalname = the name of the function/method
    • request.node.name = name of the function/method and ids of the parameters
    • request.node.nodeid = relative path to the test file, name of the test class (if in a class), name of the function/method and ids of the parameters

Long answer:

I inspected the content of request.node. Here are the most interesting attributes I found:

class TestClass:

    @pytest.mark.parametrize("arg", ["a"])
    def test_stuff(self, request, arg):
        print("originalname:", request.node.originalname)
        print("name:", request.node.name)
        print("nodeid:", request.node.nodeid)

Prints the following:

 originalname: test_stuff
 name: test_stuff[a]
 nodeid: relative/path/to/test_things.py::TestClass::test_stuff[a]

NodeID is the most promising if you want to completely identify the test (including the parameters). Note that if the test is as a function (instead of in a class), the class name (::TestClass) is simply missing.

You can parse nodeid as you wish, for example:

components = request.node.nodeid.split("::")
filename = components[0]
test_class = components[1] if len(components) == 3 else None
test_func_with_params = components[-1]
test_func = test_func_with_params.split('[')[0]
test_params = test_func_with_params.split('[')[1][:-1].split('-')

In my example this results to:

filename = 'relative/path/to/test_things.py'
test_class = 'TestClass'
test_func = 'test_stuff'
test_params = ['a']
4
# content of conftest.py

@pytest.fixture(scope='function', autouse=True)
def test_log(request):
    # Here logging is used, you can use whatever you want to use for logs
    log.info("STARTED Test '{}'".format(request.node.name))  

    def fin():
        log.info("COMPLETED Test '{}' \n".format(request.node.name))

    request.addfinalizer(fin)
2

Try my little wrapper function which returns the full name of the test, the file and the test name. You can use whichever you like later. I used it within conftest.py where fixtures do not work as far as I know.

def get_current_test():
    full_name = os.environ.get('PYTEST_CURRENT_TEST').split(' ')[0]
    test_file = full_name.split("::")[0].split('/')[-1].split('.py')[0]
    test_name = full_name.split("::")[1]

    return full_name, test_file, test_name
1

You might have multiple tests, in which case...

test_names = [n for n in dir(self) if n.startswith('test_')]

...will give you all the functions and instance variables that begin with "test_" in self. As long as you don't have any variables named "test_something" this will work.

You can also define a method setup_method(self, method) instead of setup(self) and that will be called before each test method invocation. Using this, you're simply given each method as a parameter. See: http://pytest.org/latest/xunit_setup.html

5
  • All methods representing py.test tests start with test. What I need here is py.test API, because py.test has collected all the tests beforehand (basically the way you suggested here) and already knows which test is to be run now. I just don't know the right question to ask py.test :-) Jul 18, 2013 at 15:08
  • Comment after your edit: I don't want to simply have a list of all the methods starting with "test_". From this list, I am after the one name / the method of the test being executed right now. And this only the py.test internals can tell. Jul 18, 2013 at 15:13
  • I think you want setup_method instead of just setup
    – ejk314
    Jul 18, 2013 at 15:17
  • I want setup, because this is what py.test calls for initializing each test. Jul 18, 2013 at 15:33
  • Thanks, that was definitely the right pointer. I was using py.test with setup and teardown for a long time now without realizing that those methods are more or less supported only for legacy reasons (this is right, isn't it?). In order to answer the question with a code example, I have submitted my own answer. I hope this is fine with you. Jul 19, 2013 at 10:52
1

You could give the inspect module are try.

import inspect

def foo():
    print "My name is: ", inspect.stack()[0][3]


foo()

Output: My name is: foo

1
  • 1
    Called from within the setup method this obviously returns setup. Jul 18, 2013 at 15:32
-1

Try type(self).__name__ perhaps?

1
  • 1
    In my example, this would only provide TestSomething. I'm mainly after the second part of the name :) Jul 18, 2013 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.