trouble with unittest and namespaces - can anyone help?

Peter Hansen peter at engcorp.com
Wed Nov 12 10:14:00 EST 2003


Lol McBride wrote:
> 
> On Tue, 11 Nov 2003 18:55:16 -0500, Peter Hansen wrote:
> << snip snip >>
> > Given that your tests are in a subfolder of the one where prog2.py
> > is found, I'm not sure how you are invoking the tests right now
> > such that they are working at all.  How do they find "prog2"
> > when they import it right now?
> >
> > -Peter
> Yes Peter you're right I did mean sys.path.
> I use some code from a tutorial in Linux Format magazine to get the test
> in the subfolder to work as below:
> import unittest
> # Import from this modules parent directory
> import os
> import sys
> sys.path.insert(0,os.pardir)
> import BallLoop
> del sys.path[0]
> del sys
> del os
> 
> Could you expand a little on your answer - perhaps using the structure I
> used as an example?I tend to need a bit of hand-holding till I understand
> the gist of what I'm shown.

Okay, I understand better now.  (Note that in the above example, you 
could probably dispense with all the "del" stuff as it adds very little
of use.)

Here's our approach to achieving the same ultimate goal of allowing
files from other directories to be imported during unit testing.  If
you look at the standard site.py module, you'll see stuff in there
about ".pth" files.  Building on that support, we have the following
in our test framework, although for only a few files you could just
insert it into each test file:

  import site
  site.addsitedir('.')

This has the effect of adding the current directory to the sys.path,
as well as searching for all .pth files in the current directory and
adding their contents to the sys.path as well, according to the notes
in site.py.  At this point, you just create a little, say, "test.pth"
file and put in it the paths to the other directories which you need
to make available for importing.  I believe relative paths will work
fine, or you could use absolute paths although that's nearly always
a worse approach.

Let me know if you need more background to understand what's happening,
though I recommend perusing site.py first.

-Peter




More information about the Python-list mailing list