Jac*_*cob 8 sql testing django
我正在尝试通过检查我的代码来检索我的代码提交到数据库的查询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')
Run Code Online (Sandbox Code Playgroud)
以下是运行它的结果:
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
Run Code Online (Sandbox Code Playgroud)
有人能够对此有所了解吗?谢谢.
你必须明确设置DEBUG.例如,请参阅django文档中的这些测试的示例用法部分:
# 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
Run Code Online (Sandbox Code Playgroud)
更新:我可能会遗漏一些东西,但在每次测试中都应该解决这个问题.看看DjangoTestSuiteRunner- 似乎DEBUG在setup_test_environment被调用的中设置为False run_tests,它继续实例化a DjangoTestRunner并调用它run method.因此,您需要撤消该操作 - 基于快速扫描代码,在您的setup方法中执行此操作可能就足够了.
执行后您将看不到任何查询User.objects.all().这只是预料之中的.原因?查询集很懒惰.除非您对查询集执行某些操作,否则将触发查询.要验证此假设,请尝试以下操作并查看测试是否通过.
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1751 次 |
| 最近记录: |