如何为 Django 的 ORM 查询生成模板覆盖报告?
解读
国内 Django 项目普遍采用“模型层+视图层+模板层”三层结构,面试时问“模板覆盖报告”并不是要统计 HTML 模板文件被渲染了几次,而是想知道:
- 你是否理解“ORM 查询”与“模板渲染”是两个独立的运行时;
- 能否用 pytest 体系把“哪些查询在模板里被实际用到”量化出来,形成一份人眼可读的“模板层 SQL 覆盖”报告;
- 是否熟悉 coverage.py + pytest-django + django-debug-toolbar 的底层钩子,能在 CI 门禁里落地。
一句话:让面试官看到你既能写用例,又能把“查询→模板”链路可视化,还能集成到 GitLab-CI 的 merge request 卡点。
知识点
- pytest-django 的 db、django_db_setup、django_assert_num_queries 等 fixtures 与 markers。
- django.test.utils override_settings 动态开启 DEBUG=True 并拦截 connection.queries。
- coverage.py 的 dynamic context API,可在“进入/退出模板渲染”时切换 context,实现“模板级”粒度。
- Jinja2/Django Template 的 Node.render 钩子,通过猴子补丁注入探针,记录当前栈帧对应的 ORM SQL 指纹(fingerprint = md5(sql+params))。
- pytest-html、pytest-json-report 或 allure-pytest 二次开发,把“模板路径 + 其触发过的 SQL 指纹”写成可交互报告。
- GitLab-CI 的 artifacts:reports:coverage 格式,以及国内镜像源(清华、中科大)加速依赖安装。
- 性能红线:探针必须可关闭,生产环境零 overhead;单元测试里默认关闭,仅在“template-cov”job 开启。
答案
步骤一:建立可重复测试环境
pip install pytest-django pytest-cov django-debug-toolbar==3.2.2 allure-pytest –i https://pypi.tuna.tsinghua.edu.cn/simple
步骤二:在 conftest.py 里注册“模板覆盖”fixture
import json, hashlib, threading, coverage
from django.conf import settings
from django.test.utils import override_settings
from django.db import connection
from django.template import Node
local = threading.local()
def sql_fingerprint(sql, params):
return hashlib.md5(f"{sql}|{params}".encode()).hexdigest()[:8]
def patch_template_node():
original_render = Node.render
def instrumented_render(self, context):
cov = coverage.Coverage.current()
if cov and hasattr(local, 'template_stack'):
local.template_stack.append(self.origin.name)
try:
return original_render(self, context)
finally:
if cov and hasattr(local, 'template_stack'):
local.template_stack.pop()
Node.render = instrumented_render
@pytest.fixture(scope='session', autouse=True)
def enable_template_cov():
if os.getenv('ENABLE_TEMPLATE_COV') == '1':
patch_template_node()
coverage.process_startup()
@pytest.fixture(autouse=True)
def _collect_queries(request, db):
if os.getenv('ENABLE_TEMPLATE_COV') != '1':
yield
return
local.template_stack = []
queries_before = len(connection.queries)
yield
queries_after = connection.queries[queries_after:]
template = local.template_stack[-1] if local.template_stack else '<unknown>'
store = request.config.cache.get('template_sql', {})
for q in queries_after:
fp = sql_fingerprint(q['sql'], q['params'])
store.setdefault(template, set()).add(fp)
request.config.cache.set('template_sql', store)
步骤三:运行并生成报告
ENABLE_TEMPLATE_COV=1 pytest tests/ --cov --cov-report=json --cov-context=test
pytest-json-report 的 hook 里把 template_sql 读出,写成 template_coverage.json:
{
"templates/person_list.html": ["a9f3e2d8", "77bc901a"],
"templates/base.html": []
}
空数组代表“模板被渲染但未触发新 SQL”,可视为缓存命中。
步骤四:CI 集成
.gitlab-ci.yml:
template-cov:
stage: test
image: python:3.11
script:
- pip install -r requirements.txt
- ENABLE_TEMPLATE_COV=1 pytest --cov=myapp --cov-fail-under=80
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage.xml
paths:
- template_coverage.json
expire_in: 1 week
only:
- merge_requests
MR 页面即可看到“模板 SQL 覆盖率”指标,未覆盖到的模板会被评论机器人 @ 开发者。
拓展思考
- 分布式场景:Django 多数据库 + 只读副本,如何在 coverage 上下文里区分“主库”与“从库”查询,避免把缓存命中误判为未覆盖?
- 增量报告:基于 git diff 只检测变更模板,结合 pytest-testmon 实现“增量模板 SQL 覆盖”,把 10 分钟的全量流水线压缩到 90 秒,满足国内互联网公司“分钟级”门禁要求。
- 生产灰度:借助 OpenTelemetry 的 trace_id,把真实流量里的 SQL 指纹回写到模板覆盖平台,对比“测试覆盖”与“真实覆盖”,发现“测试未覆盖但线上高频”的模板,反向补充用例。