Behave - Hooks

Behave setup and teardown functions are implemented in a file called the which is within the same directory that contains the steps folder. The setup functions include – browser open, database connection, configurations, and so on.

The teardown functions include browser closure, database connection termination, reversing changes, and so on.

The file contains the following functions −

  • before_feature(context, feature) − Executes prior every feature.

  • before_scenario(context, scenario) − Executes prior every scenario.

  • before_step(context, step) − Executes prior every step.

  • before_tag(context, tag) − Executes prior every tag.

  • before_all(context) − Executes prior everything.

  • after_feature(context, feature) − Executes post every feature.

  • after_scenario(context, scenario) − Executes post every scenario.

  • after_step(context, step) − Executes post every step.

  • after_tag(context, tag) − Executes post every tag.

  • after_all(context) − Executes post everything.

The above functions are used as hooks in Behave. Project structure should be as follows −

Project Structure

Feature File with hooks (Payment.feature)

The feature file with hooks for Payment.feature is as follows −

Feature − Payment Process
Scenario − Verify transactions
         Given user makes a payment of 100 INR And user makes a payment of 10 Dollar

Feature File with hooks (Payment1.feature)

Given below is the feature file with hooks for Payment1.feature −

Feature − Administration Process
Scenario − Verify admin transactions
         Given user is on admin screen

Corresponding step Implementation File

The step implementation file is as follows −

from behave import *
from parse_type import TypeBuilder
parse_amt = TypeBuilder.make_choice(["100", "10"])
parse_curr = TypeBuilder.make_choice(["INR", "Dollar"])
@given("user makes a payment of {n:Amt} {t:Curn}")
def step_payment(context, n, t):
@given('user is on admin screen')
def step_admin(context):

Step 4 − Hooks in file

The hooks in file are as follows:

# before all
def before_all(context):
   print('Before all executed')
# before every scenario
def before_scenario(scenario, context):
   print('Before scenario executed')
# after every feature
def after_feature(scenario, context):
   print('After feature executed')
# after all
def after_all(context):
   print('After all executed')


The output obtained after running the feature files is as follows −