Pytest Django Importing apps issues

305 views Asked by At

I have a question regarding pytest and django 3.1. I have an app structure like that:

main_app
├── config
│   └── settings
│       └── base.py / local.py / prod.py
├── main_app
│   ├── sub_apps
│   │   └── models.py tests.py apps.py views.py etc...
│   ├── templates
│   │   ├── account
│   │   ├── sub_apps
│   │   ├── pages
│   │   ├── userpreferences
│   │   └── users
│   ├── userpreferences
│   │   └── models.py tests.py apps.py views.py etc...
│   ├── users
│   │   └── tests --> test_models.py test_views.py test_forms.py etc...
│   └── utils
└── requirements

Following the structure of pydanny/cookiecutter.

With this cookiecutter, the preferred test method is via pytest. But pytest is giving me a bunch of headaches:

In my settings, INSTALLED_APPS I register sub_apps within the

LOCAL_APPS =["sub_app_1", "sub_app_2", ...]

When I start django, everything is fine. But if I want to run tests, pytest is complaining heavily, it can't import the sub_app modules.

I suspect mixed up relative and absolute import paths but am not seeing how to solve this atm. As a background: I use a separate userpreferences model which is imported in the settings via LOCAL_APPS = ["main_app.userpreferences.apps.UserpreferencesConfig"] In the apps.py I have to define the app name as name = "main_app.userpreferences"

Otherwise I get an Runtime error stating the Model class does'nt declare an explicit app_label / is not installed in INSTALLED_APPS.

While django runs just fine with these imports, pytest exits before running tests with: ModuleNotFoundError: No module named "sub_app_1"

I tried to change every import of modules in the sub_apps to e.g.: from .sub_app_1 import models --> from main_app.sub_app_1 import models but then django won't run anymore while the tests seem to run (pytest is starting and telling me 5/7 tests passed, while also occasionally printing import errors)

How do I resolve this?

0

There are 0 answers