我有一个大型Django应用程序,其中包含大量需要SQL查询优化的测试
我正在使用pytest django运行我的测试
我不想单独为每个测试添加assertNumQueries
或django-assert-num-queries
,而是概述一下所有测试中的每个测试都触发了多少SQL查询,以了解哪些代码最需要优化,如下所示:
test | number of queries
------------------------------------------------
test_a.py::test_my_function1 | 5
test_a.py::test_my_function3 | 2
test_a.py::test_my_function5 | 7
是否可以在conftest.py中配置pytest钩子,该钩子计算每个(DB)测试的SQL查询数并在结果中显示它们,而无需修改我的测试源(如添加装饰器)
我的天真方法是使用这些挂钩,并在每次测试前后以某种方式访问数据库连接:
def pytest_runtest_call(item):
pass
def pytest_runtest_teardown(item, nextitem):
return True
为了记录查询计数,一个自动使用装置就足够了。在下面的示例中,我将计数存储在config对象下的
queries_count
dict中:为了输出结果,我在^{} 钩子的自定义impl中添加了一个自定义节。将以下代码放入项目或测试根目录中名为
conftest.py
的文件中:现在运行测试将产生:
相关问题 更多 >
编程相关推荐