Skip to main content
 首页 » 编程设计

Python 单元测试 : In Nose is there a way to skip a test case from nose. run()

2024年10月25日9shangdawei

我正在编写一组测试用例,比如测试模块中的 Test1、Test2。

有没有办法使用命令 nose.main() 在该模块中跳过 Test1 或选择性地仅执行 Test2?

我的模块包含,

测试模块.py,

class Test1: 
    setUp(self): 
       print('setup') 
    tearDown(self): 
       print('teardown') 
    test(self): 
       print('test1') 
 
class Test2: 
    setUp(self): 
       print('setup') 
    tearDown(self): 
       print('teardown') 
    test(self): 
       print('test2') 

我使用不同的 python 文件运行它,

if __name__ == '__main__': 
    nose.main('test_module') 

请您参考如下方法:

跳过测试和不运行测试的概念在 nose 上下文中是不同的:跳过的测试将在测试结果结束时报告为跳过。如果你想跳过测试,你将不得不用装饰器猴子修补你的测试模块或做一些其他的黑魔法。

但是如果你不想运行测试,你可以像在命令行中那样做:使用--exclude 选项。它采用您不想运行的测试的正则表达式。像这样:

import sys 
import nose 
 
def test_number_one(): 
    pass 
 
def test_number_two(): 
    pass 
 
if __name__ == '__main__': 
    module_name = sys.modules[__name__].__file__ 
 
    nose.main(argv=[sys.argv[0], 
                    module_name, 
                    '--exclude=two', 
                    '-v' 
                    ]) 

运行测试会给你:

$ python stackoverflow.py 
stackoverflow.test_number_one ... ok 
 
---------------------------------------------------------------------- 
Ran 1 test in 0.002s 
 
OK