The docs 说:
如果您更愿意直接在模块级别定义测试函数,您还可以使用以下函数来实现 fixture:
def setup_function(function):
""" setup any state tied to the execution of the given function.
Invoked for every test function in the module.
"""
def teardown_function(function):
""" teardown any state that was previously setup with a setup_function
call.
"""
但实际上并不清楚您应该如何使用它们。
我尝试完全按照上面所示将它们放入我的测试文件中,但它们没有被调用。仔细观察它们,使用 function
arg,它们看起来像装饰器。所以我试图找到一种方法来做:
@pytest.setup_function
def my_setup():
# not called
虽然我找不到任何地方可以从中导入一个作为装饰器,所以这是不对的。
我找到了 this thread on grokbase有人解释你可以做什么:
@pytest.fixture(autouse=True)
def setup_function(request):
# this one gets called
它有效,但它似乎与文档不再相关...没有理由在这里将其称为 setup_function
。
最佳答案
您只需实现 setup_function()
的主体,为名称以 test_
开头的每个函数调用该函数,并将该函数作为参数传递:
def setup_function(fun):
print ("in setup function: " + fun.__name__)
def test_test():
assert False
当使用 py.test
运行时,这将给出输出:
============================= test session starts ==============================
platform linux2 -- Python 2.7.6 -- pytest-2.3.5
collected 1 items
test/test_test.py F
=================================== FAILURES ===================================
__________________________________ test_test ___________________________________
def test_test():
> assert False
E assert False
test/test_test.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
in setup function: test_test
=========================== 1 failed in 0.01 seconds ===========================
最后一行显示了实际调用 setup_function()
一个稍微有用的例子,实际做了一些影响测试功能的事情:
def setup_function(function):
function.answer = 17
def teardown_function(function):
del function.answer
def test_modlevel():
assert modlevel[0] == 42
assert test_modlevel.answer == 17
这取自 py.test
的 own tests ,总是一组很好的(希望是完整的)py.test
所有特性的例子。
关于python - 如何使用 xunit 风格的 setup_function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21463278/