palotasb
palotasb

Reputation: 4648

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

Assuming the following test suite:

# 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

When invoking the unittest library via python -m unittest are there any arguments I can pass to it actually run and not skip Tests.test_1 without modifying the test code and running any other skipped tests?

python -m unittest test_module.Tests.test_1 correctly selects this as the only test to run, but it still skips it.

If there is no way to do it without modifying the test code, what is the most idiomatic change I can make to conditionally undo the @unittest.skip and run one specific test case test case?

In all cases, I still want python -m unittest discover (or any other invocation that doesn't explicitly turn on the test) to skip the test.

Upvotes: 6

Views: 3230

Answers (1)

a_guest
a_guest

Reputation: 36239

If you want to skip some expensive tests you can use a conditional skip together with a custom environment variable:

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

Then you can include this test by specifying the corresponding environment variable:

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

If you want to skip a test because you expect it to fail, you can use the dedicated expectedFailure decorator.

By the way, pytest has a dedicated decorator for marking slow tests.

Upvotes: 5

Related Questions