0

I am implementing tests for my django application with pytest. I added the decorator @pytest.mark.django_db to my test_function so i could access my database (sqlite3). When i run a simple assert response.status_code an error occurs and tells me that there are no application installed with the label. I precise that my application appears in INSTALLED_APPS settings.

Complete error message:

(env) Inspiron-3793:~/Python-OC-Lettings-FR$ pytest lettings/
============================================================== test session starts ===============================================================
platform linux -- Python 3.9.7, pytest-7.1.1, pluggy-1.0.0 -- /home/arthur/openclass/P13/Python-OC-Lettings-FR/env/bin/python3
cachedir: .pytest_cache
django: settings: oc_lettings_site.settings (from ini)
rootdir: /home/arthur/openclass/P13/Python-OC-Lettings-FR, configfile: setup.cfg
plugins: django-3.9.0, mock-3.7.0
collected 1 item                                                                                                                                 

lettings/tests/unit/tests.py::TestLettings::test_index ERROR                                                                               [100%]

===================================================================== ERRORS =====================================================================
___________________________________________________ ERROR at setup of TestLettings.test_index ____________________________________________________

self = <django.db.migrations.state.StateApps object at 0x7f3fd35b0b50>, app_label = 'oc_lettings_site'

    def get_app_config(self, app_label):
        """
        Import applications and returns an app config for the given label.
    
        Raise LookupError if no application exists with this label.
        """
        self.check_apps_ready()
        try:
>           return self.app_configs[app_label]
E           KeyError: 'oc_lettings_site'

env/lib/python3.9/site-packages/django/apps/registry.py:155: KeyError

During handling of the above exception, another exception occurred:

request = <SubRequest '_django_db_marker' for <Function test_index>>

    @pytest.fixture(autouse=True)
    def _django_db_marker(request):
        """Implement the django_db marker, internal to pytest-django.
    
        This will dynamically request the ``db``, ``transactional_db`` or
        ``django_db_reset_sequences`` fixtures as required by the django_db marker.
        """
        marker = request.node.get_closest_marker("django_db")
        if marker:
            transaction, reset_sequences = validate_django_db(marker)
            if reset_sequences:
                request.getfixturevalue("django_db_reset_sequences")
            elif transaction:
                request.getfixturevalue("transactional_db")
            else:
>               request.getfixturevalue("db")

env/lib/python3.9/site-packages/pytest_django/plugin.py:513: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
env/lib/python3.9/site-packages/pytest_django/fixtures.py:105: in django_db_setup
    db_cfg = setup_databases(
env/lib/python3.9/site-packages/django/test/utils.py:169: in setup_databases
    connection.creation.create_test_db(
env/lib/python3.9/site-packages/django/db/backends/base/creation.py:67: in create_test_db
    call_command(
env/lib/python3.9/site-packages/django/core/management/__init__.py:168: in call_command
    return command.execute(*args, **defaults)
env/lib/python3.9/site-packages/django/core/management/base.py:369: in execute
    output = self.handle(*args, **options)
env/lib/python3.9/site-packages/django/core/management/base.py:83: in wrapped
    res = handle_func(*args, **kwargs)
env/lib/python3.9/site-packages/django/core/management/commands/migrate.py:231: in handle
    post_migrate_state = executor.migrate(
env/lib/python3.9/site-packages/django/db/migrations/executor.py:117: in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
env/lib/python3.9/site-packages/django/db/migrations/executor.py:147: in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
env/lib/python3.9/site-packages/django/db/migrations/executor.py:245: in apply_migration
    state = migration.apply(state, schema_editor)
env/lib/python3.9/site-packages/django/db/migrations/migration.py:124: in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
env/lib/python3.9/site-packages/django/db/migrations/operations/special.py:190: in database_forwards
    self.code(from_state.apps, schema_editor)
lettings/migrations/0002_auto_20220406_1825.py:13: in fill_address
    Old_address = apps.get_model("oc_lettings_site", "address")
env/lib/python3.9/site-packages/django/apps/registry.py:205: in get_model
    app_config = self.get_app_config(app_label)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.db.migrations.state.StateApps object at 0x7f3fd35b0b50>, app_label = 'oc_lettings_site'

    def get_app_config(self, app_label):
        """
        Import applications and returns an app config for the given label.
    
        Raise LookupError if no application exists with this label.
        """
        self.check_apps_ready()
        try:
            return self.app_configs[app_label]
        except KeyError:
            message = "No installed app with label '%s'." % app_label
            for app_config in self.get_app_configs():
                if app_config.name == app_label:
                    message += " Did you mean '%s'?" % app_config.label
                    break
>           raise LookupError(message)
E           LookupError: No installed app with label 'oc_lettings_site'.

env/lib/python3.9/site-packages/django/apps/registry.py:162: LookupError
------------------------------------------------------------- Captured stderr setup --------------------------------------------------------------
Creating test database for alias 'default'...
============================================================ short test summary info =============================================================
ERROR lettings/tests/unit/tests.py::TestLettings::test_index - LookupError: No installed app with label 'oc_lettings_site'.
================================================================ 1 error in 0.23s ================================================================

The test:

import pytest
from django.urls import reverse


@pytest.mark.django_db
class TestLettings:
    '''This is the testclass for index_view'''

    def test_index(self, client):
        '''This test ...'''
        response = client.get(reverse('lettings:index'))
        assert response.status_code == 200
Arthur
  • 13
  • 4
  • i restarted the project and changed the migrations files and now it works. So the problem came from the migrations. If someone knows why, i'm all ears. – Arthur Apr 13 '22 at 17:02

1 Answers1

2

It looks like your issue was that your migrations were missing a dependency.

Your letting app was attempting to use a Model from your oc_lettings_site app in one of it's migrations.

lettings/migrations/0002_auto_20220406_1825.py:13: in fill_address
Old_address = apps.get_model("oc_lettings_site", "address")

Django applies migrations in order and based on defined dependencies. When you makemigrations for a model that has a ForeignKey field, the dependency is added automatically.

In this case, you have created a function in the migration that references the other app manually. To fix this issue, you'd need to add a line to your dependencies in lettings/migrations/0002_auto_20220406_1825.py.

It would looks something like this:

dependencies = [
    ('lettings', '0001_initial'),
    ('oc_lettings_site', 'xxxx_auto_xxxxxxxx_xxxx'),
]

Where the first entry refers to your initial migration in the lettings app (since this is the second migration), and the second entry is the most recent migration in the oc_lettings_site app that references its address model.

Fred
  • 563
  • 3
  • 12