【问题标题】:How to respond to django.test.Client using the test database如何使用测试数据库响应 django.test.Client
【发布时间】:2017-12-15 11:41:33
【问题描述】:

我有一个 django settings.py 文件,其中配置了一个数据库,导致两个 mysql 数据库,我们称它们为 dbnametest_dbname

当运行像python manage.py test ... 这样的命令时,像这样的对象选择

MyClass.objects.all()

将从test_dbname 中选择对象,到目前为止一切顺利。

另一方面,如果我测试生成一个 html 页面使用

client = django.test.Client()
response = client.post(...)

然后创建client 对象和post 参数的测试代码(或线程,我不确定)使用test_dbname,而服务post 请求并生成响应的线程使用@ 987654333@(没有 test_ 前置)。

这是一个不便,因为:

  1. 如果此类请求应该依赖于服务器线程的数据库,我的测试代码无法正确制定请求(即发布数据),从而导致类似How to test a Django form with a ModelChoiceField using test client and post method 的问题
  2. 现在有两个数据库在测试中,而我的测试代码似乎只能控制其中一个的内容,这使得测试变得不可预测。

我可以让服务器线程使用我可以从测试用例线程控制的数据库吗?

【问题讨论】:

  • 测试客户端不像 WSGI 服务器那样使用单独的线程。它只是直接调用相关的 Django 函数,否则这些函数会响应 WSGI 请求。如果查询引用了错误的数据库,您很可能在设置测试数据库之前执行查询。
  • 啊,谢谢,好像已经解决了,下面会描述情况。

标签: python mysql django django-1.9


【解决方案1】:

感谢 knbk 提供解决此问题的提示:答案是在单元测试开始之前不应运行任何查询。在我的情况下,这意味着替换像

这样的表单定义
class MyForm(forms.Form):
    my_field = forms.ChoiceField(choices=<somequery>)

在导入文件时运行somequery,即在测试用例运行之前,由:

class MyForm(forms.Form):
    my_field = forms.ChoiceField()
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(self, *args, **kwargs)
        self.fields['my_field'].choices = <somequery>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多