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. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method.

For extended parse matchers, we have to pass the parameter cfparse. It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given).

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

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 given 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 behave --no-capture -f plain.

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 parse expression.

Advertisements