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

Behave - Multi-Methods


Previous Page Next Page  

There are maybe 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 (almost similar steps)

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

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.

Multi-Methods

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