为什么在测试中没有将查询添加到Django的db.connection.queries?

时间:2010-09-07 22:51:19

标签: sql django testing

我正在尝试通过检查django.db.connection.queries的内容来捕获我的代码提交给数据库的查询。但是出于某种原因,在记录了所有自动生成的设置查询之后,不再从我自己的代码中记录进一步的查询。以下测试用例演示了该行为。

from django.test import TestCase
from django.db import reset_queries, connection
from django.contrib.auth.models import User
from django.conf import settings

class Test1(TestCase):
    def setUp(self):
        settings.DEBUG = True

    def test1(self):
        self.assert_(settings.DEBUG, 'DEBUG is False')
        reset_queries() #clears out all the setup queries
        User.objects.all()
        self.assert_(connection.queries, 'No queries')

以下是运行它的结果:

Traceback (most recent call last):
  File "/Users/jacob/foo/bar_project/baz_application/tests.py", line 246, in test1
    self.assert_(connection.queries)
AssertionError: No queries

有人能够对此有所了解吗?感谢。

3 个答案:

答案 0 :(得分:8)

您必须明确设置DEBUG。例如,请参阅django文档中的these tests的示例用法部分:

# Set up.
# The test runner sets settings.DEBUG to False, but we want to gather queries
# so we'll set it to True here and reset it at the end of the test suite.
>>> from django.conf import settings
>>> settings.DEBUG = True

更新:我可能会遗漏一些东西,但在每次测试中都应该解决这个问题。看看DjangoTestSuiteRunner - DEBUG中的setup_test_environment似乎设置为False,run_tests中调用DjangoTestRunner,后者实例化run method并调用其setup。因此,您需要撤消该操作 - 基于code的快速扫描,在{{1}}方法中执行此操作可能就足够了。

答案 1 :(得分:5)

执行User.objects.all()后,您不会看到任何疑问。这只是预料之中的。原因?查询集 lazy 。除非您对查询集执行某些操作,否则将触发查询。要验证此假设,请尝试以下操作并查看测试是否通过。

class Test1(TestCase):
    def setUp(self):
        settings.DEBUG = True

    def test1(self):
        self.assert_(settings.DEBUG, 'DEBUG is False')
        reset_queries() #clears out all the setup queries
        print User.objects.all() # <============= Printing the queryset.
        self.assert_(connection.queries, 'No queries')

答案 2 :(得分:3)

当您通过Django测试框架运行测试DEBUG is set to False explicitly时。