[py-dev] Test directories for py.test

Maciek Fijalkowski fijal at genesilico.pl
Fri Feb 23 15:20:03 CET 2007


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).
>
>   
Also note that you usually need to use absolute imports than (as in 
example above) as well as you cannot have __init__.py in the same 
directory where foo is located.



More information about the Pytest-dev mailing list