I do a unit test with pytest in "cmd" and it work fine, but whem I am try to import my main file I get an import error. Here my file tree structure:
MATCHING_CC/
- pytest.ini
- __init__.py (empty file)
- conftest.py (empty file)
- src/
- __init__.py (empty file)
- conftest.py (empty file)
- matching_ingr_zing.py
- services/
- __init__.py (empty file)
- ElasticSearch.py
- ingredient_extractor_for_search.py
- metrics.py
- stop_word_matching.py
- models/ (folder to save trained models)
- tests/
- __init__.py (empty file)
- test_services/
- __init__.py (empty file)
- test_elastic_search.py
- test_ingredient_extractor_for_search.py
- test_metrics.py
- test_src/
- __init__.py (empty file)
- test_matching_ingr_zingr.py
Here an image of the problem: error
If someone can help me and explain whats is my error I will be greatful.
CodePudding user response:
It seems your program does not know where to locate src
. This might solve the issue.
import sys
# adding src to the system path
sys.path.insert(0, '/home/USERNAME/PATH/TO/src')
from src import something
Here is an explanation:
ModuleNotFoundError, because by default python interpreter will check for the file in the current directory only, and we need to set the file path manually to import the modules from another directory. We can do this using various ways. These ways are discussed below in detail.
Using sys module
We can use sys.path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that python can also look for the module in that directory if it doesn’t found the module in its current directory. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path.
For further reading: https://www.geeksforgeeks.org/python-import-module-from-different-directory/
CodePudding user response:
You need to run test from your parent directory MATCHING_CC_TEST
not from src
:
CodePudding user response:
Since matching_ingr_zing.py is inside 'src' directory already, you don't need to add 'src' at the beginning of file import anymore.
Simply do:
from services.ingredient_extractor_for_search.py import ... as ...