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

女生的网名这么多〃 提交于 2019-11-29 09:06:34
danielfrg

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

def test_name1(request):
    testname = request.node.name
    assert testname == 'test_name1'

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

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]

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

Try type(self).__name__ perhaps?

Robert Caspary

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!