背景
看看 @given、@when、@when 的源码
def given(name, converters=None, target_fixture=None):
"""Given step decorator.
:param name: Step name or a parser object.
:param converters: Optional `dict` of the argument or parameter converters in form
{<param_name>: <converter function>}.
:param target_fixture: Target fixture name to replace by steps definition function.
:return: Decorator function for the step.
"""
return _step_decorator(GIVEN, name, converters=converters, target_fixture=target_fixture)
def when(name, converters=None, target_fixture=None):
"""When step decorator.
:param name: Step name or a parser object.
:param converters: Optional `dict` of the argument or parameter converters in form
{<param_name>: <converter function>}.
:param target_fixture: Target fixture name to replace by steps definition function.
:return: Decorator function for the step.
"""
return _step_decorator(WHEN, name, converters=converters, target_fixture=target_fixture)
def then(name, converters=None, target_fixture=None):
"""Then step decorator.
:param name: Step name or a parser object.
:param converters: Optional `dict` of the argument or parameter converters in form
{<param_name>: <converter function>}.
:param target_fixture: Target fixture name to replace by steps definition function.
:return: Decorator function for the step.
"""
return _step_decorator(THEN, name, converters=converters, target_fixture=target_fixture)
类型
string(默认)
可以视为精确解析器,它不解析任何参数,根据提供的字符串精确匹配对应的步骤名称
parse(基于 pypi_parse)
- 提供一个简单的解析器,用像
{param:Type}
可读语法替换步骤参数的正则表达式 - 可以不提供类型
{username}
- 也可以提供类型
{username:s}
- 这个类型和写 string.format(“%s”) 时,支持的类型一样,比如 %d、%s、%f
cfparse(基于 pypi_parse_type)
没看懂官方文档的解析,乱七八糟的描述
re
支持完整的正则表达式来解析步骤参数,必须用这个表达式(?P<name>…)
parse 的 🌰(比较常用)
parser.feature
Feature: Step arguments
Scenario: Arguments for given, when, then
Given there are 5 cucumbers
When I eat 3 cucumbers
And I eat 2 cucumbers
Then I should have 0 cucumbers
test_parser.py
from pytest_bdd import scenario, given, when, then, parsers
@scenario("parser.feature", "Arguments for given, when, then")
def test_arguments():
pass
@given(parsers.parse("there are {start:d} cucumbers"), target_fixture="cucumbers")
def given_cucumbers(start):
print(start, type(start))
return dict(start=start, eat=0)
@when(parsers.parse("I eat {eat} cucumbers"))
def eat_cucumbers(cucumbers, eat):
print(eat, type("eat"))
cucumbers["eat"] += int(eat)
@then(parsers.parse("I should have {left:d} cucumbers"))
def should_have_left_cucumbers(cucumbers, left):
assert cucumbers['start'] - cucumbers['eat'] == left
命令行运行
pytest -sq test_parsers.py
运行结果
5 <class 'int'>
3 <class 'str'>
2 <class 'str'>
.
1 passed in 0.01s