Behave - Multi-methods



There may be steps in the feature file having almost similar phrases. For instance,

Given user makes payment of 100 INR
And user makes payment of 10 Dollar

Here, we can have different step definitions to differentiate the INR and Dollar. For this, we can use the multi-method approach, where it is mandatory to have varied regular expressions for the dissimilar data types.

Feature File - payment.feature

Consider the feature file as given below −

Feature: Multi-Methods
   Scenario: Purchase
      Given User is on shop
      When user purchases 3 shirts
      And user purchases 4 pants

In the step implementation file, TypeBuilder.make_choice function evaluates a regular expression pattern for the provided choices. 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.

Also, we shall pass the parameter: user-defined datatype enclosed in "{}".

Corresponding Step Implementation File - stepImpPayment.py

The step implementation file is as follows −

from behave import *
from behave import register_type
from parse_type import TypeBuilder

parse_dress = TypeBuilder.make_choice(["shirts", "t-shirts"])
#register user-defined datatype
register_type(Dress=parse_dress)
parse_pant = TypeBuilder.make_choice(["pants", "gowns"])
#register user-defined datatype
register_type(Pant=parse_pant)
@given("User is on shop")
def step_user_shop(context):
      pass
# multiple methods being used .
@when(u"user purchases {count:n} {d:Dress}")
def step_dress(context, count, d):
      print("User purchased: ")
      print(d)
      print("Count is:")
      print(count)
@when(u"user purchases {count:n} {p:Pant}")
def step_pant(context, count, p):
      print("User purchased: ")
      print(p)
      print("Count is:")
      print(count)

Output

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

(myenv) D:\behave\myenv\pythonProject>behave --no-capture -f plain
USING RUNNER: behave.runner:Runner
Feature: Multi-Methods

  Scenario: Purchase
    Given User is on shop ... passed in 0.000s
User purchased:
shirts
Count is:
3
    When user purchases 3 shirts ... passed in 0.000s
User purchased:
pants
Count is:
4
    And user purchases 4 pants ... passed in 0.000s

1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
3 steps passed, 0 failed, 0 skipped
Took 0min 0.000s

The output shows the purchase items and their counts. These two values have been passed with almost similar steps (but dissimilar data types) in the feature file. In step implementation, we have used multiple methods to obtain the values.

Advertisements