django 单元测试中缺少固定装置没有错误
当 django 单元测试加载固定装置时,有没有办法查看错误?
令人烦恼的是,在运行 django 单元测试时,丢失文件、重复键或格式错误的固定文件等内容不会显示为错误。
Is there a way to see errors when django unit tests loads fixtures?
It's annoying that something like missing file, duplicate keys or badly formatted fixtures files do not show up as error when running django unit test.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果重复的主键在加载夹具时产生错误,许多现有的测试将被破坏。有时,夹具需要包含该错误,以便可以对其进行测试。
您可以编写通用测试来检查您提到的问题:
如果您的固定装置无法加载,则依赖于该固定装置的任何查询都将失败。编写一个尝试检索该固定装置中的对象的测试(例如,
YourObject.objects.get(pk=1)
或YourObject.objects.get(name='My Test Entry')
.要测试是否有重复的主键,请比较
YourObject.objects.all().aggregate(Count()。 'id',distinct=True))
到YourObject.objects.all().aggregate(Count('id'))
如果它们不相等,则主键重复。 .为了避免格式错误的固定文件,请从经过验证的数据生成它们。使用
manage.py dumpdata
,避免手动创建或编辑装置。提到的第一个测试将指示您是否有无效路径。最后的建议消除了格式错误的任何问题。
无提示失败是
loaddata
工作方式的结果。它正在多个位置查找fixtures = []
列表中给出的文件名,并且可能无法在其中任何一个位置找到文件。为了报告错误,loaddata
必须跟踪是否已找到文件,并且这需要修补程序。有一个用于静默失败的 trac 票据,但它已在“需要设计决策”中进行分类现在2年了。您可以选择在 Django 邮件列表上对此发表一些评论,并使用 您的 Django 开发副本中未经批准的补丁。
If duplicate primary keys generated an error when a fixture was loaded, many existing tests would be broken. Sometimes a fixture needs to contain that error, so it can be tested against.
You can write generic tests to check for the problems you've mentioned:
If your fixture fails to load, any query relying on that fixture will fail. Write a test that attempts to retrieve an object in that fixture (eg,
YourObject.objects.get(pk=1)
orYourObject.objects.get(name='My Test Entry')
.To test if you have duplicate primary keys, compare
YourObject.objects.all().aggregate(Count('id', distinct=True))
toYourObject.objects.all().aggregate(Count('id'))
. If those are not equal, you have duplicate primary keys.To avoid badly formatted fixture files, generate them from validated data. Use
manage.py dumpdata
, and avoid manually creating or editing fixtures.The first test mentioned will indicate if you have an invalid path. The last recommendation removes any issues with bad formatting.
The silent failure is a result of how
loaddata
works. It's looking for the filenames given in thefixtures = []
list in several locations, and may fail to find the files in any one of them. In order to report an error,loaddata
must track if a file has been found yet, and that requires a patch. There's a trac ticket for the silent fail, but it has been triaged at 'Design Decision Needed' for 2 years now.You have the option to make some noise about this on the Django mailing list, and use the unapproved patch in your development copy of Django.
您可以尝试在setUp()中定义自己的验证方法。测试您的灯具是否已加载将非常容易,但是,验证您的灯具将需要相当多的工作,具体取决于您的灯具的格式。
You can try to define your own validation method in setUp(). Testing if your fixtures are loaded would be quite easy, however, validating your fixtures would require quite a bit work depending on what format is your fixture.