How to organize test cases with PyUnit

Peter Hansen peter at engcorp.com
Sun Jul 7 15:39:08 EDT 2002


Roy Smith wrote:
> 
> I could put all the test-case code in the same .py file as the module.

I'd only consider this for a small stand-alone module.  Anything larger 
and I would expect to have maintainability problems (file growing too 
large, for example), as well as issues like you pointed out with
having to parse the test code every time the module is compiled.

> I could put the test cases for a module in another file in the same
> directory, or possibly put all the test cases for all my modules in a
> "test" subdirectory.  This answers the efficiency question above, but
> seems like it's begging to have the two files get out of sync.  

We put all of ours in a subdirectory called "unit", with files named
for the module under test but with "_unit" appended, as in somemodule.py
getting a somemodule_unit.py for its tests.

Depending on the project, we similarly use "_user" or "_accept" at
the end for tests involving acceptance tests rather than unit tests.
These are also in a separate directory (predictably named "user" or
"accept").

As for getting out of sync -- this is not a problem if you always
write the test code before the application code, and make sure your
tests always run 100% successfully (which tells you you're done coding).
If you leave tests until later, you'll definitely start encountering
synchronization problems unless you have a very disciplined process.

> Also, does the test case file import the module being tested?  Is there a
> common higher-level file that imports both?

No need for a third file, except perhaps as part of a sophisticated
framework.  Don't make life more complicated than it already is. :)

> BTW, I started out with the test cases in a "test" subdirectory, and ran
> into a slight uglyness.  My initial idea was to just have module-test.py
> do an "import ../module", until I discovered that gives you a syntax
> error.  I can get around it with:
> 
> import sys
> sys.path.insert (1, '..')
> import module

We modify PYTHONPATH to include ".." first and run from the folder 
containing the tests.  Then the "import module" is all we need.

By the way, you might encounter problems with "module-test.py" as
a file name at some point... you couldn't import it, for example.
Use underscores instead of hyphens...

-Peter



More information about the Python-list mailing list