I was wandering around the internet in search of some people in need of help. I stumbled upon this thread where someone was asking, “How can I make test specific models?” and deep down I felt, “I know this is possible.” but wasn’t really sure how to do it.
After turning over some rocks, I found the solution on another thread. It looked interesting. So after I responded to the other thread with the link to the solution, I thought of trying it out myself.
The basic scenario for this problem is that you have a model, MyTestModel, that you want to test by inheriting from it when you run ‘python manage.py test’. A reason for wanting to do this could be that you want to examine different derivations of MyTestModel and selecting the best one among all the derivations. Doing this, there will be no need to syncdb the derived models into your database and then removing them afterwards.
To do this, let’s say you have an app called my_app containing MyTestModel. You then create another app, say model_test, which will contain the MyTestModel derivations. Take note, my_app should be included in your INSTALLED_APPS and model_test shouldn’t be so that when you syncdb, the models inmodel_test won’t get created. Now here comes the interesting piece of code that will do the magic. Create a TestCase inside the tests.py of my_app containing this snippet into your TestCase:
from django.conf import settings
from django.core.management import call_command
from django.db.models import loading
settings.INSTALLED_APPS += ('model_test',)
loading.cache.loaded = False
What it simply does is that it adds model_test in the INSTALLED_APPS of your project and runs a syncdb programmatically. And by the magic of running ‘python manage.py test’, you can test the performance of the MyTestModel derivations.
For more information, see http://stackoverflow.com/questions/502916/django-how-to-create-a-model-dynamically-just-for-testing