Python Automation Frameworks: Behave and Pytest with AI Agents
In Python API testing, two frameworks cover almost everything I need: Behave for behaviour-driven scenarios written in Gherkin, and pytest for everything else. Underneath both sits the Requests library, doing the actual HTTP work. The tools themselves are well documented. What's harder to find is how to put them together into a framework that stays maintainable once it has hundreds of tests and several people, or several agents, adding to it.
That last part is new. GitHub Copilot, Claude Code, Cursor and similar coding agents now write a lot of step definitions, fixtures and parametrised tests. They're good at it when the framework has a clear shape, and they make a mess quickly when it doesn't. A framework today has two audiences: the people who maintain it, and the agents that imitate it.
This guide walks through how I structure a Python automation framework with Behave, pytest and Requests: what each piece is for, the shared layer that keeps them consistent, how fixtures and hooks work in each, and how I set the framework up so AI-written tests stay reviewable.
Smarter API Test Automation — Python, Behave, VS Code, AI with GitHub Copilot & CI/CD Pipelines. Complete in a Weekend!
What a framework is actually for
A test framework isn't the tool you install. It's the set of conventions that answers the same questions the same way every time: how a test gets configuration, how it authenticates, how it builds data, how it calls the API, where assertions go and how results are reported. When those answers are consistent, a new test is short and obvious. When they aren't, every test becomes its own small framework and maintenance cost grows with every file.
So I design the framework in layers: configuration, an API client, data builders, then the tests themselves, written in Behave or pytest. The test runner is the top layer, not the foundation.
Requests and a shared client layer
Requests is the foundation for HTTP. A requests.Session keeps headers and connection reuse in one place, and every call should set a timeout, because Requests has no default and a hung call will hang your CI job with it. I wrap it in a small client class that both Behave steps and pytest tests use:
import requests
class ApiClient:
def __init__(self, base_url, token, timeout=10):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {token}",
"Accept": "application/json",
})
def get(self, path, **kwargs):
return self.session.get(f"{self.base_url}{path}", timeout=self.timeout, **kwargs)
def post(self, path, json=None, **kwargs):
return self.session.post(f"{self.base_url}{path}", json=json, timeout=self.timeout, **kwargs)
The client returns the raw response and never asserts. That keeps negative tests easy and keeps every check visible in the test that makes it. Because Behave and pytest share this client, a change to auth or base URLs happens once.
Behave: scenarios people can read
Behave runs Gherkin feature files and maps each step to a Python function. Its value is a specification that non-engineers can read and approve. A typical layout is a features/ folder with .feature files, a features/steps/ folder for step definitions and a features/environment.py for hooks.
Feature: Order creation
Scenario: Rejecting an order with a negative quantity
Given I am an authenticated customer
When I create an order for SKU "BOOK-1" with quantity -1
Then the response status is 400
And the error points at the "quantity" field
Hooks in environment.py set up shared state on the context object. Values passed on the command line with -D base_url=... are available through context.config.userdata:
import os
from api_client import ApiClient
def before_all(context):
base_url = context.config.userdata.get("base_url", os.environ.get("API_BASE_URL"))
context.client = ApiClient(base_url, os.environ["API_TOKEN"])
Steps stay thin. They translate Gherkin into client calls and assertions, nothing more:
from behave import given, when, then
@given("I am an authenticated customer")
def step_authenticated(context):
assert context.client.session.headers.get("Authorization")
@when('I create an order for SKU "{sku}" with quantity {quantity:d}')
def step_create_order(context, sku, quantity):
context.response = context.client.post("/orders", json={"sku": sku, "quantity": quantity})
@then("the response status is {status:d}")
def step_status(context, status):
assert context.response.status_code == status, context.response.text
@then('the error points at the "{field}" field')
def step_error_field(context, field):
assert context.response.json()["error"]["field"] == field
The {quantity:d} syntax comes from Behave's default parse matcher and converts the value to an integer. Generic steps like the status check get reused across every feature; that reuse is what keeps a Behave suite from growing a new step for every sentence. For larger suites, see structuring a Behave project so it scales past 50 scenarios.
pytest: breadth, fixtures and parametrisation
pytest is where I put engineering-facing tests: edge cases, contract checks, negative paths. Fixtures in conftest.py provide the same client, with scope chosen on purpose:
import os
import pytest
from api_client import ApiClient
@pytest.fixture(scope="session")
def client():
return ApiClient(os.environ["API_BASE_URL"], os.environ["API_TOKEN"])
@pytest.mark.parametrize("quantity, expected_status", [
(-1, 400),
(0, 400),
("two", 400),
(None, 400),
])
def test_order_rejects_invalid_quantity(client, quantity, expected_status):
response = client.post("/orders", json={"sku": "BOOK-1", "quantity": quantity})
assert response.status_code == expected_status
assert response.json()["error"]["field"] == "quantity"
In a real suite the fixture lives in conftest.py and the test in its own module; they're together here for brevity. The expected statuses come from the API's documentation, not from running the request and copying the answer. Keeping conftest.py files small and close to the tests that use them is a discipline of its own, which I cover in writing pytest conftest files that don't become a mess.
Choosing between them, or using both
On most projects I use both in the same repository, sharing the client and data builders:
- Behave for acceptance behaviour that product owners, analysts or compliance reviewers will read or approve.
- pytest for heavily parametrised cases, contract and schema checks, and internal service behaviour nobody outside engineering needs to read.
If nobody outside engineering will ever open the feature files, Behave is an extra layer with no reader, and plain pytest is the better choice. I go through the decision in more depth in when to use BDD vs plain pytest for API tests.
Running both in CI
Both runners can produce JUnit XML, which almost every CI system can display: pytest --junitxml=reports/pytest.xml for pytest and behave --junit for Behave, which writes its XML files into a reports/ directory by default. Run the fast pytest checks and a tagged smoke subset of scenarios on every pull request, for example behave --tags=smoke, and the full suite on merge. Keeping one report format for both runners means failures from either framework land in the same place, with the same owner.
Setting the framework up for AI agents
When an agent writes tests, it copies what it sees. That makes the framework's conventions the most effective way to steer it, provided they're written down. Copilot reads .github/copilot-instructions.md, and other agents have an equivalent repository instructions file. Mine for a framework like this looks something like:
## Framework rules
- All HTTP goes through api_client.ApiClient. No raw requests calls in steps or tests.
- Scenarios in features/*.feature are owned by people. Do not edit a scenario to
make it pass; report the mismatch.
- Reuse existing steps before adding new ones. Steps stay thin: call, then assert.
- Edge cases and contract checks go in tests/ as parametrized pytest tests.
- Expected values come from openapi.yaml or the scenario, never from a live response.
- Never add retries, sleeps or skips to get a test passing.
The workflow that follows from it divides the work cleanly. People write or approve the Gherkin. The agent implements step definitions against it, which is mechanical work it does well, and the scenario defines what done means. The agent also generates pytest breadth, where a reviewer checks a parameter table rather than prose. Everything goes through a pull request with CI and a human approval.
When reviewing agent-written framework code, I look for a handful of recurring problems: a near-duplicate step that should have reused an existing one, a raw requests call that bypasses the client, a fixture that duplicates one in a parent conftest.py, and assertions that only check the status code. My quickest check is still to break the expected value and confirm the test goes red. I cover prompting for steps specifically in prompting an AI assistant to write Behave step definitions.
Frameworks for testing LLM features
The same structure extends to products that include a model. Keep model-calling tests in their own folder with a registered pytest marker, inject the model call as a fixture that takes a prompt and returns a string, and assert on properties you can verify (valid JSON, an allowed intent, no leaked email address) across several runs, reported as a pass rate against a threshold the team agrees. Run them on a schedule rather than on every pull request, and keep their results separate from the deterministic suite so a measurement isn't mistaken for a flaky test.
If you'd like to build this kind of framework end to end, my courses do exactly that with Python, Behave, VS Code and GitHub Copilot, and there's a Node and Cucumber version too.