Login

Unit testing Django model mixins

Author:
michaelmior
Posted:
January 26, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

This facilitates unit tests for model mixins in Django. For more info, see my blog.

 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
from django.test import TestCase
from django.db import connection
from django.core.management.color import no_style
from django.db.models.base import ModelBase
 
class ModelMixinTestCase(TestCase):
    """
    Base class for tests of model mixins. To use, subclass and specify
    the mixin class variable. A model using the mixin will be made
    available in self.model.
    """
 
    def setUp(self):
        # Create a dummy model which extends the mixin
        self.model = ModelBase('__TestModel__'+self.mixin.__name__, (self.mixin,),
            { '__module__': self.mixin.__module__ })
 
        # Create the schema for our test model
        self._style = no_style()
        sql, _ = connection.creation.sql_create_model(self.model, self._style)
 
        self._cursor = connection.cursor()
        for statement in sql:
            self._cursor.execute(statement)
 
    def tearDown(self):
        # Delete the schema for the test model
        sql = connection.creation.sql_destroy_model(self.model, (), self._style)
        for statement in sql:
            self._cursor.execute(statement)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

zzhjerry (on May 11, 2016):

Hey, thanks for the recipe.

Another question is what if I also need field setup in the model?

#

Please login first before commenting.