Behave 简明教程

Behave - Optional Part

在 feature 文件中可能存在具有几乎相似短语的步骤。Behave 具有解析能力以便一个步骤定义可以涵盖这些步骤。为此使用 use_step_parser 方法,并且我们必须将解析器类型作为参数传递给该方法。

对于扩展解析匹配,我们必须传递参数 cfparse。它具有基数字段 (CF) 支持。在默认情况下,它为连接的基数生成缺失的类型转换器(如果给定了基数等于一的类型转换器)。

它可以支持以下解析表达式−

  1. {values:Type+} – Cardinality=1..N, many

  2. {values:Type*} – Cardinality=0..N, many0

  3. {values:Type?} – Cardinality=0..1, optional

Feature File (almost similar steps)

具有非常相似步骤的功能文件如下 −

Feature − Payment Process
Scenario − Check Debit transactions
      Given user is on "debit" screen
   Scenario − Check Credit transactions
      Given user is on "credit" screen

register_type 方法用于注册用户定义的类型,以便在匹配步骤时可以对其进行任何类型转换的解析。

Corresponding Step Implementation File

步骤实现文件如下 −

from behave import *
import parse
#define parse type
use_step_matcher("cfparse")
# for whitespace characters
@parse.with_pattern(r"x\s+")
def parse_string(s):
#type converter for "x" succeeded by single/multiple spaces
   return s.strip()
#register user-defined datatype
register_type(x_=parse_string)
#optional part :x_? cardinality field in parse expression
@given('user is on {:x_?}{payment} screen')
def step_payment(context, x_, payment):
   print("Payment type: ")
   print(payment)

Output

运行功能文件后获得的输出如下,使用的命令是 behave --no-capture -f plain

optional part

输出显示 debitcredit 。这两个值通过特性文件中的几乎类似步骤来传递。在步骤实现中,我们在解析表达式的基数字段中解析了这两个步骤。