2

I have a package and a test package. According to advice from Where do the Python unit tests go?, the tests should be in a different directory. The project's directory tree is as follows:

project\
    kernel\
        __init__.py
        file1.py
        file2.py
    tests\
        __init__.py
        test1.py
        test2.py
        test3.py

I would like to import the kernel package to the tests package, because that is where file1.py and file2.py are being tested. Also, I would like to use one import statement in the __init__.py instead of importing kernel again and again in each test. I tried adding the following to the __init__.py file in tests and to test2.py , test2.py (together and separately), with no success (the first does no harm, the second gives a syntax error):

import kernel
import ../kernel

I'm using python2.6. From command line all the above happens. When I use Eclipse PyDev, everything magically works.

twink_ml
  • 512
  • 3
  • 14
Yair Daon
  • 1,043
  • 2
  • 15
  • 27

1 Answers1

3

The relative imports you're using will only work if the "project" directory is a python package (i.e. it has an __init__.py file in it). Try that first and see if that works for you.

If the kernel directory is acting as the "package" that would be distributed then you could put the tests directory inside of that and do the relative imports that way. So it would look like this:

project/
    kernel/
        __init__.py
        file1.py
        file2.py
        tests/
            __init__.py
            test1.py ...

And you would import the kernel modules from the tests directory either as:

from kernel import file1  # if it's installed in the python path/environment

Or:

from .. import file1
# 'import ..file1' might work, but I'm not sure that's syntactically correct
djhoese
  • 3,567
  • 1
  • 27
  • 45