unit testing class hierarchies

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Oct 3 05:33:55 EDT 2012


On 3 October 2012 02:20, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>
> But surely, regardless of where that functionality is defined, you still
> need to test that both D1 and D2 exhibit the correct behaviour? Otherwise
> D2 (say) may break that functionality and your tests won't notice.
>
> Given a class hierarchy like this:
>
> class AbstractBaseClass:
>     spam = "spam"
>
> class D1(AbstractBaseClass): pass
> class D2(D1): pass
>
>
> I write tests like this:
>
> class TestD1CommonBehaviour(unittest.TestCase):
>     cls = D1
>     def testSpam(self):
>          self.assertTrue(self.cls.spam == "spam")
>     def testHam(self):
>          self.assertFalse(hasattr(self.cls, 'ham'))
>
> class TestD2CommonBehaviour(TestD1CommonBehaviour):
>     cls = D2

That's an excellent idea. I wanted a convenient way to run the same
tests on two classes in order to test both a pure python and a
cython-accelerator module implementation of the same class. I find it
difficult to work out how to do such simple things with unittest
because of its Java-like insistence on organising all tests into
classes. I can't immediately remember what solution I came up with but
yours is definitely better.


Oscar



More information about the Python-list mailing list