测试期间没有加载夹具

Tho*_*mel 5 django unit-testing fixtures

我写了一个单元测试,检查初始数据是否正确加载.但是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) 
Run Code Online (Sandbox Code Playgroud)

夹具core_fixture.json包含14个节点,我使用此夹具作为初始数据加载到db中使用以下命令:

python manage.py loaddata core/core_fixture.json
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*mel 5

在另一个主题中找到解决方案,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']
    ...
Run Code Online (Sandbox Code Playgroud)

这样做我得到了一个正确的错误消息,说外键被违反,我不得不包括应用程序"auth"的灯具.我用这个命令导出了所需的数据:

manage.py dumpdata auth.User auth.Group > usersandgroups.json
Run Code Online (Sandbox Code Playgroud)

使用Unittest我只得到加载夹具数据失败的消息,这不是很有帮助.

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

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)  
Run Code Online (Sandbox Code Playgroud)