如何 运行 测试在 Python 中标记为 `@unittest.skip` 的用例?

How to run test case marked `@unittest.skip` in Python?

假设以下测试套件:

# test_module.py
import unittest

class Tests(unittest.TestCase):

  @unittest.skip
  def test_1(self):
    print("This should run only if explicitly asked to but not by default")

  # assume many other test cases and methods with or without the skip marker

当通过 python -m unittest 调用 unittest 库时,有没有我可以实际传递给它的参数 运行 而不是跳过 Tests.test_1 而不修改测试代码和 运行是否还有其他跳过的测试?

python -m unittest test_module.Tests.test_1 正确选择了此作为 运行 的唯一测试,但它仍然跳过它。

如果不修改测试代码就无法做到这一点,我可以做的最惯用的更改是有条件地撤消 @unittest.skip 和 运行 一个特定的测试用例测试用例?

在所有情况下,我仍然希望python -m unittest discover(或任何其他未明确打开测试的调用)跳过测试。

如果您想跳过一些昂贵的测试,您可以使用 conditional skip together with a custom environment variable:

@skipIf(int(os.getenv('TEST_LEVEL', 0)) < 1)
def expensive_test(self):
    ...

那么你可以通过指定相应的环境变量来包含这个测试:

TEST_LEVEL=1 python -m unittest discover
TEST_LEVEL=1 python -m unittest test_module.Tests.test_1

如果你想跳过一个测试,因为你预计它会失败,你可以使用专用的 expectedFailure 装饰器。

顺便说一下,pytest 有一个专门用于 marking slow tests 的装饰器。