Blog Archives

Python unittests and subclasses

While working on one of my projects, I discovered one of those things about a programming language/module that forms a smile on your face as you are coding.

I have been creating unittests for some code that is using a class from the standard Python library, which means that my unittests can only see the result of a process, not the state of the process while my code is running. This was becoming problematic because I needed to test the state of my code at a particular part in the overall process.

So I have a parser which is using sgmllib.SGMLParser as it’s superclass. So once, I pass data to the feed() method I can only see the state of my parser after it has parsed the data. I need to see the state of some internal representations of the data during the parsing, though, so this was becoming problematic. Debug messages, while helpful, are difficult to decipher when the number of messages goes beyond as human readable number.

So here’s where the joy came in. I remembered seeing a test (somewhere) that used a new subclass of the class that was being tested. This (happily) means that your class can test itself by overwriting some of the superclass’s methods. While I was happy to find a testable solution, the real joy came when I was worried about how my subclass was going to tell the unittest module that something failed.

Enough babble, here’s an “example” of testing a fake BlackBox class (one that I can’t see into):

class TestableClass(BlackBox):
    def blackbox_method(self):
        super(TestableClass, self).blackbox_method()
        assert self.internal == 1

Running my test which uses TestableClass yielded the failure I was after. But it also caused a failed test, rather than the exception that I expected. This makes perfect sense because the unittest module is just looking for an AssertionError to count as a failure and does not mind where that comes from.

And that’s it. You can suddenly run assert something and test the state at a given moment. In my case, I used it to test when a certain element in the HTML is closed or open. Works wonders!

Posted: December 22, 2008 @ 14:27
Tagged: code, python, tech, testing

Comments

No comments have been added