0

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.

asked Jun 25, 2021 at 11:48
2
  • 1
    What happens if you add sys.path.append("./src") after the sys.path.append you already have ? Commented Jun 25, 2021 at 11:56
  • wow. that worked Commented Jun 25, 2021 at 12:08

1 Answer 1

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.

answered Jun 25, 2021 at 12:33
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.