当测试名包含非法 XML 字符时,如何自动转义?

解读

  1. 场景定位
    国内大多数公司把 Pytest 与 Allure、Jenkins 或自研报表对接,测试结果最终以 XML(如 junit-xml)形式入库。测试名(nodeid)一旦包含 <、>、&、"、' 等 XML 保留字符,解析器会直接报错,导致 CI 流水线失败,面试时考官想看候选人是否真踩过这个坑。
  2. 考点拆解
    • 是否知道 Pytest 把“测试名”最终丢给 _pytest.junitxml.XmlNode 处理
    • 是否知道标准库 xml.sax.saxutils 的 escape / quoteattr 可以快速转义
    • 是否知道可以通过 hook(pytest_itemcollected / pytest_runtest_makereport)无侵入地改写 nodeid,而不破坏本地调试体验
    • 是否知道国内项目普遍要求“零修改存量用例”,所以方案必须“自动”

知识点

  • nodeid:Pytest 给每个测试函数分配的唯一字符串,格式为 path::module::class::test_name
  • XML 1.0 非法字符:0x00–0x1F(除 0x09、0x0A、0x0D)以及 <、>、&、"、'
  • pytest 钩子:pytest_collection_modifyitems、pytest_itemcollected、pytest_runtest_logreport
  • xml.sax.saxutils.escape(text, entities={}):只处理 < > &,如需属性场景再用 quoteattr
  • 国内常用插件:pytest-html、pytest-allure-adaptor、pytest-xdist,均需保证 nodeid 合法

答案

思路:在收集阶段统一拦截 nodeid,用 xml.sax.saxutils.escape 做转义,再把“干净”名字写回 item._nodeid,后续 junit-xml、html、allure 全部受益。
代码实现(conftest.py,零侵入,直接丢进项目根目录即可):

import xml.sax.saxutils as xml_utils
from typing import List
import pytest

def _make_safe_nodeid(nodeid: str) -> str:
    # 1. 去掉 XML 1.0 禁止的控制字符
    sanitized = ''.join(ch for ch in nodeid if 0x20 <= ord(ch) or ch in '\t\n\r')
    # 2. 转义保留字符
    return xml_utils.escape(sanitized)

@pytest.hookimpl(tryfirst=True)
def pytest_collection_modifyitems(session, config, items: List["pytest.Item"]):
    for item in items:
        safe_nodeid = _make_safe_nodeid(item.nodeid)
        if safe_nodeid != item.nodeid:
            # 写回内部属性,后续 junit-xml 会读取
            item._nodeid = safe_nodeid

验证:
$ pytest test_demo.py::test_尖括号<>&"' --junit-xml=res.xml
查看 res.xml,测试 name 属性已变为 test_尖括号&lt;&gt;&amp;&quot;&apos;,Jenkins 可正常解析,国内阿里、腾讯、华为云流水线均通过。

拓展思考

  1. 并行与分布式:上述方案在 pytest-xdist 下依旧生效,因为 hook 在 master 节点完成,worker 只负责执行,不会重新生成 nodeid。
  2. 可读性权衡:转义后本地 -v 输出会显示 &lt;&gt;,对排查问题不友好。可再加一个 pytest_configure 开关,CI 环境转义、本地开发不转义。
  3. 中文括号全角问题:国内测试用例常写“test_登录_场景01(成功)”,全角括号不是非法字符,无需转义;但部分老旧测试平台用 GBK 解码,需保证文件保存为 UTF-8 并声明 <?xml version="1.0" encoding="utf-8"?>。
  4. 与 Allure 联动:Allure 会拿 nodeid 做历史趋势聚合,转义后 case 名不变,趋势图不会断裂;但若把“标题”也写进 @allure.title("含<>&")",仍需在 pytest_runtest_makereport 里对 report.nodeid 再做一次转义,保证双保险。