Search code examples
pythondjangodjango-unittest

Passing extra argument to TestCase Setup


I am writing tests for my django app using TestCase, and would like to be able to pass arguments to a parent class's setUp method like so:

from django.test import TestCase

class ParentTestCase(TestCase):
    def setUp(self, my_param):
        super(ParentTestCase, self).setUp()
        self.my_param = my_param

    def test_something(self):
        print('hello world!')

class ChildTestCase(ParentTestCase):
    def setUp(self):
        super(ChildTestCase, self).setUp(my_param='foobar')

    def test_something(self):
        super(ChildTestCase, self).test_something()

However, I get the following error:

TypeError: setUp() takes exactly 2 arguments (1 given)

I know that this is because only self is still passed, and that I need to overwrite to class __init__ to get this to work. I am a newbie to Python and not sure how to implement this. Any help is appreciated!


Solution

  • The test runner will call your ParentTestCase.setup with only self as a parameter. Therefore you will add a default value for this case e.g.:

    class ParentTestCase(TestCase):
        def setUp(self, my_param=None):
            if my_param is None:
                # Do something different
            else:
                self.my_param = my_param
    

    Note: be careful not to use mutable values as defaults (see "Least Astonishment" and the Mutable Default Argument for more details).