Carl Friedrich Bolz wrote:
> Hi Tom!
>
> Tom Harris wrote:
> > I like to have my tests in a subdirectory for a project, so directory
> > 'foo' would have a subdirectory 'test'. The tests in 'test' should be
> > able to load module foo.py in it's parent directory, with a
> > sys.path.insert(0, '..'). That's the way I did it with unittest anyway.
> > Example below fails unless I insert a '.' instead of '..' into sys.path.
> >
> > file 'foo/foo.py':
> > def a(): return 1
> >
> > file 'foo/test/test_foo.py':
> > import sys
> > sys.path.insert(0, '..')
> > import foo
> >
> > def test_1():
> > assert foo.a() == 1
> >
> > Now I'm quite happy to type import sys; sys.path.insert(0, '.') at the
> > head of all my test files, but am I missing something?
>
> Since this is quite a common problem, There is a built-in solution in
> py.test :-). The idea is the following: py.test inserts a certain path into
> sys.path. Which path that is, is determined by walking up the
> directories starting from the test dir until it finds a directory that
> does not have an __init__.py file. So what you could do:
>
> file 'foo/__init__.py':
> # empty or whatever
>
> file 'foo/bar.py':
> def a(): return 1
>
> file 'foo/test/__init__.py':
> # empty or whatever
>
> file 'foo/test/test_bar.py':
> from foo import bar
>
> def test_a():
> assert bar.a() == 1
>
>
> This allows you to have a deeper directory hierarchy and always the
> right directory is inserted (as long as you have __init__.py files
> everywhere but in the dir above your project).
Thanks for this. I didn't know any of that.
But it doesn't seem to work unless the import statements are written exactly
as above. For example, if you change the 3rd from last line to:
from bar import a
it says "FAILED TO LOAD MODULE". So the compromise, I guess, is to write it as
from foo.bar import a
A bit uglier and more typing but superior to the sys.path append/insert
business.
Thanks again,
Michael
_______________________________________________
py-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/py-dev