Test FastAPI email verification with pytest
FastAPI apps usually send verification email from a background task, which makes the flow easy to get subtly wrong: the task never runs, the code in the message differs from the stored one, or the link points at the wrong host. This guide tests the real thing. It uses pytest and requests against a running FastAPI server, signs up through the API, waits for the email with the standard-library AssertInbox client file, then posts the one-time code and follows the link, and asserts the account state after each step.
The app under test
Save this as app.py. Users are kept in memory to stay short. The app sends mail with the standard library's smtplib from a background task, with settings from environment variables. Install fastapi and uvicorn and run it with uvicorn app:app --port 8000.
import os
import secrets
import smtplib
from email.message import EmailMessage
from fastapi import BackgroundTasks, FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8000")
users = {}
class SignUp(BaseModel):
email: str
class Confirm(BaseModel):
email: str
code: str
def send_verification(email, code, token):
message = EmailMessage()
message["From"] = os.environ["MAIL_FROM"]
message["To"] = email
message["Subject"] = "Your verification code"
link = BASE_URL + "/verify?token=" + token
message.set_content("Your verification code is " + code + ". Or open " + link)
with smtplib.SMTP(os.environ["SMTP_HOST"], int(os.environ.get("SMTP_PORT", "587"))) as smtp:
smtp.starttls()
smtp.login(os.environ["SMTP_USER"], os.environ["SMTP_PASS"])
smtp.send_message(message)
@app.post("/signup", status_code=202)
def signup(body: SignUp, tasks: BackgroundTasks):
email = body.email.lower()
code = "".join(secrets.choice("0123456789") for _ in range(6))
token = secrets.token_urlsafe(16)
users[email] = {"code": code, "token": token, "verified": False}
tasks.add_task(send_verification, email, code, token)
return {"ok": True}
@app.post("/confirm")
def confirm(body: Confirm):
user = users.get(body.email.lower())
if not user or user["code"] != body.code:
raise HTTPException(status_code=400, detail="invalid_code")
user["verified"] = True
return {"verified": True}
@app.get("/verify")
def verify(token: str):
for user in users.values():
if user["token"] == token:
user["verified"] = True
return {"verified": True}
raise HTTPException(status_code=400, detail="invalid_token")
@app.get("/users/{email}")
def get_user(email: str):
user = users.get(email.lower())
if not user:
raise HTTPException(status_code=404, detail="not_found")
return {"verified": user["verified"]}
The /users/{email} route is there only so the test can read the state back. Use a transactional mail service you control for the SMTP settings.
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, links and magic_link. Messages are deleted after 24 hours.
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 CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is 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 listed in the limits page.
The client file
The Python client file uses only the standard library. Download it next to your tests:
mkdir -p tests
curl -o tests/assertinbox.py https://assertinbox.com/sdk/assertinbox.py
pip install pytest requests
AssertInbox(KEY, NAMESPACE) gives you address(tag), unique_tag(prefix), wait(tag, subject=..., after=..., retries=...), wait_for_otp, wait_for_link and delete(tag). It raises AssertInboxError with the API's error code when something fails.
The tests
Save this as tests/test_signup.py. Set APP_URL to the running app. The tag is unique per test, so tests can run in parallel with pytest-xdist. The OTP test and the link test each sign up a fresh address.
import os
import pytest
import requests
from assertinbox import AssertInbox
APP = os.environ.get("APP_URL", "http://localhost:8000")
client = AssertInbox(os.environ["ASSERTINBOX_KEY"], os.environ["ASSERTINBOX_NAMESPACE"])
@pytest.fixture
def inbox():
tag = client.unique_tag("fastapi")
yield tag, client.address(tag)
client.delete(tag)
def sign_up(email):
res = requests.post(APP + "/signup", json={"email": email}, timeout=10)
assert res.status_code == 202
def verified(email):
res = requests.get(APP + "/users/" + email, timeout=10)
assert res.status_code == 200
return res.json()["verified"]
def test_code_verifies_the_account(inbox):
tag, email = inbox
sign_up(email)
mail = client.wait(tag, subject="verification", retries=2)
assert mail["otp"] and len(mail["otp"]) == 6
assert verified(email) is False
res = requests.post(APP + "/confirm", json={"email": email, "code": mail["otp"]}, timeout=10)
assert res.status_code == 200
assert verified(email) is True
def test_wrong_code_is_rejected(inbox):
tag, email = inbox
sign_up(email)
mail = client.wait(tag, subject="verification", retries=2)
wrong = "000000" if mail["otp"] != "000000" else "111111"
res = requests.post(APP + "/confirm", json={"email": email, "code": wrong}, timeout=10)
assert res.status_code == 400
assert verified(email) is False
def test_link_verifies_the_account(inbox):
tag, email = inbox
sign_up(email)
link = client.wait_for_link(tag, subject="verification", retries=2)
assert link.startswith(APP)
res = requests.get(link, timeout=10)
assert res.status_code == 200
assert verified(email) is True
Run it with APP_URL=http://localhost:8000 pytest tests/test_signup.py. The link.startswith(APP) assertion catches a BASE_URL that still holds its default value in the environment that sends the mail.
Background tasks and timing
FastAPI runs a background task after the response is sent, so the 202 returns before any mail leaves. That is why the test waits instead of asserting right after the sign-up: wait long-polls and returns as soon as the message arrives. If you reuse one address for several steps, for example a resent code, pass after with the id of the previous message so that the wait cannot return the old one.
Troubleshooting
- The wait raises a timeout error. A failure inside a background task does not reach the client. Check the server log for an SMTP exception, and confirm that
MAIL_FROMis a sender your provider accepts. - The code has no
otp. The extractor looks for a standalone 4 to 8 digit code. Printmail["subject"]and the message text to see what the app sent. KeyErroronSMTP_HOST. The server process does not see your environment. Export the variables in the shell that startsuvicorn.- HTTP 429. The key used its 2,000 requests for the day.
Retry-Aftergives the seconds until 00:00 UTC.
Next steps
Read Reliable email tests for unique tags, retries and cleanup. Related guides: pytest with Playwright and Django allauth. The wait filters are described in the docs.
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.