Behave – Optional Part

Behave - Optional Part

In this chapter, we will discuss Behave Optional Part. There are maybe steps in the feature file having almost similar phrases. Behave has the parsing ability so that one step definition can cover these steps.

For extended parse matches, we have to pass the parameter cp parse. It has the Cardinality Field (CF) support. B

It can support the below parse expressions βˆ’

  • {values:Type+} – Cardinality=1..N, many
  • {values:Type*} – Cardinality=0..N, many0
  • {values:Type?} – Cardinality=0..1, optional

Feature File (almost similar steps)

The feature file with almost similar steps is as follows βˆ’

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

Behave Optional Part in the method register_type is used to register a user-defined type that can be parsed for any type conversion at the time of matching the step.

Corresponding Step Implementation File

The step implementation file is below βˆ’

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

The output obtained after running the feature file is given below and the command used is behaving –no-capture -f plain.

Behave - Optional Part

The output shows theΒ debitΒ andΒ credit. These two values have been passed with almost similar steps in the feature file. In step implementation, we have parsed both the steps with cardinality fields within the parse expression.

Next Topic – Click Here

This Post Has One Comment

Leave a Reply