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!

 

 

转载于:https://www.cnblogs.com/Alex-Python-Waiter/archive/2012/10/30/2747142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值