doctest, unittest, or if __name__='__main__'

Tim Peters tim.peters at gmail.com
Tue Mar 21 22:47:13 CET 2006


[john_sips_tea at yahoo.com <john_sips_tea at yahoo.com>[
> For writing testcode, it looks like there's three ways that it's
> typically done:
>
> (1). using the doctest module,
>
> (2). using the unittest module (i.e. "pyunit"), or else
>
> (3). just putting an "if __name__ = '__main__':" at the bottom of your
> module containing code to manually run your class through its paces.
>
> So, which way is preferred?

Serious testers often use both #1 and #2, depending on the specific
test at hand.  #3 doesn't work well in practice.

> Seems to me that unittest is the way to go, at least because it has
> you separate your test code from the code being tested.

Equally true of #1, if you write doctest files separate from your
code.  I suggest you look at Zope3, which is a major project using
that style extensively.  In fact, it's standard practice there to
write "tutorial doctest" files for a new feature before writing code
to implement it.  The text serves as a tutorial introduction to the
feature, and the tests scattered throughout clarify, illustrate, and
verify the text's claims.  By writing the text in ReST format, these
doctest files also serve as the source for auto-generated
documentation in HTML format (available interactively from a Zope3
console).  This combination of virtues has proved extremely
productive.

BTW, doctest makes it a little easier to write prose than to write
Python code, and your typical frazzled programmer is highly influenced
by small biases ;-)  The reverse is true of raw unittest, which goes a
long way toward explaining why you see so many unittests in real life
that are incomprehensible:  when it's easier to write code than
explanations, that's what people do.

> If unittest is the standard way to write test code, why do we still
> have doctest?

Because doctest is much better for some kinds of testing.  See above.

> (I notice there's no mention in PEP 3000 of deprecating
> the doctest module).

Or of deprecating the unittest module ;-)



More information about the Python-list mailing list