首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在运行时跳过整个Python 'unittest‘模块?

如何在运行时跳过整个Python 'unittest‘模块?
EN

Stack Overflow用户
提问于 2012-09-19 09:54:12
回答 10查看 25.4K关注 0票数 31

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

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

EN

回答 10

Stack Overflow用户

发布于 2014-05-08 16:42:33

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

Stack Overflow用户

发布于 2012-09-20 18:12:55

在看了这里的其他答案后,这是我想出的最好的答案。它很丑陋,在异常处理中嵌入了整个测试套件,但它似乎做了您想做的事情。特别是当导入不起作用时跳过测试。

假设您正在讨论使用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()

如果导入失败,它将用简单跳过的单个测试替换测试运行。我还试图确保它不会无意中吞噬任何异常。这个解决方案在很大程度上归功于对这个问题的所有其他答案和评论。

如果您在详细模式下运行它,当它跳过时,您将看到以下内容,

test_fail (test_openihm_gui_interface_mixins.TestMissingDependency) ... skipped 'Missing dependency - No module named PyQt4'
票数 9
EN

Stack Overflow用户

发布于 2019-10-05 19:14:10

@unittest.skip('comments_for_skipping_unit_tests')
class MyTests(unittest.TestCase):
def setUp(self):
    pass

def test_something(self):

您可以使用@unittest.skip装饰器跳过整个单元测试类。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12487532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档