Django 测试:如何获取仅包含固定数据且没有 IntegrityErrors 的数据库(通过诊断错误源)?
我正在尝试使用夹具数据运行测试,并收到臭名昭著的 IntegrityError: column user_id is not unique
错误。
现在,查看我的装置,我可以看到装置中用户模型的 id 彼此之间是唯一的。我推断冲突与(非测试)数据库中的现有数据有关。这是正确的吗? (编辑:这似乎是不正确的 - 见下文)
我希望能够准确控制哪些数据可用于我的测试。有没有办法阻止 django testrunner 从我的实时数据库以及我的夹具数据加载数据? (编辑:是的 - 请参阅 Thibaut 的回答)。
编辑:按照 Thibaut 的回答切换到使用干净的内存数据库并不能解决问题。因此,我推断我现有的开发数据库不是问题。
所以,我有第三个问题:在测试期间加载夹具时如何诊断 IntegrityError 的原因?(以及,如何修复它?)
编辑 2:我的问题的解决方案,除了从干净的数据库开始(根据 Thibault J)之外,还可以从已安装的应用程序中消除引用用户的模型,直到错误不再发生。
DrTyrsa 的另一个建议(而不是查看数据)是使用 自然键,对于用户来说无疑需要一定数量的猴子补丁或其他黑客攻击(编辑用户的代码?)。
I'm trying to run tests with fixture data, and getting the infamous IntegrityError: column user_id is not unique
error.
Now, looking at my fixtures, I can see that the ids of my User models in my fixture are unique between each other. I infer that the clash is with existing data in (non-test) database. Is this correct? (Edit: This appears to be incorrect - see below)
I want to be able to control exactly what data are available to my tests. Is there a way to prevent the django testrunner from loading data from my live database, as well as my fixture data? (Edit: Yes - see Thibaut's answer).
Edit: Switching to using a clean, in memory database, as per Thibaut's answer does not fix the problem. Accordingly, I infer that my existing dev database is not the problem.
So, I have a third question: How do I diagnose the cause of an IntegrityError when loading fixtures during testing? (And, how do I fix it?)
Edit 2: The solution for my problem, in addition to starting with a clean database (per Thibault J) was also to eliminate models from installed apps referring to User, until the error no longer occurs.
DrTyrsa's other suggestion (than looking at the data), was to use natural keys, which for User would no doubt have required a certain amount of monkey-patching or other hackery (edit the code for User?).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用不同的数据库进行生产和测试(良好实践)。在
settings.py
中:在
test_settings.py
中:Use a different database for prod and tests (good practice). In
settings.py
:In
test_settings.py
: