t.perk
t.perk

Reputation: 111

Inheriting setUp method Python Unittest

I have a question regarding unittest with Python! Let's say that I have a docker container set up that handles a specific api endpoint (let's say users, ex: my_site/users/etc/etc/etc). There are quite a few different layers that are broken up and handled for this container. Classes that handle the actual call and response, logic layer, data layer. I am wanting to write tests around the specific calls (just checking for status codes).

There are a lot of different classes that act as Handlers for the given endpoints. There are a few things that I would have to set up differently per one, however, each one inherits from Application and uses some methods from it. I am wanting to do a setUp class for my unittest so I don't have to re-establish this each time. Any advice will help. So far I've mainly seen that inheritance is a bad idea with testing, however, I am only wanting to use this for setUp. Here's an example:

class SetUpClass(unittest.TestCase):
    def setUp(self):
        self._some_data = data_set.FirstOne()
        self._another_data_set = data_set.SecondOne()
    def get_app(self):
        config = Config()
        return Application(config,
            first_one=self._some_data,
            second_one=self._another_data_set)


class TestFirstHandler(SetUpClass, unittest.TestCase):
    def setUp(self):
        new_var = something 
    def tearDown(self):
         pass
    def test_this_handler(self):
      # This specific handler needs the application to function
      # but I don't want to define it in this test class
      res = self.fetch('some_url/users')
      self.assertEqual(res.code, 200)


class TestSecondHandler(SetUpClass, unittest.TestCase):
    def setUp(self):
        different_var_thats_specific_to_this_handler = something_else
    def tearDown(self):
         pass
    def test_this_handler(self):
      # This specific handler needs the application to function
      # but I don't want to define it in this test class
      res = self.fetch('some_url/users/account/?something_custom={}'.format('WOW'))
      self.assertEqual(res.code, 200)

Thanks again!!

Upvotes: 1

Views: 3335

Answers (1)

Don Kirkby
Don Kirkby

Reputation: 56650

As mentioned in the comments, you just need to learn how to use super(). You also don't need to repeat TestCase in the list of base classes.

Here's the simple version for Python 3:

class TestFirstHandler(SetUpClass):
    def setUp(self):
        super().setUp()
        new_var = something
    def tearDown(self):  # Easier to not declare this if it's empty.
        super().tearDown()
    def test_this_handler(self):
      # This specific handler needs the application to function
      # but I don't want to define it in this test class
      res = self.fetch('some_url/users')
      self.assertEqual(res.code, 200)

Upvotes: 4

Related Questions