简体   繁体   English

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

[英]Setup and teardown functions executed once for all nosetests tests

How to execute setup and teardown functions once for all nosetests tests? 如何对所有测试测试执行一次设置和拆卸功能?

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()

Note that there exists a similar question with an answer that is not working with python 2.7.9-1, python-unittest2 0.5.1-1 and python-nose 1.3.6-1 after replacing the dots with pass and adding the line import unittest . 请注意,在使用pass替换点并添加行import unittest后,存在一个类似的问题 ,答案是不能使用python 2.7.9-1,python-unittest2 0.5.1-1和python-nose 1.3.6-1 import unittest Unfortunately my reputation is too low to comment on that. 不幸的是,我的名声太低,无法评论。

You can have a module level setup function. 您可以拥有模块级别设置功能。 According to nose documentation : 根据鼻子文件

Test modules offer module-level setup and teardown; 测试模块提供模块级设置和拆卸; define the method setup, setup_module , setUp or setUpModule for setup, teardown, teardown_module , or tearDownModule for teardown. 为setup,teardown, teardown_module或tearDownModule定义方法设置, setup_module ,setUp或setUpModule以进行拆卸。

So, more specifically, for your case: 所以,更具体地说,对于你的情况:

def setup_module():
    print "common_setup"

def teardown_module():
    print "common_teardown"

def test_1():
    print "test_1"

def test_2():
    print "test_2"

Running test gives you: 运行测试为您提供:

$ 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

It does not matter which name you choose, so both setup and setup_module would work the same, but setup_module has more clarity to it. 您选择的名称无关紧要,因此setupsetup_module工作方式相同,但setup_module更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM