如何获取未加载的夹具的更多详细信息?
我有一个测试案例,但它似乎无法加载数据文件。
在测试数据库建立时,我看到这个错误:
No fixtures found.
.............................................Problem installing fixture '/Users/Bryan/work/CNPROG/forum/fixtures/forum_fixtures.json': Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/loaddata.py", line 169, in handle
obj.save(using=using)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/serializers/base.py", line 165, in save
models.Model.save_base(self.object, using=using, raw=True)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 543, in save_base
created=(not record_exists), raw=raw)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/dispatch/dispatcher.py", line 162, in send
response = receiver(signal=self, sender=sender, **named)
File "/Users/Bryan/work/CNPROG/forum/models.py", line 656, in record_ask_event
activity = Activity(user=instance.author, active_at=instance.added_at, content_object=instance, activity_type=TYPE_ACTIVITY_ASK_QUESTION)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/fields/related.py", line 302, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/query.py", line 341, in get
% self.model._meta.object_name)
DoesNotExist: User matching query does not exist.
class UserProfileTestCases(TestCase):
"""These are tests to verify that refactoring of UserProfile is correct"""
fixtures = ['forum_fixtures.json'] # apparently this needs to be in fixtures/ directory.
def setUp(self):
self.client = Client()
if self.client.login(username='DickCheney', password='test'):
print "client.login DickCheney successful";
else:
print "client.login FAILED"
不知道为什么数据文件没有加载。
这个数据文件的位置是:
forum/fixtures/forum_fixtures.json
我该如何输出数据文件没有加载的原因呢?
错误追踪信息显示在这里发生了一些事情:
文件 "/Users/Bryan/work/CNPROG/forum/models.py",第656行,在 record_ask_event 中
但我想不出这会影响数据文件加载的原因。
我查看了代码,发现 record_ask_events 是通过 post_save 事件调用的。
我成功运行了 manage.py loaddata forum_fixtures
,所以我相信我设置得没问题。
3 个回答
你需要修改一下你的 post_save 信号处理器,让它能处理 'raw' 这个参数。如果你这样做的话,在加载数据时就不会出现错误了:
@receiver(post_save, sender=MyModel, dispatch_uid='MyModelUID')
def handler(sender, *args, **kwargs):
if kwargs.get('raw'):
return
else:
...stuff
我也遇到了这个问题。我的应用程序已经在设置文件中的INSTALLED_APPS列表里了。根据Django的文档,它应该会在我的应用目录下的fixtures文件夹里搜索我在TestCase类的'fixtures'属性中放的文件名。但是这并没有奏效。我不想把我的数据文件命名为'initial_data.json',因为我只想在运行单元测试的时候使用它。
使用这个命令可以更详细地运行测试:
python manage.py test --verbosity=2
我通过调整数据的顺序解决了这个问题。
如果你有相关的对象,需要确保那些关联最多的对象(比如说 auth_user)在数据文件中排在最前面,因为在保存的时候可能会调用到这些相关的对象。
Django v1.2 只会查找名为 'initial_data' 的数据文件。它从来不会去找 'forum_fixtures.json'。
我把数据文件的名字改成了 'initial_data.json',现在就可以正常工作了。