Doctests

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:

pyherc.data.model.Character
add_to_tick Ok 0.093

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s