I have a python application which contains unittest as well. Below is my file structure
├── src
│ ├── common
│ │ ├──constants.py
│ │ └──configs.py
│ ├── utils
│ │ ├──module1.py
│ │ └──module2.py
│ └── service
│ │ ├──module3.py
│ │ └──module4.py
│ └── main.py
├── test
│ ├── utils
│ │ ├──test_module1.py
│ │ └──test_module2.py
utils/module1.py contain
# module1.py
from common.constants import LOG_FORMAT, TIME_FORMAT
...
test_module1.py contain
# test_module1.py
import sys
sys.path.append(".")
from src.utils.module1 import filter_file
from unittest import TestCase, main, mock
and when i run below code from root below exception occurs.
$- python3 test/utils/test_module1.py
$- ModuleNotFoundError: No module named 'common'
I am using a linux machine. It will work when i try to add a "src." before every module import inside module1.py. But i don't want to change the code inside src because i have dockerized it. Please suggest your idea.
1 Answer 1
You are appending the directory containing test and src to sys.path, then accessing topleveldir/src/utils/module1.py with src.utils.module1. That module tries to import the file topleveldir/common/constants.py, but the file is actually located at topleveldir/src/common/constants.py - this must give a ModuleNotFound error. Change sys.path.append(".") to sys.path.append("./src") and remove the src. from the import below that, and it should work fine.
sys.path.append("./src")after thesys.path.appendyou already have ?