pytest 8.2.0+ 弃用 pytest.warns 的位置参数调用,须改用 keyword 参数:仅检查类型用 category=Warning,匹配消息用 match=r"pattern"(正则),二者兼具则同时指定。

pytest 3.12 中 pytest.warns 的弃用警告从哪来
不是 Python 3.12 的问题,而是你用的 pytest 版本(≥ 8.2.0)开始把 pytest.warns 的旧调用方式标为废弃。典型警告是:PytestDeprecationWarning: Passing positional arguments to pytest.warns is deprecated。这说明你写了类似 pytest.warns(UserWarning, "expected message") 这种写法——它在新版本里不被鼓励了。
怎么改写 pytest.warns 才不报错
必须显式使用关键字参数,不能再靠位置传参。核心原则:警告类型和匹配内容必须用 match 或 category 明确指定。
- 只检查警告类型(不关心内容)→ 用
category=MyWarning - 要匹配警告消息 → 用
match=r"pattern"(正则字符串),不能直接传字符串字面量 - 两者都要 → 同时写
category=UserWarning, match=r"deprecated"
示例对比:
def test_old_way():
# ❌ 报废弃警告
with pytest.warns(UserWarning, "use new API"):
my_func()
<p>def test_new_way():</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/gongju/2944" title="pytest 8.4.1"><img
src="https://img.php.cn/upload/manual/001/221/864/6b05341a6b720160.png" alt="pytest 8.4.1" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/gongju/2944" title="pytest 8.4.1">pytest 8.4.1</a>
<p>pytest 8.4.1 官方版本安装包。</p>
</div>
<a href="/xiazai/gongju/2944" title="pytest 8.4.1" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><h1>✅ 正确写法</h1><pre class='brush:python;toolbar:false;'>with pytest.warns(category=UserWarning, match=r"use new API"):
my_func()为什么必须用 match 而不是字符串相等
match 接收正则表达式,不是子串匹配。这是为了更严谨地验证警告内容——比如避免因空格、换行或额外前缀导致误判。如果你习惯用 "warning text" 直接匹配,现在会失效,且不会报错,只是匹配失败(即警告没被捕获,测试可能意外通过)。
- 想做简单包含匹配?写
match=r".*warning text.*" - 要精确开头结尾?加
^和$,如match=r"^Deprecated since.*v2\.0$" - 忽略大小写?用
match=re.compile("deprecated", re.IGNORECASE)
其他容易漏掉的废弃点
除了 pytest.warns,pytest 8.2+ 还悄悄标记了几个老接口:
-
pytest.approx的abs/rel参数名已废弃,改用abs_tol/rel_tol - 自定义
pytest_runtest_makereporthook 中访问report.longrepr可能触发警告,应改用report.longreprtext - 命令行里用
--strict-markers已被--strict-markers替代(名字没变,但行为更严格;不过若你用了旧的--strict,它已彻底移除)
运行测试时加 -W error::pytest.PytestDeprecationWarning 可把所有这类警告转成错误,提前暴露问题。
最常被忽略的是:警告本身不中断执行,所以即使 CI 没报错,实际已在输出里埋了废弃提示——等升级到下一个大版本,这些调用就真失效了。

















