Login

Run a testcase with custom INSTALLED_APPS

Author:
vdboor
Posted:
November 8, 2012
Language:
Python
Version:
1.4
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.