ImportError when separating test files from project files

36 Views Asked by At

I'm attempting to implement a Python project with a src layout structure. Essentially putting unit tests in a test directory and project files in a src directory.

I'm getting an import error:

Traceback (most recent call last):
  File "test_project\tests\test_mod1.py", line 1, in <module>
    from src import mod1 as m1
ImportError: cannot import name 'mod1' from 'src' (unknown location)

I'm looking to understand why I am getting this error and how to fix it.

I've included the code and file structure below. I know the code doesn't implement an actual unit test (planning to do that after getting this to work). Also, I would like to do this with out having to specify absolute paths. Online material seem to indicate this should work, but obviously I've made a mistake somewhere.

Here is the project structure:

test_project/
│
├── src/
│   └── __init__.py
│   └── mod1.py
└── tests/
    └── __init__.py
    └── test_mod1.py

The __init__.py files are empty.

mod1.py:

def add(x,y):
    return x + y

test_mod1.py:

from src import mod1 as m1

x,y = 3,4
print(m1.add(x,y))
0

There are 0 best solutions below