0

I have the following directory structure:

src/
    main/
        somecode/
            A.py
            B.py
            __init__.py
        __init__.py
    test/
        somecode/
            testA.py
            testB.py
            __init__.py
        __init__.py
    __init__.py

I was able to successfully add the following to the test modules:

import sys
sys.path.insert(0, "absolute path to src")

which allowed me to run nosetests from the src folder. But the problem is when other people use my code, this doesn't work because their absolute path doesn't is different.

So then I tried:

import sys, os
sys.path.append(os.path.abspath('../../../main/somecode')
from main.somecode import A

which worked great from src/test/somecode, but I can't run nosetests from the src folder since the relative path doesn't work from there.

I also tried to do from ...main.somecode import A but it doesn't like that even though they are all python packages.

So what do I do? This seems like a potential answer but he doesn't explain where to add the code.

Community
  • 1
  • 1
postelrich
  • 3,274
  • 5
  • 38
  • 65

1 Answers1

1

Instead of using a relative path ("../../../main/somecode"), you can do the same but using the __file__ global variable:

tests_dir = os.path.dirname(__file__)
sys.path.append(os.path.join(tests_dir, "..", "..", "..", "main", "somecode"))

I would put that in the __init__.py file under "test/somecode", instead of adding it for each test module file.

mguijarr
  • 7,641
  • 6
  • 45
  • 72