1

I have a directory structure like the following:

project/
    README.md
    project/
        foobar/
            foo.py
        tests/
            test_foo.py

test_foo is just from foobar import foo and when I run py.test or just python3 tests/test_foo.py from the project subdirectory, I get a No module named foobar error. I tried the other answers here such as adding .. to sys.path, using relative imports, none work, except when running python3 test_foo.py inside tests with sys.path.append('..').

shamilpython
  • 479
  • 1
  • 5
  • 18

2 Answers2

0

First make a package from your project and install it.

If installed, you can simply use absolute links, started with your package name:

from project import foobar
from project.foobar import foo

Another way - use intra-package links (no modification to sys.path needed):

test_foo.py

from .. import foobar
grapes
  • 8,185
  • 1
  • 19
  • 31
0

foo.py

def test():
    print("test")

test_foo.py

import os
import sys

runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))

from foobar import foo

foo.test()

Output

test
Ali.Turkkan
  • 266
  • 2
  • 11
  • two issues, adding paths to `sys.path` is "generally not recommended" and it would be cumbersome to paste that into every test file. – shamilpython Dec 27 '18 at 12:24