Test Django allauth email verification with pytest
django-allauth sends a confirmation email when a user signs up, and with mandatory verification the user cannot log in until the link in that email has been used. Django's own test outbox hides all of that behind mail.outbox. This guide tests the real thing instead: a running server that really sends mail, and a pytest test that signs up with requests, reads the confirmation link from an AssertInbox address, confirms the address and logs in. The test needs no browser and no Django test client.
When to test against a real server
The Django test client with mail.outbox is fast and right for unit tests. It cannot tell you whether your SMTP settings work, whether the link has the right host, or whether a real mail provider delivers the message. A test against a running server, in a staging or CI environment with real outgoing mail, covers those. Use both: the outbox for logic, a few real-mail tests for the whole path.
What your project needs
The project uses django-allauth with ACCOUNT_EMAIL_VERIFICATION = "mandatory" and a working EMAIL_BACKEND that sends to a real SMTP server. Sign-up is by email and password; if your project also asks for a username, add it to the form data in the test. The link in the email is built from the Site domain (or the request host, depending on your allauth version and settings), so set it to the address the tests use. The names of the settings and the sign-up form fields differ between allauth versions; check the allauth documentation for yours.
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, 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. Also set APP_URL to the server under test, for example http://localhost:8000. 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 fixture
Install the test tools with pip install pytest requests. Put this in conftest.py. Each test gets its own tag, so parallel tests never read each other's mail, and the fixture deletes the messages afterwards. The test is skipped when the key is not set.
import json
import os
import secrets
import time
import urllib.parse
import pytest
import requests
API = "https://assertinbox.com"
KEY = os.environ.get("ASSERTINBOX_KEY", "")
NAMESPACE = os.environ.get("ASSERTINBOX_NAMESPACE", "")
APP = os.environ.get("APP_URL", "http://localhost:8000")
class Inbox:
def __init__(self, tag):
self.tag = tag
self.email = NAMESPACE + "." + tag + "@assertinbox.com"
self.headers = {"Authorization": "Bearer " + KEY}
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
for _ in range(attempts):
res = requests.get(API + "/v1/wait", params=params, headers=self.headers, timeout=40)
if res.status_code == 200:
return res.json()
if res.status_code != 408:
raise RuntimeError("AssertInbox returned HTTP %d" % res.status_code)
raise TimeoutError("No email arrived for tag " + self.tag)
def clear(self):
requests.delete(API + "/v1/messages", params={"tag": self.tag}, headers=self.headers, timeout=40)
@pytest.fixture
def inbox():
if not KEY or not NAMESPACE:
pytest.skip("ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE are not set")
box = Inbox(("dj-%d-%s" % (int(time.time()), secrets.token_hex(3))).lower())
yield box
box.clear()
The tests
Save this as test_allauth_email.py. allauth forms are protected by Django's CSRF check, so every POST first fetches the form to get the token and sends a Referer header. The field names (email, password1, password2, login, password) are the allauth defaults; change them if your forms differ.
import re
from urllib.parse import urlparse
import requests
from conftest import APP
PASSWORD = "correct-horse-battery-9"
def csrf_token(session, url):
page = session.get(url, timeout=30)
match = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', page.text)
assert match, "no CSRF token on " + url
return match.group(1)
def post_form(session, url, data):
data = dict(data, csrfmiddlewaretoken=csrf_token(session, url))
return session.post(url, data=data, headers={"Referer": url}, timeout=30)
def sign_up(session, email):
return post_form(
session,
APP + "/accounts/signup/",
{"email": email, "password1": PASSWORD, "password2": PASSWORD},
)
def log_in(session, email):
return post_form(session, APP + "/accounts/login/", {"login": email, "password": PASSWORD})
def test_confirmation_link_verifies_the_address(inbox):
session = requests.Session()
sign_up(session, inbox.email)
mail = inbox.wait_for_email(subject="confirm")
link = mail["magic_link"]
assert link, "no confirmation link in the email"
assert urlparse(link).netloc == urlparse(APP).netloc, link
# allauth shows a confirmation page first; the POST completes it.
confirm = post_form(session, link, {})
assert confirm.status_code == 200
session = requests.Session()
result = log_in(session, inbox.email)
assert "/accounts/confirm-email" not in result.url
assert inbox.email in session.get(APP + "/accounts/email/", timeout=30).text
def test_login_is_refused_before_confirmation(inbox):
session = requests.Session()
sign_up(session, inbox.email)
inbox.wait_for_email(subject="confirm")
result = log_in(session, inbox.email)
assert "/accounts/confirm-email" in result.url
The first test is the happy path: it signs up, waits for the email whose subject contains confirm, and asserts that the link is on the same host as the app. By default allauth shows a page with a confirm button when the link is opened, so the test sends a POST to the link; if your project sets ACCOUNT_CONFIRM_EMAIL_ON_GET = True, a plain GET confirms instead. It then logs in with a fresh session and checks that the address is listed on the account's email page. The second test asserts the other side of mandatory verification: before the link is used, login leads back to the confirmation step.
Using the client file instead of requests
If you prefer no extra dependency, the Python client file does the same job with only the standard library. Download it with curl -O https://assertinbox.com/sdk/assertinbox.py and replace the Inbox class with calls like client.wait(tag, subject="confirm", retries=2), with client = AssertInbox(KEY, NAMESPACE) and client.address(tag) for the address. It raises AssertInboxError with the API's error code when something fails.
Cooldowns and several emails
allauth limits how often it resends a confirmation email to the same address, and the default cooldown is measured in minutes. A test that triggers a second email to the same address may therefore get none. Use a new tag for every test, as the fixture does, and avoid resend tests unless you lower the cooldown in your test settings. When one address does receive several emails in a row, pass the id of the one you already read as after, so the wait returns only a newer message.
Troubleshooting
- TimeoutError. The server did not send the email. Check
EMAIL_BACKEND: the console and file backends send nothing. Printinbox.emailand compare it with the address in the server log. - The link host is wrong. The link was built from the
Siterecord or the request host. Fix the domain of the site in the Django admin or the proxy headers. - No CSRF token found. The form URL is different in your project, or a login wall redirected the request. Print
page.urland the status code. - The second test does not stay on the confirmation step. Your project may not use mandatory verification. Set it to
"mandatory"for the test environment. - HTTP 429 from AssertInbox. 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 and Playwright email tests, Selenium with Python and password reset tests. 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.