You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pytest调用MarkGenerator创建测试参数触发弃用警告的合规方案

合法实现pytest参数复用的方案

你不需要实例化pytest内部的MarkGenerator类来生成参数化标记,pytest已经在公共API层暴露了标记生成入口,直接使用即可完全规避弃用警告,且能实现完全一致的参数复用效果。

正确写法示例

import pytest

def parameters():
    # 直接通过公共入口pytest.mark生成parametrize标记
    return pytest.mark.parametrize("the_argument, the_result", [(1, 2), (2, 4)])

@parameters()
def test_multiplication(the_argument, the_result):
    # 这里写你的测试逻辑
    assert the_argument * 2 == the_result

注:原示例中测试函数定义时把参数写成了字符串"the_argument, the_result",属于笔误,函数参数位置直接写对应形参名即可,加引号会触发语法错误。

实现说明

  • 所有pytest标记(包括parametrize/skip/xfail以及自定义标记)的官方公共生成入口都是顶层导入的pytest.mark对象,直接调用对应方法生成的标记和你之前手动实例化内部类生成的效果完全一致,属于官方承诺长期兼容的公开用法,不会在后续版本被移除或抛出错误。
  • 所有以_pytest开头的模块都属于pytest内部实现模块,不对外保证API兼容性,日常开发中不要从这类模块下导入任何对象,所有公开能力都可以直接从顶层pytest模块导入获取。

如果要更方便地在多测试用例间复用同一组参数,还可以直接把参数化标记定义为常量,直接装饰到不同测试函数上即可:

import pytest

# 预定义可复用的参数集
MULTIPLICATION_TEST_CASES = pytest.mark.parametrize(
    "the_argument, the_result",
    [(1, 2), (2, 4), (3, 6), (0, 0)]
)

@MULTIPLICATION_TEST_CASES
def test_multiplication(the_argument, the_result):
    assert the_argument * 2 == the_result

@MULTIPLICATION_TEST_CASES
def test_double_add_calculation(the_argument, the_result):
    assert the_argument + the_argument == the_result

内容的提问来源于stack exchange,提问作者Milan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 16:18:20