Skip to main content
 首页 » 编程设计

python之py.test 将 IndexError/KeyError 报告为失败而不是错误

2024年10月17日11bluestorm

 import unittest 
 import logging 
 
 FORMAT = '%(asctime)-15s %(message)s' 
 logging.basicConfig(format=FORMAT) 
 
 
 log = logging.getLogger(__name__) 
 log.root.setLevel(logging.DEBUG) 
 
 class FixturesTest(unittest.TestCase): 
 
     def setUp(self): 
         log.info('starting setup') 
         self.fixture = range(1, 10) 
         log.warn('Hello world') 
 
     def tearDown(self): 
         log.info('starting teardown') 
         del self.fixture 
         log.info('Goodbye world') 
 
     def test_pass(self): 
         log.info('in test pass') 
         self.assertEqual(self.fixture, range(1, 10)) 
         log.error('Test world') 
 
     def test_fail(self): 
         log.info('in test fail') 
         log.error("let's fail a test") 
         assert(1==0) 
 
     def test_error(self): 
         log.info('in test error') 
         log.info("let's error a test") 
         d = [] 
         d[1] 
 
     if __name__ == '__main__': 
         unittest.main() 

使用 py.test 运行上面的代码,它将 test_error 测试方法报告为测试失败而不是测试错误。而使用 unittest 运行它会将 test_error 显示为错误而不是失败,您能分享一下对此的任何想法吗?

更新:相同的代码,nose 也将其视为错误而不是 test_error 的失败,这是 py.test 中的问题吗?

更新:如果你不确定我指的是什么,如果你运行 py.test test_filename.py,你会得到 1 次通过,2 次失败,如果你运行 python -m unittest test_filename.py 或 nosetest test_filename.py,这是 1 次通过,1 次失败,1 次错误。

请您参考如下方法:

pytest 不区分测试失败(由于AssertionError)和测试错误(任何其他异常),如 unittest 确实如此。这不是错误,而是设计使然。

this thread 中有一些讨论添加对这种类型的分离的支持,结果是 pytest-finer-verdicts插入。