English 中文(简体)
Behave - Optional Part
  • 时间:2024-12-22

Behave - Optional Part


Previous Page Next Page  

There are maybe steps in the feature file having almost similar phrases. Behave has the parsing abipty 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 Cardinapty Field (CF) support. By default, it generates the missing type converters for connected cardinapty (if type converter for cardinapty equal to one is given).

It can support the below parse expressions −

    {values:Type+} – Cardinapty=1..N, many

    {values:Type*} – Cardinapty=0..N, many0

    {values:Type?} – Cardinapty=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"xs+")
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_? cardinapty 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 cardinapty fields within parse expression.

Advertisements