2

in unittest python library, exists the functions setUp and tearDown for set variables and other things pre and post tests.

how I can run or ignore a test with a condition in setUp ?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
JuanPablo
  • 23,792
  • 39
  • 118
  • 164
  • I suppose you could raise an exception in the `setUp` call; I expect that would cause the test not to be run. That's awfully dirty, though. Why do you actually want to do this? Wouldn't it be cleaner to decide what tests to run elsewhere? – Henry Keiter May 19 '14 at 15:06
  • 1
    Related: http://stackoverflow.com/questions/19031953/skip-unittest-test-without-decorator-syntax – guettli May 19 '14 at 15:06
  • @HenryKeiter I use a [directory structure of data test](http://stackoverflow.com/questions/21944384/same-tests-over-many-similar-data-files/22042689#22042689), if some files are found the test running – JuanPablo May 19 '14 at 15:11

2 Answers2

3

You can call if cond: self.skipTest('reason') in setUp().

otus
  • 5,572
  • 1
  • 34
  • 48
  • I implemented class inheritance for my unit tests to avoid code repetition, and since I have a mandatory field in my testcase implementations, I can check if this field is `None` as a condition to skip the tests. This avoided me hacky things like multiple inheritance or putting `del MyAbstractTestCase` at the end of my module – sox supports the mods Sep 06 '18 at 16:37
2

Instead of checking in setUp, use the skipIf decorator.

@unittest.skipIf(not os.path.exists("somefile.txt"),
                 "somefile.txt is missing")
def test_thing_requiring_somefile(self):
    ...

skipIf can also be used on the class, so you can skip all contained tests if the condition does not hold.

@unittest.skipIf(not os.path.exists("somefile.txt"),
                 "somefile.txt is missing")
class TestStuff(unittest.TestCase):

    def setUp(self):
        ...

    def test_scenario_one(self):
        ...

    def test_scenario_two(self):
        ...
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Note that skipIf being a decorator doesn't have access to the class members, so you cannot skip tests based on a class flag (e.g. you cannot do `@skipIf(self.work_in_progress is True)`). – sox supports the mods Sep 06 '18 at 16:41