Python 对所有测试执行一次设置和拆卸功能

Python 对所有测试执行一次设置和拆卸功能,python,nosetests,Python,Nosetests,如何对所有测试执行一次设置和拆卸功能 def common_setup(): #time consuming code pass def common_teardown(): #tidy up pass def test_1(): pass def test_2(): pass #desired behavior common_setup() test_1() test_2() common_teardown() 请注意,在将点替换为pa

如何对所有测试执行一次设置和拆卸功能

def common_setup():
    #time consuming code
    pass

def common_teardown():
    #tidy up
    pass

def test_1():
    pass

def test_2():
    pass

#desired behavior
common_setup()
test_1()
test_2()
common_teardown()
请注意,在将点替换为
pass
并添加行
import unittest
之后,存在一个答案不适用于python 2.7.9-1、python-unittest2 0.5.1-1和python nose 1.3.6-1的问题。
不幸的是,我的声誉太低,无法对此发表评论。

您可以使用模块级设置功能。根据:

测试模块提供模块级设置和拆卸;定义方法 设置,设置\u模块,用于设置、拆卸的设置或设置模块, 拆卸模块,或用于拆卸的拆卸模块

因此,更具体地说,对于您的案例:

def setup_module():
    print "common_setup"

def teardown_module():
    print "common_teardown"

def test_1():
    print "test_1"

def test_2():
    print "test_2"
运行测试将为您提供:

$ nosetests common_setup_test.py -s -v
common_setup
common_setup_test.test_1 ... test_1
ok
common_setup_test.test_2 ... test_2
ok
common_teardown

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

您选择哪个名称并不重要,因此
setup
setup\u模块
的工作原理相同,但是
setup\u模块
更清晰。

谢谢您的建议。对不起,我的描述不够清楚。对于所有测试,setup()和teardown()函数只应调用一次。我编辑了我的问题以澄清这个问题。更改了答案以反映评论。