Embedding unit tests in source files?

Jean-Paul Calderone exarkun at divmod.com
Sun Jun 17 17:31:43 CEST 2007

On Sun, 17 Jun 2007 08:15:46 -0700, Roy Smith <roy at panix.com> wrote:
>I'm starting a new project and am thinking of embedding my unit tests
>right in the source files.  I've used unittest before, and I'm happy
>with it, but I've always used it with the source code in one file and
>the unit tests in another.  I figure if I just put a
>if __name__ == '__main__":
>    import unittest
>    blah, blah, blah
>block at the end of each source file, I'll end up with a cleaner
>project structure.  I can run the unit tests just by executing each
>source file.  Any comments from people who have organized their Python
>projects this way?  Did it work out well?
>It seems like what you give up is the ability to aggregate tests in a
>hierarchy of test suites.  In theory, that sounds like something you
>might want to do, but in practice, I've never found it that useful, so
>I don't think I'll miss it.
>I know about doctest, but I'm happy with unittest and don't see any
>reason to change.

If you do this, then all of your code will be defined one way for the
test suite (in a module named __main__ - and defined twice if it happens
to import anything else which tries to import it) and another way when
it's actually being used in an application.  This will probably have
various "interesting" consequences which you'd be better off avoiding.

You might be able to find a way to avoid this import behavior if you get
a little creative, but I doubt it's worth the effort or the trickery.


More information about the Python-list mailing list