BDD email verification tests with Behave
Behave is a behaviour-driven development tool for Python: you describe behaviour in plain sentences in a .feature file, and Python step functions make each sentence run. Email verification suits this style, because the scenario reads like what a user does: sign up, receive an email, enter the code, and see the welcome page. This guide builds such a scenario. It uses a unique AssertInbox address for every scenario, Selenium for the browser, and only the Python standard library for the email calls. It targets Behave 1.2 and newer and Python 3.9 or newer.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, including id, subject, otp and magic_link, or 408 if nothing arrived. Messages are deleted after 24 hours. The tag is the isolation boundary: every test builds its own tag, so tests never read each other's mail. In Behave, a fresh inbox is created in a hook before each scenario, and the steps share it through the context object.
Get an API key
Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your secret manager or CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page.
Project layout
Behave expects a features folder with the feature files, a steps folder for step definitions and an environment.py for hooks:
features/
signup.feature
environment.py
steps/
signup_steps.py
The feature file
Save this as features/signup.feature. The wording is yours to adapt; what matters is that the steps are specific enough to implement. The second scenario covers the resend button and relies on the after filter described below.
Feature: Email verification at sign-up
Scenario: A new user verifies the address with the emailed code
Given a new visitor with a fresh test inbox
When they sign up with that address
And they enter the code from the verification email
Then they see the welcome page
Scenario: A new user asks for a second code
Given a new visitor with a fresh test inbox
When they sign up with that address
And they ask for a new code
And they enter the code from the newest verification email
Then they see the welcome page
Hooks and the email client
Save this as features/environment.py. It starts a headless browser for the whole run, creates a unique inbox before each scenario and deletes its messages afterwards. The client uses only urllib, so there is nothing to install for it.
import json
import os
import secrets
import time
import urllib.error
import urllib.parse
import urllib.request
from selenium import webdriver
API = "https://assertinbox.com"
KEY = os.environ.get("ASSERTINBOX_KEY", "")
NAMESPACE = os.environ.get("ASSERTINBOX_NAMESPACE", "")
def _call(method, path):
request = urllib.request.Request(
API + path, method=method, headers={"Authorization": "Bearer " + KEY}
)
try:
with urllib.request.urlopen(request, timeout=35) as response:
return response.status, json.loads(response.read() or b"{}")
except urllib.error.HTTPError as error:
return error.code, {}
class Inbox:
def __init__(self, tag):
self.tag = tag
self.email = NAMESPACE + "." + tag + "@assertinbox.com"
def wait_for_email(self, subject=None, after=None, attempts=3):
params = {"tag": self.tag, "timeout": 25}
if subject:
params["subject"] = subject
if after:
params["after"] = after
query = urllib.parse.urlencode(params)
for _ in range(attempts):
status, body = _call("GET", "/v1/wait?" + query)
if status == 200:
return body
if status != 408:
raise RuntimeError("AssertInbox returned HTTP %d" % status)
raise TimeoutError("No email arrived for tag " + self.tag)
def clear(self):
_call("DELETE", "/v1/messages?" + urllib.parse.urlencode({"tag": self.tag}))
def before_all(context):
if not KEY or not NAMESPACE:
raise RuntimeError("Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE")
context.app = os.environ.get("APP_URL", "http://localhost:3000")
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
context.browser = webdriver.Chrome(options=options)
def before_scenario(context, scenario):
tag = ("behave-%d-%s" % (int(time.time()), secrets.token_hex(3))).lower()
context.inbox = Inbox(tag)
context.last_mail = None
def after_scenario(context, scenario):
context.inbox.clear()
def after_all(context):
context.browser.quit()
The step definitions
Save this as features/steps/signup_steps.py. Each step does one thing. The browser steps use Selenium's explicit waits, not fixed sleeps. Replace the locators and texts with those of your app.
import re
from behave import given, then, when
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
def wait(context):
return WebDriverWait(context.browser, 15)
@given("a new visitor with a fresh test inbox")
def step_fresh_inbox(context):
assert context.inbox.email.endswith("@assertinbox.com")
@when("they sign up with that address")
def step_sign_up(context):
context.browser.get(context.app + "/signup")
wait(context).until(EC.visibility_of_element_located((By.NAME, "email"))).send_keys(context.inbox.email)
context.browser.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
wait(context).until(EC.visibility_of_element_located((By.NAME, "code")))
@when("they ask for a new code")
def step_resend(context):
context.last_mail = context.inbox.wait_for_email(subject="verify")
wait(context).until(EC.element_to_be_clickable((By.ID, "resend"))).click()
@when("they enter the code from the verification email")
def step_enter_code(context):
mail = context.inbox.wait_for_email(subject="verify")
assert re.fullmatch(r"[0-9]{4,8}", mail["otp"] or ""), mail["subject"]
context.browser.find_element(By.NAME, "code").send_keys(mail["otp"])
context.browser.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
@when("they enter the code from the newest verification email")
def step_enter_newest_code(context):
mail = context.inbox.wait_for_email(subject="verify", after=context.last_mail["id"])
assert mail["id"] != context.last_mail["id"]
context.browser.find_element(By.NAME, "code").send_keys(mail["otp"])
context.browser.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
@then("they see the welcome page")
def step_welcome(context):
wait(context).until(EC.text_to_be_present_in_element((By.TAG_NAME, "h1"), "Welcome"))
Run the suite with behave from the project root. To run one scenario, use behave -n "A new user asks for a second code".
Why steps keep the email in the context
The resend scenario needs the first message's id when it waits for the second. Storing the message on context.last_mail is the Behave way to pass data between steps. The after filter makes the wait ignore everything up to and including that message, so the scenario cannot accidentally enter the old code.
Running in CI
- Set
ASSERTINBOX_KEYas a secret andASSERTINBOX_NAMESPACEas an ordinary variable. Never print them. - Behave runs scenarios one after another in one process. If you split features across CI jobs, the per-scenario tags keep jobs apart.
- Messages are deleted in
after_scenario, and by the service after 24 hours.
Troubleshooting
- "Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE". The variables are not set in the shell that runs Behave.
- Undefined step. A sentence in the feature file has no matching step. Behave prints a snippet you can paste into the steps file.
- The wait times out. Check the app's mail log. Remove the
subjectfilter to see whether any message arrives. - HTTP 429. The daily allowance is 2,000 requests per key.
Retry-Aftergives the seconds until 00:00 UTC.
Next steps
Read Reliable email tests for unique tags, retries and cleanup. Related guides: Selenium with Python pytest with Playwright and Cucumber.js. The wait filters are described in the docs, and the client files wrap the helper for Node.js and Python.
Free beta, run by AI agents
This service is in free beta and is operated by AI agents under human supervision. Messages are deleted after 24 hours.