0

Using Python 3.8, I made a functional project using FastAPI. With the structure I outline below, I placed all the elements of my project in an "app" folder so I could create a Docker image.


├── app/
|     └── sdk/
|          └── __init__.py
|          └── sdk.py
|          └── schemas.py
|          └── exceptions.py
|     └── api/
|          └── __init__.py
|          └── services.py
|     └── tests/
|          └── __init__.py
|          └── test_live_sdk.py
|     └── main.py
├── DockerFile
├── Pipfile

After debugging and renaming imports, my project works correctly when I run the docker image, however, when I want to run the tests navigating from my console (Not from Docker), this is, inside the app folder, and then running pytest tests/test_live_sdk.py, as I did before, I get the following error:

Traceback:
/usr/lib/python3.8/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
app/tests/__init__.py:1: in <module>
    from app import sdk
app/sdk/__init__.py:2: in <module>
    from . import sdk
app/sdm/sdk.py:1: in <module>
    from sdk import schemas, exceptions, constants
E   ModuleNotFoundError: No module named 'sdk'

Previously, in order to import those directories from another package, what I did was to import them inside the __init__.py, in the following ways:

# sdk/__init__.py
import sdk
# api/__init__.py
from . import *

Afterwards, I assumed that my package already recognized this import. This seemed to work before modifying the parent directory, but no longer. I tried to add app., but this also doesn't work either.

Is it possible to run the tests independently of docker? That is, navigating directly to the app folder and then run pytest <test.py>, or this can only be executed once Docker already recognizes which is the working directory?

In other words, how can I access the modules that pytest fails to recognize?

I recognize that python imports are one of the subjects that confuse me the most, so I greatly appreciate any guidance. I'm sure the problem is here.

J. Santiago
  • 99
  • 1
  • 11

1 Answers1

0

Plase provide the contents of your Dockerfile and the Pipfile.

Usually the standard for writing Dockerfiles for Python is that, you have a

requirements.txt

For your case it could be something like :

cat requirements.txt 
uvicorn[standard]==0.18.3
fastapi==0.45.0
urllib3==1.22
cx_freeze==6.0b1
pytest==3.2.2
pytest-cov==2.5.1
pytest-dependency==0.2

And then the Dockerfile :

FROM python:3.9

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY requirements.txt /usr/src/app

RUN pip install --no-cache-dir -r requirements.txt

COPY . /usr/src/app

CMD["pytest", "tests/test_live_sdk.py"]

Or something like that... I will edit with more appropriate configurations once you provide Dockerfile and Pipfile.

jcroyoaun
  • 312
  • 3
  • 6