[英]Fixtures not loaded during testing
我写了一个单元测试,检查初始数据是否正确加载。 但是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个节点,我使用此夹具作为初始数据加载到db中使用以下命令:
python manage.py loaddata core/core_fixture.json
它们位于我在settings.py
设置FIXTURE_DIRS
提供的文件夹中。
在另一个主题中找到解决方案, 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
使用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)
在测试用例中加载fixture时,我认为Django不允许你包含目录名。 尝试将fixtures
设置更改为:
fixtures = ['core_fixture.json',]
您可能还必须更改FIXTURE_DIRS
设置,以包含core
目录。
如果以详细模式运行测试,您将看到Django尝试加载的fixture文件。 这应该可以帮助您调试配置。
python manage.py test -v 2
确保您的应用已在INSTALLED_APPS
列出,并且您的应用包含models.py
文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.