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

55 Views Asked by At

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.

2

There are 2 best solutions below

0
oon arfiandwi On BEST ANSWER

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

4
willeM_ Van Onsem On

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.

It does not look at databases. The django_apps dictionary only looks what models registered when starting to run the server. So these models don't per see have a corresponding table in the database.

If you want to test this, you can just pass non-sensical values, like:

type_model_name = 'my_non_existing_model_name'
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

But that being said, it often makes not much sense to test Django's features: testing these properly is the job of the Django developers, not of people building apps for Django. Their job is to test features that they have built on top of Django.