获取测试套件中每个测试的SQL查询计数概述

2024-10-03 23:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大型Django应用程序,其中包含大量需要SQL查询优化的测试

我正在使用pytest django运行我的测试

我不想单独为每个测试添加assertNumQueriesdjango-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


Tags: djangopytest应用程序sqlpytestmydef
1条回答
网友
1楼 · 发布于 2024-10-03 23:31:06

为了记录查询计数,一个自动使用装置就足够了。在下面的示例中,我将计数存储在config对象下的queries_countdict中:

@pytest.fixture(autouse=True)
def record_query_count(request):
    from django.test.utils import CaptureQueriesContext
    from django.db import connection

    with CaptureQueriesContext(connection) as context:
        yield
    num_performed = len(context)

    if not hasattr(request.config, "query_counts"):
        request.config.query_counts = dict()
    request.config.query_counts[request.node.nodeid] = num_performed

为了输出结果,我在^{}钩子的自定义impl中添加了一个自定义节。将以下代码放入项目或测试根目录中名为conftest.py的文件中:

import os

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    content = os.linesep.join(
        f'{nodeid:40} | {num_queries}'
        for nodeid, num_queries in config.query_counts.items()
    )
    terminalreporter.ensure_newline()
    terminalreporter.section('number of queries', sep='-', bold=True)
    terminalreporter.line(content)

现在运行测试将产生:

tests/test_db.py ...                                                                [100%]

                 - number of queries                   
tests/test_db.py::test_add_entry      | 2
tests/test_db.py::test_remove_entry   | 2
tests/test_db.py::test_no_entries     | 1
=================================== 3 passed in 0.26s ====================================

相关问题 更多 >