'pytest can't find module for tests
I have a structure like (not exact names)
- my_project
- app
- repo
- __init__.py
- my_repo.py
- services
- __init__.py
- my_service.py
- utils
- __init__.py
- __init__.py
- main.py
- __init__.py
- test_main.py
Previously I had a flat structure and my tests worked, now that I changed to this structure, every time I try to run pytest
, I get the following error:
portError while importing test module '/Users/user/IdeaProjects/my-project/test_main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/local/Cellar/[email protected]/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
test_main.py:3: in <module>
from app.main import app
app/main.py:3: in <module>
from repository.image_repository import ImageRepository
E ModuleNotFoundError: No module named 'repository'
bear in mind that I can run this project normally without any problems, the problems happen when I try to run the tests.
The import section of my test_main.py
file is:
from unittest.mock import patch
from fastapi.testclient import TestClient
from app.main import app
from app.services.image_storage import ImageStorage
from app.repository.image_repository import ImageRepository
and the import section of my main.py
file is:
import uvicorn
from fastapi import FastAPI, UploadFile, HTTPException
from repository.image_repository import ImageRepository
from services.image_storage import ImageStorage
from utils import generate_filename, is_image
app = FastAPI()
image_repository = ImageRepository()
image_storage = ImageStorage()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|