AUTOMATION FRAMEWORKS

Sharing Test Data Across a Behave Suite Safely

Behave's context object is the obvious place to share data between steps, hooks and scenarios, and that's exactly why it gets misused. A value set in one scenario turns up in the next. A list created in before_all quietly accumulates items across the whole run. A scenario passes on its own and fails when run after a particular other one.

Most of these problems come from not knowing which layer of context a value lives on, and how long it survives. Once that's clear, sharing data safely is mostly a matter of putting each kind of data at the right level and making anything mutable belong to one scenario.

There's also a newer source of bleed. When GitHub Copilot or a coding agent writes step definitions, it tends to stash whatever it needs on context wherever is convenient, or in a module-level variable. In this article I'll cover how the layers work, where each kind of data belongs, how to keep mutable state from leaking, how to structure environment.py, and the rules I give agents so generated steps follow the same discipline.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

How context layers work

Behave's context is layered. When a feature starts, Behave pushes a new layer; when a scenario starts, it pushes another. Attributes you set are stored on the current top layer, and when that feature or scenario finishes, its layer is removed along with everything set on it. Reads look through the layers from the top down.

So the lifetime of a value depends on where you set it:

  • Set in before_all: lives for the whole run. Visible everywhere.
  • Set in before_feature: lives until the end of that feature.
  • Set in before_scenario or in a step: removed when the scenario ends.

This is helpful, because scenario-level values clean themselves up. But there's a catch that causes most bleed: the cleanup only removes the attribute, not changes made to an object that lives on a lower layer. If before_all sets context.created_ids = [] and a step appends to it, the append changes the run-level list. The scenario layer has nothing to remove, and the next scenario sees the extra item.

Put each kind of data at the right level

The mental model I use:

  • Run level, read-only: configuration, base URLs, an API client, reference data that no test changes. Set it in before_all and never mutate it.
  • Feature level: rarely needed. If scenarios in a feature need the same expensive read-only setup, it can live here.
  • Scenario level, everything mutable: the current user, the last response, created resource ids, anything a step writes. Set it in before_scenario or in steps.
# features/environment.py
import os

from test_support.api_client import ApiClient  # your own client module


def before_all(context):
    context.config_base_url = os.environ.get("API_BASE_URL", "http://localhost:8000")
    context.api = ApiClient(context.config_base_url, token=os.environ["API_TOKEN"])


def before_scenario(context, scenario):
    # Fresh, scenario-owned state. Removed automatically when the scenario ends.
    context.created = []
    context.response = None

The rule that prevents most problems: if a step needs to write it, it belongs to the scenario. A value set in before_scenario is a new object every time, so no scenario can see another's data.

Make test data unique and clean it up

Context layering protects your in-memory state. It does nothing for data created on the server. If two scenarios both create a user called alice, they collide in the API regardless of how tidy context is. Generate unique values per scenario:

import uuid

from behave import given


@given('a registered user with role "{role}"')
def step_registered_user(context, role):
    email = f"qa-{uuid.uuid4().hex[:10]}@example.test"
    user = context.api.create_user(email=email, role=role)
    context.user = user
    context.add_cleanup(context.api.delete_user, user["id"])

context.add_cleanup registers a function to run when the current layer is removed, so a cleanup registered during a scenario runs at the end of that scenario, even if a later step failed. That keeps the cleanup next to the creation, which makes it hard to forget. If your Behave version doesn't support it, record ids on context.created and delete them in after_scenario, which also runs when a scenario fails. For how far to take isolation, see how much test data isolation is actually enough.

Structure environment.py so scope is obvious

When environment.py grows, it becomes hard to tell what's shared and what isn't. A few conventions help the whole team, and any agent reading the file:

  • Keep hooks short. Move real work into helper functions in a support module.
  • Name run-level values so they read as shared and read-only, such as a config_ prefix, and freeze reference data where practical (a tuple or a MappingProxyType instead of a list or dict).
  • Initialise every scenario-level attribute in before_scenario, so a step that reads context.response before anything set it gets None rather than a leftover from another scenario.
  • Put a short comment at the top listing what lives at each level.

Rules for agent-written steps

An assistant writing step definitions sees one feature at a time. It doesn't know which attributes are run-level, so it will happily append to a shared list, or keep a module-level dictionary as a cache "for efficiency". Both pass when you run a single feature and leak when you run the suite.

I write the rules into the repository instructions the agent reads, .github/copilot-instructions.md for Copilot or your agent's equivalent:

## Behave shared data
- Run-level context attributes (set in before_all) are read-only. Never mutate them.
- Anything a step writes goes on context during the scenario, initialised in
  before_scenario. No module-level variables in step files.
- Server-side test data uses uuid-based names with the qa- prefix and registers
  cleanup with context.add_cleanup immediately after creation.
- Verify by running the full suite, not just the feature you changed.

The last rule matters. Bleed between scenarios only shows up when scenarios run together, so an agent that verifies its change on one feature file will report success. In review, I look for any step that writes to an attribute set in before_all, and any global or module-level mutable in a step file.

The same applies to data an agent generates. If you ask an AI assistant to produce realistic test records, keep them synthetic and check them into the repository as fixtures, rather than generating fresh ones on each run. Generated data that changes from run to run makes failures hard to reproduce. I cover the privacy side in generating test data with AI without leaking real data.

Shared, but owned

Safe data sharing in Behave comes down to ownership. Read-only things are shared at run level; everything mutable belongs to a scenario and cleans up with it; server data is unique and registered for cleanup the moment it's created. If you'd like to build a Behave suite with these habits from the first scenario, using VS Code and GitHub Copilot, my API testing courses walk through it.