Behave 数据类型


Behave中有两种类型的数据类型,即预定义的和用户定义的。让我们首先了解什么是预定义的数据类型。

预定义的数据类型


Behave 使用 parse 模块来解析步骤定义中的参数。让我们探索一些支持步骤定义并且不需要像用户定义的数据类型一样注册的解析类型。

  • w (of str type):下划线和字母。

  • W (of str type):下划线和非字母。

  • s(str类型):空格。

  • S (of str type):非空白。

  • d(int类型):数字。

  • D(str类型):非数字。

  • n (of int type): 有千位分隔符的数字。

  • %(浮点型):百分比。 (转换为值/100.0)

  • f (of float type): Fixed:点数。

  • e (float type): Floating:点数加上指数。

  • g(浮点型):数字格式。

  • b (of int type):二进制数。

  • (of int type):八进制数。

  • x (of int type): 十六进制数。

  • ti (of datetime type): ISO 8601 日期/时间格式的时间。

  • te(日期时间类型): RFC 2822 电子邮件数据/时间格式的时间。

  • tg(日期时间类型): 全局数据/时间格式的时间。

  • ta(日期时间类型):美国数据/时间格式的时间。

  • tc (datetime 类型): ctime() 数据/时间格式。

  • th (of datetime type):HTTP日志数据/时间格式的时间。

  • tt(时间类型)

在步骤实现中,我们将传递参数:“{}”中包含的数据类型。

具有 % 数据类型的功能文件

%数据类型的特征文件如下:

Feature: Payment Process
    Scenario Outline: Credit card transaction
    Given user is on credit card payment screen
    When user makes a payment of "<p>" percent of total
    例子s: Amounts
        | p      |
        |80%     |
        |90%     |

对应步骤实现文件

文件如下:

from behave import *
@given('user is on credit card payment screen')
def credit_card_pay(context):
    print('User is on credit card payment screen')
#passing parameter in % datatype enclosed in {}
@when('user makes a payment of "{p:%}" percent of total')
def step_impl(context, p):
    print('Number is: ')
    print(p)

运行特征文件后得到输出,使用的命令为 Behave --no-capture -f plain .

Pre-defined Data types

继续输出如下:

Data Types

输出显示从 % 数据类型获得的 0.8 和 0.9,表示从特征文件传递的 80% 和 90% 值。

用户定义的数据类型


Behave 还具有用户定义的数据类型。方法 register_type 用于注册一个用户定义的类型,该类型可以在匹配步骤时被解析为任何类型转换。

特征文件

以支付流程为特征的特征文件如下:

Feature: Payment Process
    Scenario Outline: Credit card transaction
        Given user is on credit card payment screen
        When user makes a payment of "<amount>" of total
        例子s: Amounts
            |amount  |
            |75      |
            |85      |

在步骤实现中,我们将传递参数:用“{}”括起来的用户定义数据类型。方法 register_type 用于注册一个用户定义的类型,该类型可以在匹配步骤时被解析为任何类型转换。

对应步骤实现文件

文件如下:

from behave import *
from behave import register_type
#convert parsed text to float
def parse_percent(t):
    return float(t)
#register user-defined type
register_type(Float=parse_percent)
@given('user is on credit card payment screen')
def credit_card_pay(context):
    print('User is on credit card payment screen')
@when('user makes a payment of "{amount:Float}" of total')
def step_impl(context, amount):
    print('Number is: ')
    print(amount)

运行特征文件后得到输出,使用的命令为 Behave --no-capture -f plain .

User-defined Data types

继续输出如下:

Float   0
值

输出显示 75.0 and 85.0 已转换为浮点值(借助用户定义的转换)。这些参数作为特征文件中的整数类型传递。