I have a flask app, inside the app I import some functions from another python files live on the same directory,
inside app.py
from kafka_handler import KafkaReceiver, KafkaSender, logger
and I have tests folder inside it I have BaseCase.py
from src.app import app
but when try to run the test using python3 -m unittest discover tests
I got this error from kafka_handler import KafkaReceiver, KafkaSender, logger ModuleNotFoundError: No module named 'kafka_handler'
I have a docker image to run the application, what should I do to make the tests runs without breaking the application
FROM python:3.11
WORKDIR /app
RUN pip3 install --upgrade pip
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
ENV PYTHONPATH=/app
COPY src /app
EXPOSE 8000
CMD ["python", "app.py"]
and the project tree is as the following
project
src
__init__.py
pp.py
kafka_hander.py
tests
__init__.py
BaseCase.py
test_something.py
Try prefix your import with a dot, from .kafka_handler import KafkaReceiver, KafkaSender, logger
.
Find detailed information about relative imports in according section of this article:
https://realpython.com/absolute-vs-relative-python-imports/
Based on the information you provided, it seems that the BaseCase serves as __main__
file and imports app.py
. Therefore it needs to know the reference / path, where to find kafka_handler.py
.