2012-07-22 43 views
5

我写了一个单元测试,检查初始数据是否正确加载。然而Node.objects.all().count()总是返回0,因此它看起来因为灯具根本没有加载。命令行中没有输出/错误消息,表示灯具未加载。在测试期间未加载的夹具

from core.models import Node 

class NodeTableTestCase(unittest.TestCase): 
    fixtures = ['core/core_fixture.json'] 
    def setUp(self): 
     print "nothing to prepare..." 

    def testFixture(self): 
     """Check if initial data can be loaded correctly""" 
     self.assertEqual(Node.objects.all().count(), 14) 

夹具core_fixture.json含有14个节点,我使用下面的命令使用该夹具作为初始数据加载到分贝:

python manage.py loaddata core/core_fixture.json 

它们位于我在所提供的文件夹中settings.py设置FIXTURE_DIRS

回答

5

发现在另一个线程解决方案,answer from John Mee

# Import the TestCase from django.test: 

# Bad: import unittest 
# Bad: import django.utils.unittest 
# Good: import django.test 

from django.test import TestCase 

class test_something(TestCase): 
    fixtures = ['one.json', 'two.json'] 
    ... 

这样做我得到正确的错误信息,称外键被破坏,我不得不还包括该应用的灯具“AUTH ”。我使用此命令导出所需的数据:

manage.py dumpdata auth.User auth.Group > usersandgroups.json 

使用单元测试我只固定数据加载失败,这是不是非常有帮助的信息。

最后我工作的测试看起来像这样:

from django.test import TestCase 

class NodeTableTestCase2(TestCase): 
    fixtures = ['auth/auth_usersandgroups_fixture.json','core/core_fixture.json'] 

    def setUp(self): 
     # Test definitions as before. 
     print "welcome in setup: while..nothing to setup.." 

    def testFixture2(self): 
     """Check if initial data can be loaded correctly""" 
     self.assertEqual(Node.objects.all().count(), 11) 
1

在测试用例中加载fixture时,我不认为Django允许您包含目录名称。试着改变你的fixtures设置:

fixtures = ['core_fixture.json',] 

您可能需要改变你的FIXTURE_DIRS设置为好,包括core目录。

如果您在verbose mode中运行测试,您将看到Django尝试加载的fixture文件。这应该可以帮助您调试您的配置。

python manage.py test -v 2 
+0

感谢您的建议。我在FIXTURE_DIRS中也包含了核心目录。尽管我仍然可以使用loaddata命令加载灯具,但运行测试时出现以下错误:检查是否可以正确加载初始数据...失败 – 2012-07-23 07:31:13

+0

这可能与我的模型信号和数据冲突有关。然而,我不会用“if not kwargs.get('raw',False):”执行loaddata命令的信号,这个信号可能是在加载测试集中的灯具时执行的。会检查它。 – 2012-07-23 08:02:55

1

确保你有你的应用程序中INSTALLED_APPS列出您的应用包含models.py文件。