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

前端 未结 7 2156
心在旅途
心在旅途 2020-12-17 07:49

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 e

7条回答
  •  春和景丽
    2020-12-17 08:40

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

提交回复
热议问题