djangodjango-modelsdjango-testsdjango-apps

Django Test: how to simulate LookupError for django_apps.get_model()


I need help to implement a test for my Django app. This is a snippet code from my serializer, that I want to test:

        try:
            app_config = django_apps.get_app_config(BcConfig.name)
            app_model = django_apps.get_model(app_label=app_config.name,
                                              model_name=type_model_name)
            recording = app_model.objects.create(**recording)
        except LookupError:
            recording = None

as mentioned in Django docs, Raises LookupError if no such application or model exists.

How to simulate the LookupError programmatically?

I have tried to remove the listed model using ContentType, but django_apps.get_model() was still working. I have tried to remove the model using SchemaEditor, but not working properly for testing in SQLite. I also checked the DeleteModel() at Migration Operations.

I still can not find how to delete the model or disable the Django app programmatically. I appreciate the help. Thank you.


Solution

  • After getting a clue regarding "testing these properly is the job of Django developers", I checked how Django tests the apps.

    I found that there's a testing tool to override settings. So currently, my solution is to add the test method with decorator @override_settings(INSTALLED_APPS=LIST_WITHOUT_MY_APP). Then it triggered the LookupError exception as I expected.

    See more detail in the Django apps tests sample.

    hope it helps