如何在运行时跳过整个 Python 'unittest' 模块? [英] How do I skip a whole Python 'unittest' module at run time?

查看:23
本文介绍了如何在运行时跳过整个 Python 'unittest' 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like my Python unittest module to tell the test runner to skip it entirety under some situations (such as being unable to import a module or locate a critical resource).

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

I can use @unittest.skipIf(...) to skip a unittest.TestCase class, but how do I skip the entire module? Applying skips to every class is not sufficient because the class definitions themselves could cause exceptions if a module fails to import.

推荐答案

如果你看一下unittest.skipIfunittest.skip 的定义,你可以看到关键是在执行测试时做 raise unittest.SkipTest(reason) .如果您可以将它显示为 one 跳过的测试而不是测试运行程序中的几个,您可以简单地在导入时自己提高 unittest.SkipTest :

If you look at the definition of unittest.skipIf and unittest.skip, you can see that the key is doing raise unittest.SkipTest(reason) when the test is executed. If you're okay with having it show up as one skipped test instead of several in the testrunner, you can simply raise unittest.SkipTest yourself on import:

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)

这篇关于如何在运行时跳过整个 Python 'unittest' 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆