Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created February 23, 2015 22:45
Show Gist options
  • Save twolfson/13f5f5784f67fd49b245 to your computer and use it in GitHub Desktop.
Save twolfson/13f5f5784f67fd49b245 to your computer and use it in GitHub Desktop.
Python unittest `setUp` inheritance

In some cases for Python unit tests, we want to automatically perform setUp methods in as declared in a base class. However, we still want setUp to work as per normal in the subclass. The following code will proxy the new setUp function to run it's base class' and the new one.

# Define a common test base for starting servers
class MyBaseTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        """On inherited classes, run our `setUp` method"""
        # Inspired via http://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class/17696807#17696807
        if cls is not MyBaseTestCase and cls.setUp is not MyBaseTestCase.setUp:
            orig_setUp = cls.setUp
            def setUpOverride(self, *args, **kwargs):
                MyBaseTestCase.setUp(self)
                return orig_setUp(self, *args, **kwargs)
            cls.setUp = setUpOverride

    def setUp(self):
        """Do some custom setup"""
        self.abc = True


class ItemCreateTest(MyBaseTestCase):
    def setUp(self):
        """Do more custom setup"""
        self.def = True

    def test_verify_both_setups_run(self):
        """Test for our current usage"""
        self.assertEqual(self.abc, True)
        self.assertEqual(self.def, True)
    
@felixslager
Copy link

You could simply call a super(superclass, self).setUp(), on the other hand if you want to dispense with that, nice to see this works

@emcartwright
Copy link

emcartwright commented Jun 12, 2018

But if you have multiple child classes that someone else wrote and you want to add functionality in the setup and teardown, then the given code is much better than using super.

@abdul-hamid-achik
Copy link

thanks man, very cool

@josephsmartinez
Copy link

Thanks for adding this! Also the call out for super() makes sense too. I still like this implementation.

@blohinn
Copy link

blohinn commented Oct 13, 2021

thanks man!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment