Jac*_*ing 23 python unit-testing
我想我的Python unittest模块告诉测试运行器在某些情况下跳过它的全部(例如无法导入模块或找到关键资源).
我可以使用@unittest.skipIf(...)跳过unittest.TestCase类,但是如何跳过整个模块?将跳过应用于每个类是不够的,因为如果模块无法导入,类定义本身可能会导致异常.
Mu *_*ind 18
如果你看的定义unittest.skipIf和unittest.skip,你可以看到,关键是做raise unittest.SkipTest(reason)执行测试时.如果您将它显示为一个跳过的测试而不是testrunner中的几个,那么您可以unittest.SkipTest在导入时自行提升:
import unittest
try:
# do thing
except SomeException:
raise unittest.SkipTest("Such-and-such failed. Skipping all tests in foo.py")
Run Code Online (Sandbox Code Playgroud)
运行时nosetests -v给出:
Failure: SkipTest (Such-and-such failed. Skipping all tests in foo.py) ... SKIP:
Such-and-such failed. Skipping all tests in foo.py
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK (SKIP=1)
Run Code Online (Sandbox Code Playgroud)
otu*_*tus 11
我发现在setUp中使用skipTest效果很好.如果需要导入模块,可以使用try块设置例如module_failed = True,如果设置了setUp,则调用skipTest.这会报告正确的测试跳过次数,只需要一个短的try块:
import unittest
try:
import my_module
module_failed = False
except ImportError:
module_failed = True
class MyTests(unittest.TestCase):
def setUp(self):
if module_failed:
self.skipTest('module not tested')
def test_something(self):
#...
Run Code Online (Sandbox Code Playgroud)
@unittest.skip('comments_for_skipping_unit_tests')
class MyTests(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
Run Code Online (Sandbox Code Playgroud)
您可以使用@unittest.skip装饰器跳过整个单元测试类。
看完这里的其他答案后,这是我提出的最佳答案.它很难看,将整个测试套件嵌入到异常处理中,但它看起来像你想要的那样.特别是当导入不起作用时跳过测试.
假设你正在谈论使用nosetests -x来运行测试,那么它应该继续进行跳过的测试,至少在我尝试它时会出现这种情况.
import unittest
try:
import PyQt4
# the rest of the imports
# actual tests go here.
class TestDataEntryMixin(unittest.TestCase):
def test_somefeature(self):
# ....
except ImportError, e:
if e.message.find('PyQt4') >= 0:
class TestMissingDependency(unittest.TestCase):
@unittest.skip('Missing dependency - ' + e.message)
def test_fail():
pass
else:
raise
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
如果导入失败,它将使用一个简单跳过的测试替换测试运行.我还试图确保它不会无意中吞下任何异常.这个解决方案很大程度上归功于该问题的所有其他答案和评论.
如果你以详细模式运行它,你会在它跳过时看到它,
test_fail (test_openihm_gui_interface_mixins.TestMissingDependency) ... skipped 'Missing dependency - No module named PyQt4'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17760 次 |
| 最近记录: |