Login

Run a testcase with custom INSTALLED_APPS

Author:
vdboor
Posted:
November 8, 2012
Language:
Python
Version:
1.4
Tags:
settings testing test syncdb
Score:
1 (after 1 ratings)

This code allows you to register a model to Django that is only used for unit testing. It will not exist in the regular Django workflow. After the tests executed, the Django settings are restored.

Usage:

  1. Change tests.py into a tests package.
  2. Place a models.py in the tests package.
  3. Use the following code below to enable it.

Example:

class MyTest(CustomSettingsTestCase):
    new_settings = dict(
        INSTALLED_APPS=(
            'django.contrib.contenttypes',
            'django.contrib.auth',
            'app_to_test',
            'app_to_test.tests',
        )
    )

Based on http://djangosnippets.org/snippets/1011/ as Django 1.4 version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from django.core.management import call_command
from django.db.models import loading
from django.test import TestCase
from django.test.utils import override_settings


class CustomSettingsTestCase(TestCase):
    """
    A TestCase which makes extra models available in the Django project, just for testing.
    Based on http://djangosnippets.org/snippets/1011/ in Django 1.4 style.
    """
    new_settings = {}
    _override = None


    @classmethod
    def setUpClass(cls):
        cls._override = override_settings(**cls.new_settings)
        cls._override.enable()
        if 'INSTALLED_APPS' in cls.new_settings:
            cls.syncdb()


    @classmethod
    def tearDownClass(cls):
        cls._override.disable()
        if 'INSTALLED_APPS' in cls.new_settings:
            cls.syncdb()


    @classmethod
    def syncdb(cls):
        loading.cache.loaded = False
        call_command('syncdb', verbosity=0)

More like this

  1. Test runner that installs 'tests' packages as apps by adrian_lc 1 year, 6 months ago
  2. Use django-social-auth & Google Accounts for admin login by pmdarrow 2 years, 4 months ago
  3. Template tag to create mailto links with options by celopes 5 years, 10 months ago
  4. Simple Plone Migration by msm-art 7 years, 3 months ago
  5. yandex maps templatetag by coolchevy 2 years, 10 months ago

Comments

Please login first before commenting.