如何在运行时跳过整个 Python“unittest”模块?

新手上路,请多包涵

我希望我的 Python unittest 模块告诉测试运行器在某些情况下完全跳过它(例如无法导入模块或定位关键资源)。

我可以使用 @unittest.skipIf(...) 跳过 unittest.TestCase 类,但如何跳过 整个模块?将跳过应用到每个类是不够的,因为如果模块导入失败,类定义本身可能会导致异常。

原文由 Jace Browning 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 361
2 个回答

如果您查看 unittest.skipIfunittest.skip 的定义,您可以看到关键在执行 raise unittest.SkipTest(reason) 执行测试。如果您同意在测试运行器中将其显示为 一个 跳过的测试而不是多个测试,您可以简单地在导入时自己提高 unittest.SkipTest 自己:

 import unittest
try:
    # do thing
except SomeException:
    raise unittest.SkipTest("Such-and-such failed. Skipping all tests in foo.py")

运行 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)

原文由 Mu Mind 发布,翻译遵循 CC BY-SA 4.0 许可协议

我发现在 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):
            #...

原文由 otus 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题