1

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!

i_trope
  • 1,554
  • 2
  • 22
  • 42
  • Personally, I have been taught that using the same name for two different methods is usually bad practice. This is my first guess into the matter. Have you tried changing the names, to say: `P_set_up` and `C_set_up`? – T.Woody Sep 30 '14 at 02:35
  • I should have been more clear. I would like to still inherit from TestCase's setUp method and extend it. – i_trope Sep 30 '14 at 02:39

1 Answers1

1

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).

Community
  • 1
  • 1
djsutho
  • 5,174
  • 1
  • 23
  • 25