Python API-only sign-up email test with pytest
If your app has a sign-up endpoint, you can test its verification email from Python without driving a browser. The test calls the endpoint, waits for the email through AssertInbox, reads the code, posts it back and asserts that the account is verified. It runs in a second or two, so it works well as a fast check before the slower browser tests. This guide uses pytest and the Python standard library only: urllib.request for the calls to your app and the single-file AssertInbox client for the inbox. It targets Python 3.9 or newer and pytest 7 or newer.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls 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: each test builds its own tag, so tests never read each other's mail, even with several pytest workers.
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 keep 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.
Install the client
The client is one file with no dependencies. Download it next to your tests and install pytest:
pip install pytest
curl -o tests/assertinbox.py https://assertinbox.com/sdk/assertinbox.py
Its methods used here are unique_tag(), address(tag), wait(), wait_for_otp(), wait_for_link() and delete(tag). The client page lists all of them.
Try it first against the practice app
The practice app lets you see a green test before you touch your own application. POST https://assertinbox.com/practice/api/signup with {"email": "<address>"} returns 201 and emails a six-digit code and a confirmation link to that address and nowhere else. POST /practice/api/verify with the email and the code returns {"verified": true}. Set APP_URL=https://assertinbox.com/practice/api and the test below runs unchanged. Against your own app, change the two paths and the request bodies.
The fixture and the helper
Save this as tests/conftest.py. The inbox fixture gives each test its own tag and address and deletes that tag's messages afterwards, even when the test failed. post_json is a small wrapper over urllib.request that returns the status and the decoded body instead of raising on 4xx responses, which makes assertions on error cases simple. It also sets a User-Agent header: the default one that urllib sends (Python-urllib/3.x) is refused by the network in front of assertinbox.com with HTTP 403 and the text error code: 1010, which matters because the practice app lives on that domain. The AssertInbox client file sets its own.
import json
import os
import urllib.error
import urllib.request
from types import SimpleNamespace
import pytest
from assertinbox import AssertInbox
APP_URL = os.environ.get("APP_URL", "http://localhost:3000/api")
@pytest.fixture(scope="session")
def client():
return AssertInbox(os.environ["ASSERTINBOX_KEY"], namespace=os.environ["ASSERTINBOX_NAMESPACE"])
@pytest.fixture
def inbox(client):
tag = client.unique_tag("py")
yield SimpleNamespace(tag=tag, email=client.address(tag), client=client)
try:
client.delete(tag)
except Exception:
pass
@pytest.fixture
def post_json():
def post(path, body):
request = urllib.request.Request(
APP_URL + path,
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "User-Agent": "assertinbox-test/1.0"},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=30) as res:
status, raw = res.status, res.read()
except urllib.error.HTTPError as e:
status, raw = e.code, e.read()
try:
return status, json.loads(raw or b"{}")
except ValueError:
return status, {}
return post
The test file
Save this as tests/test_signup_email.py and run it with pytest. Each test asks the app to send an email to the address from its own fixture, waits for it with up to two retries of the 20-second wait, and asserts on what arrived.
from urllib.parse import urlparse
from conftest import APP_URL
PASSWORD = "correct-Horse-battery-1"
def test_signup_email_code_verifies_the_address(inbox, post_json):
status, _ = post_json("/signup", {"email": inbox.email, "password": PASSWORD})
assert status < 300
code = inbox.client.wait_for_otp(inbox.tag, retries=2)
assert len(code) == 6 and code.isdigit()
status, body = post_json("/verify", {"email": inbox.email, "code": code})
assert status == 200
assert body.get("verified") is True
def test_confirmation_link_points_at_our_host_over_https(inbox, post_json):
post_json("/signup", {"email": inbox.email, "password": PASSWORD})
link = urlparse(inbox.client.wait_for_link(inbox.tag, retries=2))
assert link.scheme == "https"
assert link.netloc == urlparse(APP_URL).netloc
def test_wrong_code_is_rejected(inbox, post_json):
post_json("/signup", {"email": inbox.email, "password": PASSWORD})
mail = inbox.client.wait(inbox.tag, retries=2)
wrong = "111111" if mail["otp"] == "000000" else "000000"
status, _ = post_json("/verify", {"email": inbox.email, "code": wrong})
assert status >= 400
requests instead of urllib
Many Python projects already depend on requests, and it is a fine choice for the calls to your own app. Replace the body of post with res = requests.post(APP_URL + path, json=body, timeout=30) and return res.status_code, res.json(). The AssertInbox client does not need it: the client file keeps working with the standard library alone, so the only reason to add requests is that your app calls are easier to read with it.
Waiting and timeouts
A single wait call returns as soon as the email arrives, or after 20 seconds with a 408. The retries=2 argument repeats the wait after a timeout, so a slow mail provider has up to a minute before the test fails, and a healthy run is not slower for it. pytest has no default per-test time limit, so a stuck run is bounded by those retries. If you want a hard limit anyway, the pytest-timeout plugin adds one.
Two emails from one action
When one action sends two emails, such as a welcome email and a verification email, wait for the first, then pass its id as after to wait for the second: second = inbox.client.wait(inbox.tag, after=first["id"]). This stops the second wait from returning the first message again. Filter by subject instead when the order is not fixed.
Parallel runs
With pytest-xdist the tests run in several processes. Because every test gets a tag from the clock and a random part, two workers never share an inbox. Do not create one tag at module level and reuse it across tests: the first email to arrive would satisfy every wait.
Run it in CI
Store ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE as secrets in your CI provider and pass them as environment variables to the step that runs pytest. Set APP_URL to the deployed or locally started app. Never print the key. The key allows 2,000 requests a day; each test uses a handful.
Troubleshooting
ModuleNotFoundError: assertinbox. The client file is not next toconftest.py, or the tests directory is not on the path. Keep both intests/.KeyError: ASSERTINBOX_KEY. The environment variable is not set in the shell or CI step that runs pytest.- HTTP 401. The key is wrong or revoked.
- No email arrives. Print
inbox.emailand compare it with your app's logs. Some apps lowercase or normalise addresses; the tags here are lowercase. - HTTP 429. The key used its requests for the day.
Retry-Aftergives the seconds until 00:00 UTC.
Related guides: FastAPI email verification, the same test in Node.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.