I have known about doctest for quite a while, but never got around to try them out. Today I wrote my first one:
def add_to_tick(self, cost): """ Add cost of action to characters tick, while taking characters speed into account For example: >> pc = Character(None, None, None) >> pc.tick = 5 >> pc.speed = 2 >> pc.add_to_tick(5) 15 Args: cost: Cost of action in ticks Returns: New ticks """ self.tick = self.tick + (self.speed * cost) return self.tick
After running it through nosetests –with-doctest –with-xunit and mangling the xml to html, I end up with:
Nothing really fancy and certainly nothing that I couldn’t achieve with normal unit tests. But the key to here is that I’m not testing the code, I’m testing the documentation (namely the code example). If I were to add a new parameter to the function and not update the example, the test would fail.
I’m most likely not going to use doctest very extensively, but maybe there are place or two to use it.