2

I would like to write a Python test suite in a way that allows me to inherit from a single TestBaseClass and subclass it multiple times, everytime changing some small detail in its member variables.

Something like:

import unittest

class TestBaseClass(unittest.TestCase):

  def setUp(self):
    self.var1 = "exampleone"

class DetailedTestOne(TestBaseClass):
  def setUp(self):
    self.var2 = "exampletwo"

  def runTest(self):
    self.assertEqual(self.var1, "exampleone")
    self.assertEqual(self.var2, "exampletwo")

class DetailedTestOneA(DetailedTestOne):
  def setUp(self):
    self.var3 = "examplethree"

  def runTest(self):
    self.assertEqual(self.var1, "exampleone")
    self.assertEqual(self.var2, "exampletwo")
    self.assertEqual(self.var3, "examplethree")

... continue to subclass at wish ...

In this example, DetailedTestOne inherits from TestBaseClass and DetailedTestOneA inherits from DetailedTestOne.

With the code above, I get:

AttributeError: 'DetailedTestOne' object has no attribute 'var1'

for DetailedTestOne and:

AttributeError: 'DetailedTestOneA' object has no attribute 'var1'

for DetailedTestOneA

Of course, var1, var2, var3 could be some members of a same variable declared in first instance in the TestBaseClass.

Any ideas on how to achieve such behaviour?

1 Answer 1

3

You need to call the superclass implementation in your subclasses by doing, e.g., super(DetailedTestOne, self).setUp() from inside your DetailedTestOne.setUp method.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! I thought the test framework would nest setUp calls for me treating it as an __init__, but I was wrong.
@FrancisStraccia: Nothing special about __init__ in this regard. If your subclass overrides __init__ and you want the superclass __init__ to be called, you have to call it explicitly in the same way I showed here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.