Mark Rowlands
Mark Rowlands

Reputation: 5453

Python unittest, skip tests when using a base-test-class

Whilst testing one of our web-apps for clarity I have created a BaseTestClass which inherits unittest.TestCase. The BaseTestClass includes my setUp() and tearDown() methods, which each of my <Page>Test classes then inherit from.

Due to different devices under test having similar pages with some differences I wanted to use the @unittest.skipIf() decorator but its proving difficult. Instead of 'inheriting' the decorator from BaseTestClass, if I try to use that decorator Eclipse tries to auto-import unittest.TestCase into <Page>Test, which doesn't seem right to me.

Is there a way to use the skip decorators when using a Base?

class BaseTestClass(unittest.TestCase):

    def setUp():
        #do setup stuff
        device = "Type that blocks"

    def tearDown():
        #clean up

One of the test classes in a separate module:

class ConfigPageTest(BaseTestClass):

    def test_one(self):
        #do test

    def test_two(self):
        #do test

    @unittest.skipIf(condition, reason) <<<What I want to include
    def test_three(self):
        #do test IF not of the device type that blocks

Upvotes: 7

Views: 3762

Answers (1)

Andrew Walker
Andrew Walker

Reputation: 42440

Obviously this requires unittest2 (or Python 3, I assume), but other than that, your example was pretty close. Make sure the name of your real test code gets discovered by your unit test discovery mechanism (test_*.py for nose).

#base.py
import sys
import unittest2 as unittest

class BaseTestClass(unittest.TestCase):

    def setUp(self):
        device = "Type that blocks"
    def tearDown(self):
        pass

And in the actual code:

# test_configpage.py
from base import *

class ConfigPageTest(BaseTestClass):

    def test_one(self):
        pass

    def test_two(self):
        pass

    @unittest.skipIf(True, 'msg')
    def test_three(self):
        pass

Which gives the output

.S.
----------------------------------------------------------------------
Ran 3 tests in 0.016s

OK (SKIP=1)

Upvotes: 3

Related Questions