django - 为 TestCase 装置指定数据库
我的网站使用两个数据库,并且我有一个使用这两个数据库的应用程序。我需要编写一个为两个数据库加载固定装置的测试用例。我使用数据库路由器,它在生产中运行良好,但在测试框架中,Django 坚持对所有装置使用“默认”数据库,即使对于指定其他数据库的模型也是如此。我如何告诉 Django 针对另一个数据库运行固定装置?
我的测试用例定义列表:
class VerifierTestCase(TestCase):
fixtures = ['zipcodes_test.json', 'all_states.json', 'wtf.json']
multi_db = True
I have two databases that my site uses and I have an app that uses both of them. I need to write a TestCase that loads fixtures for both databases. I use a DB router, which works fine in production, but in the testing framework, Django insists on using the 'default' database for all fixtures, even for models that specify the other database. How do I tell Django to run a fixture against another database?
My TestCase is defined list:
class VerifierTestCase(TestCase):
fixtures = ['zipcodes_test.json', 'all_states.json', 'wtf.json']
multi_db = True
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,Django 中有一个错误,如果您指定整个设备名称,它会导致它忽略基于名称的数据库特定指针。
所以如果你这样做
fixtures = ["mydata.default.yaml", "mydata.myotherdatabase.yaml"]
它将把两个装置加载到默认数据库中。
但如果你这样做
fixtures = ['mydata']
它将正确加载。对于 dbengine 特定的文件名(例如
mydata.default.postgresql.sql
)也是如此。There is actually a bug in Django that causes it to ignore the name-based db-specific pointers if you specify the entire fixture name.
so if you do
fixtures = ["mydata.default.yaml", "mydata.myotherdatabase.yaml"]
It will load both fixtures into the default database.
But if you do
fixtures = ['mydata']
It will load correctly. This is also true for dbengine specific filenames (e.g.
mydata.default.postgresql.sql
) as well.夹具通过文件名针对特定数据库。在 TestCase 实例中也是如此,因为它们只是调用 loaddata 命令。
请参阅 https://docs.djangoproject.com/en /dev/ref/django-admin/#database-specific-fixtures
Fixtures are targeted at specific databases by filename. This is true in TestCase instances as well, as they just call the loaddata command.
See https://docs.djangoproject.com/en/dev/ref/django-admin/#database-specific-fixtures
如果您有一个多数据库设置,其中模型专用于每个数据库。您需要为每个数据库保存一个fixture文件(不适用的数据库文件为空)。
如果您的代码定义了
fixtures = ["sample"]
并且您有两个数据库default
和other
。您需要两个文件:
sample.default.json
和sample.other.json
。如果sample
仅包含数据库default
中的模型,则sample.other.json
将是一个空文件 ([]
),反之亦然。尝试过Django 3.2
If you have a multi-db setup with models exclusive to each database. You need to save a fixture file for each database (with the non-applicable database files being empty).
If your code defines
fixtures = ["sample"]
and you have two databasesdefault
andother
.You need two files:
sample.default.json
andsample.other.json
. Ifsample
contains only models from dbdefault
,sample.other.json
will be an empty file ([]
) and vice-versa.Tried with Django 3.2