如何使用sqllite在pytest中启用外键检查 [英] How can I enable foreign-key checks in pytest using sqllite
本文介绍了如何使用sqllite在pytest中启用外键检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Django项目,其测试在我调用py.test
时运行,但我最近注意到它没有检查外键约束。如何让它检查外键约束?
也许it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command.,但我不知道如何使我的测试做到这一点?
[更新] 因此,看起来sqlite开箱即用并未检查它们。
class Referenced(models.Model):
pass
class Referencer(models.Model):
fk = models.ForeignKey(Referenced)
>>> Referencer.objects.create(fk_id=-1)
<Referencer>
>>> Referencer.objects.all()[0].fk
DoesNotExist
推荐答案
我最终创建了一个包来解决此问题。
pip install sqlite_checkforeignkeys
然后配置数据库:
DATABASES = {
'default': {
'ENGINE': 'sqlite_checkforeignkeys_engine',
'TEST': {'NAME': ':memory:'},
}
}
它涉及重写现有的SQLite引擎以强制执行外键
有关详细信息,请访问https://github.com/hulu/sqlite_checkforeignkeys
这篇关于如何使用sqllite在pytest中启用外键检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文