pytest-bdd中同场景下复用带不同参数的相同步骤的实现方法
pytest-bdd非Examples表模式下复用同一步骤的实现方案
核心思路:利用pytest-bdd的步骤解析器动态获取参数名,从pytest运行时上下文拉取你通过@pytest.mark.parametrize注入的参数值,无需编写多份重复的step定义,全程不需要依赖Examples表。
方案1:正则匹配兼容现有Feature文件(无需改Feature代码)
直接修改step定义即可,用正则匹配步骤里的参数名,通过pytest自带的request fixture动态获取参数值,完全兼容你当前的Feature文件写法:
from pytest_bdd import when, parsers from some_lib import utils @when(parsers.re(r'I add <(?P<arg_name>argument\d+)> to the input')) def add_argument(context, request, arg_name): # 从测试运行上下文获取你通过parametrize注入的对应参数 argument = request.getfixturevalue(arg_name) context['input'] = utils.add_argument(context['input'], argument)
不管你后续需要加多少个add <argumentN>步骤,都不用修改step定义代码,适配性极强。
方案2:通用参数占位写法(适配任意参数名)
如果愿意微调Feature文件的步骤写法,可以实现任意参数名的通用匹配:
- 调整Feature里的步骤格式,给参数名加花括号:
Scenario Outline: Example scenario Given the subprocess is running When I generate the input And I add <{argument1}> to the input And I add <{argument2}> to the input And this input is passed to the subprocess Then the output should match the <output> for <argument1> and <argument2>
- 通用step定义:
from pytest_bdd import when, parsers from some_lib import utils @when(parsers.parse('I add <{arg_name}> to the input')) def add_argument(context, request, arg_name): argument = request.getfixturevalue(arg_name) context['input'] = utils.add_argument(context['input'], argument)
这个方案可以适配任意参数名,不管你参数叫user_id、order_id还是其他命名,都能正常复用同一份step实现。
以上两种方案均兼容你当前用@pytest.mark.parametrize做动态参数化的逻辑,参数值可以从任意fixture、动态生成的测试数据中获取,没有额外限制。
内容的提问来源于stack exchange,提问作者mattdekenah
相关产品推荐
相关产品推荐

