【2】基数:0或1(可选)场景实例

基数:0或1(可选)

  有些情况下,文本部分可能存在或不存在。因此,此文本部分是可选的,基数为0或1(0..1),就可以解决可选的场景。

  parse_type.TypeBuilder可用于计算基数为零的类型或基于基数为一的数据类型计算基数为零的类型。

注意:

  使用步骤定义中的可选部分,通过在解析表达式中使用基数字段,可以更简单地解决此问题。

1.Feature 例子:

step_1.feature

# -*- coding: UTF-8 -*-
#"""
#Feature: 在步骤定义中使用可选部分
#
#  Scenario: Case 1"a "
#    Given ...
#    When ...
#
#  Scenario: Case 2 没有 "a "
#    Given ...
#    When ...
#"""

#file:features/step_1.feature
Feature: Data Type with Cardinality 0..1 (Optional Part)

  Scenario: Case1 "when this is a ..."
    Given the xiao has a 哈哈
    When this is a 三木李

  Scenario: Case2 "when this is ..."
    Given the xiao has a 哈哈
    When this is 格李艾斯

2.定义数据类型

#encoding:utf-8
#@Time:2020/4/9 17:17
#@Author:sunny

from behave import register_type
from parse_type import TypeBuilder
import parse

@parse.with_pattern(r"a\s+")
def parse_word_a(text):
    """ “a”的类型转换器(后跟一个/多个空格)."""
    return text.strip()

# -- 同样的:
# parse_optional_word_a = TypeBuilder.with_zero_or_one(parse_word_a)
parse_optional_word_a = TypeBuilder.with_optional(parse_word_a)
register_type(optional_a_=parse_optional_word_a)

#注意
# 函数的作用是:执行这个魔术。它为给定的单词/字符串选择计算正则表达式模式,
# 并将它们存储在parse_optional_word_a.pattern属性中。

# @mark.steps
# ----------------------------------------------------------------------------
# STEPS:
# ----------------------------------------------------------------------------
from behave import given, when, then
from hamcrest import assert_that, equal_to, is_in

# -- 可选部分: {:optional_a_}
# By using data type with cardinality zero or one (0..1, optional).
@when('this is {:optional_a_}{temp_name}')
def step_attacked_by(context,a_,temp_name):
    # -- 验证: 部分数据是否在feature中
    assert_that(a_, is_in(["a", None]))
    assert_that(temp_name, is_in(["三木李", "格李艾斯"]))

# ----------------------------------------------------------------------------
# MORE STEPS:
# ----------------------------------------------------------------------------

@given('the xiao has a {name}')
def step_the_xiao_has_a(context,name):
    # context.ha = xiao()
    pass

3.运行结果:

F:\AAM_project\exercise_v1\adf_behaveTest>behave
Feature: Data Type with Cardinality 0..1 (Optional Part) # features/step_1.feature:14

  Scenario: Case1 "when this is a ..."  # features/step_1.feature:16
    Given the xiao has a 哈哈             # features/steps/step_1.py:44
    When this is a 三木李                  # features/steps/step_1.py:32

  Scenario: Case2 "when this is ..."  # features/step_1.feature:20
    Given the xiao has a 哈哈           # features/steps/step_1.py:44
    When this is 格李艾斯                 # features/steps/step_1.py:32

1 feature passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
4 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.000s

F:\AAM_project\exercise_v1\adf_behaveTest>

从上面看:

可选逻辑,那么feature的When里面就是可以其中有a,也可以没有a,都行得通。

 

posted @ 2020-04-11 15:41  做一只热爱生活的小透明  阅读(296)  评论(0)    收藏  举报