0

Let's say I have classes (which are not TestCases) that all implement "some" methods. I now want to write a single testclass that validates that all objects actually do implement "some" methods like they should.

I am aware how to test the methods themselves, but what I would like to have is a list of those classes and the tests are then executed for every class. I can imagine it to be something like this:

import unittest
class ClassOne:
    def walk(param):
        return param
ClassTwo = ClassOne
class_list = [ClassOne, ClassTwo]

class TestClasses(unittest.TestCase):
    def test_walk():
        ob = object()
        for current_class in class_list:
            self.assertEqual(object, current_class.walk(object))

This solution has the disadvantage that you mix asserts that aren't really related. Is there a better way to test generically?

Natan
  • 728
  • 1
  • 7
  • 23
  • 1
    Are you looking for something like https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests? Alternatively you can also extend test classes using inheritance, so you'd have a subclass of `TestClasses` specifically for `ClassOne`. – jonrsharpe Apr 02 '22 at 15:13
  • subtest does help. I am unsure whether I like the idea of inheritance since that wouldn't be really generic. – Natan Apr 02 '22 at 15:17
  • How is that not generic? You write the test class that describes the behaviour of the contract, then have subclasses that create an instance of the specific implementation to apply them to. Given you only have one implementation this all seems academic anyway. – jonrsharpe Apr 02 '22 at 15:18
  • Example: https://stackoverflow.com/a/4566992/3001761. `Abstract` would represent the contract, then you'd have a `Test` for each implementation. – jonrsharpe Apr 02 '22 at 15:25
  • I noticed that my question wasn't clear. I updated the question so it is clear that I am not looking for generic TestClasses, but a single test class that tests generic Classes – Natan Apr 02 '22 at 18:45

0 Answers0