Behave – Hooks
”;
Behave setup and teardown functions are implemented in a file called the environment.py 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 environment.py 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 −
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"]) register_type(Amt=parse_amt) parse_curr = TypeBuilder.make_choice(["INR", "Dollar"]) register_type(Curn=parse_curr) @given("user makes a payment of {n:Amt} {t:Curn}") def step_payment(context, n, t): pass @given(''user is on admin screen'') def step_admin(context): pass
Step 4 − Hooks in environment.py file
The hooks in environment.py 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'')
Output
The output obtained after running the feature files is as follows −
”;