py.test:如何从设置方法中获取当前测试的名称? [英] py.test: how to get the current test's name from the setup method?
问题描述
我正在使用 py.test 并想知道是否/如何在运行每个测试之前调用的 setup
方法中检索当前执行的测试的名称.考虑以下代码:
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
就在 TestSomething.test_the_power
执行之前,我想在 setup
中访问此名称,如代码中所述,通过 test_name = ...
这样 test_name
== "TestSomething.test_the_power"
.
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"
.
实际上,在setup
中,我为每个测试分配了一些资源.最后,查看各种单元测试创建的资源,我希望能够看到哪个测试创建了哪个.最好的办法是在创建资源时使用测试名称.
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.
推荐答案
您也可以使用 Request Fixture 像这样:
You can also do this using the Request Fixture like this:
def test_name1(request):
testname = request.node.name
assert testname == 'test_name1'
这篇关于py.test:如何从设置方法中获取当前测试的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!