abelcastro.dev

Create and use "dummy" Models in a Test Case in Django

2021-04-17

TestingDjango

Let's image we need a new model only for a test case and we don't really want to register in our project. We can create something similar than this:

example_app.tests.test_app.models.TestModel

from django.db import models


class TestModel(models.Model):
    field_a = models.IntegerField()
    field_b = models.IntegerField()

    class Meta:
        app_label = 'test_app'

We could try to use TestModel and create objects in a test case: test_models.py

from django.test import TestCase

from example_app.tests.test_app.models import TestModel


class TestOverridingInstalledApps(TestCase):
    def setUp(self):
        self.test_model = TestModel.objects.create(
            field_a=1,
            field_b=2,
        )

    def test_objects(self):
        self.assertEqual(TestModel.objects.count(), 1)

But if you run the tests like this, the test will fail and return something similar than that:

./manage.py test

django.db.utils.ProgrammingError: relation "test_app_testmodel" does not exist
LINE 1: INSERT INTO "test_app_testmodel" ("field_a", "field_b") VALU...

It fails because Django needs to have TestModel registered in INSTALLED_APPS but we don't really want to add our example_app.tests.test_app to INSTALLED_APPS because we only need it when we run the tests.

The solution is to to add the test_app to the settings with modify_settings and calling migrate.

test_models.py

from django.core.management import call_command
from django.test import TestCase, modify_settings

from example_app.tests.test_app.models import TestModel


@modify_settings(INSTALLED_APPS={
    'append': 'example_app.tests.test_app',
})
class TestOverridingInstalledApps(TestCase):
    def setUp(self):
        call_command('migrate', run_syncdb=True)
        self.test_model = TestModel.objects.create(
            field_a=1,
            field_b=2,
        )

    def test_objects(self):
        self.assertEqual(TestModel.objects.count(), 1)

You can see the complete source code here.