A trick in loading Fixture to test django application

A test case for a database-backed Web site isn't much use if there isn't any data in the database. To make it easy to put test data into the database, Django's custom TestCase class provides a way of loading fixtures.(see detail here)

Once you've created a fixture and placed it in a fixtures directory in one of your INSTALLED_APPS, you can use it in your unit tests by specifying a fixtures class attribute on your django.test.TestCase subclass:

from django.test import TestCase
from myapp.models import Animal

class AnimalTestCase(TestCase):
    fixtures = ['myfixture.json']

    def setUp(self):
        # Test definitions as before.
        call_setup_methods()

    def testFluffyAnimals(self):
        # A test that uses the fixtures.
        call_some_test_code()

However, if you need to add setUpClass(), the fixtures won't work.

In fact, fixture can't be inserted before setUpcClass() excuted.

To solve this problem, we could call the command "python admin.py loaddata myfixture.json" in setUpClass() method. Refine the code like below:

from django.test import TestCase
from myapp.models import Animal
from django.core import management

class AnimalTestCase(TestCase):def setUpClass(cls):
        # use command to load fixture
        management.call_command("loaddata", "myfixture.json")
        call_setup_methods()

    def testFluffyAnimals(self):
        # A test that uses the fixtures.
        call_some_test_code()

If this project is not developed and tested in PyDev, it's okay now.

Otherwise there is another wired problem for fixture when you run the test case by clicking "run as unittest" in Eclipse PyDev, the fixture data doesn't work for other test method except setUpClass() in the testCase class. To make it work, you have to modify the code like below:

from django.test import TestCase
from myapp.models import Animal
from django.core import management

class AnimalTestCase(TestCase):
    fixtures = ['myfixture.json']

    def setUpClass(cls):
        # use command to load fixture
        management.call_command("loaddata", "myfixture.json")
        call_setup_methods()

    def testFluffyAnimals(self):
        # A test that uses the fixtures.
        call_some_test_code()

Not clear about the reason, maybe a little defect in PyDev, or just my misunderstand, any suggestion is welcome!

 

 

posted @ 2012-10-30 22:15  Alex_Waiter  阅读(744)  评论(0编辑  收藏  举报