Behave 数据类型
Behave有两种数据类型,分别是预定义的和用户定义的。让我们先了解什么是预定义的数据类型。
预先定义的数据类型
Behave在步骤定义中利用parse模块来解析参数。让我们来探讨一些支持步骤定义的解析类型,它们不需要像用户定义的数据类型那样被注册。
- w (of str type) – Underscore & letters.
-
W(属于str类型)–下划线和非字母。
-
s (str类型) – 空白。
-
S (str类型) – 非白字。
-
d (int类型) – 数字。
-
D(字符串类型)- 非数字。
-
n (int类型) – 有千位分隔符的数字。
-
% (float类型) – 百分比。(翻译成数值/100.0)
-
f (float类型) – 固定点的数字。
-
e (浮动类型) – 浮动点的数字,带有指数。
-
g(浮点数类型)–数字格式。
-
b (int类型) – 二进制数。
-
(int类型) – 八进制数。
-
x (int类型) – 十六进制的数字。
-
ti (数据时间类型) – ISO 8601日期/时间格式的时间。
-
te (数据时间类型) – RFC 2822电子邮件数据/时间格式的时间。
-
tg (数据时间类型) – 全球数据/时间格式的时间。
-
ta (数据时间类型) – 美国数据/时间格式的时间。
-
tc(数据时间类型)–ctime()数据/时间格式。
-
th (数据时间类型) – 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
Examples: 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
继续输出如下 –
输出显示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
Examples: 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
继续输出如下 –
输出显示 75.0 和 85.0 ,它们已被转换为浮动值(在用户定义的转换帮助下)。这些参数作为整数类型从特征文件中传递。