Skillversitas

Hooks and environment.py

Behave calls hook functions at fixed points of every run: before and after the whole run, every feature, every scenario, and every step. You define them as plain functions in a file named environment.py, placed in the feature directory next to the step files. Hooks let you prepare and clean up resources without polluting the step definitions with setup code.

The Hook Functions

# features/environment.py
import time

def before_all(context):
    context.db = create_test_database()
    context.start = time.time()

def after_all(context):
    context.db.close()
    print(f"run finished in {time.time() - context.start:.1f}s")

def before_feature(context, feature):
    context.feature = feature

def after_feature(context, feature):
    pass

def before_scenario(context, scenario):
    context.scenario = scenario

def after_scenario(context, scenario):
    context.db.rollback()

def before_step(context, step):
    pass

def after_step(context, step):
    pass

Each hook takes the context plus the object it applies to (feature, scenario, or step). Define only the hooks you need; behave skips the rest silently.

What Hooks Are For

  • Shared resources: open one database connection in before_all, close it in after_all, instead of opening one per step.
  • Per-scenario cleanup: after_scenario is the natural place to roll back transactions or delete seeded rows, so every scenario starts clean.
  • Timing and logging: measure or annotate runs without touching a single step file.
  • State flags: read a step's outcome in after_step (the step.status attribute) and react, for example by saving a screenshot on failure.

Error Handling in Hooks

An exception inside a before_* hook fails the scenario it belongs to. An exception inside an after_* hook is caught by behave, the error is appended to the scenario report, and the run continues: teardown must not mask the real test result. Keep after_* hooks defensive.

Summary

Define before_all ... after_all hooks in environment.py to manage resources that outlive single steps. Use before_ hooks for setup that must succeed, and defensive after_ hooks for cleanup that must not hide failures.