AssertInbox

pytest and Playwright for Python: email verification tests

When a sign-up sends a verification email, a Python end-to-end test needs to read it. This guide gives you a pytest fixture that yields a fresh email address and a function that waits for the message, using only the standard library (urllib.request) for the API calls. The browser part uses the pytest-playwright plugin, but the fixture works the same with Selenium.

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 message as JSON with otp, magic_link and links extracted. 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.

Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE in your environment. Install the test tools with pip install pytest pytest-playwright and playwright install chromium.

The fixture

Put this in conftest.py. Each test gets its own tag, so tests under pytest-xdist never read each other's mail. The fixture deletes the tag's messages afterwards.

import json
import os
import secrets
import time
import urllib.error
import urllib.parse
import urllib.request

import pytest

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, attempts=3):
        query = urllib.parse.urlencode({"tag": self.tag, "timeout": 25})
        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}))


@pytest.fixture
def inbox():
    if not KEY or not NAMESPACE:
        pytest.skip("ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE are not set")
    tag = ("py-%d-%s" % (int(time.time()), secrets.token_hex(3))).lower()
    box = Inbox(tag)
    yield box
    box.clear()

The tests

Save this as test_signup.py. The first test enters the one-time code; the second follows the magic link. Adjust the URL and selectors to your app.

import os
import re

APP = os.environ.get("APP_URL", "http://localhost:3000")


def test_signup_with_code(page, inbox):
    page.goto(APP + "/signup")
    page.fill("input[name=email]", inbox.email)
    page.click("button[type=submit]")

    mail = inbox.wait_for_email()
    assert re.fullmatch(r"[0-9]{4,8}", mail["otp"] or ""), mail["subject"]

    page.fill("input[name=code]", mail["otp"])
    page.click("button[type=submit]")
    assert page.get_by_text("Email verified").is_visible()


def test_signup_with_magic_link(page, inbox):
    page.goto(APP + "/signup")
    page.fill("input[name=email]", inbox.email)
    page.click("button[type=submit]")

    mail = inbox.wait_for_email()
    assert mail["magic_link"], "no verification link in the email"

    page.goto(mail["magic_link"])
    assert page.get_by_text("Email verified").is_visible()

Run it with pytest -n 4 if you have pytest-xdist installed, or plain pytest.

When the app sends a second email

A "resend code" button sends another message to the same address, and /v1/wait returns the newest one for the tag, which may still be the first. Pass the id of the message you already read as after and the call returns only a newer one. The tag and the id are safe to put in a query string as they are, because tags contain only letters, digits, dots, dashes and underscores. This test file reuses the fixture and the _call helper from conftest.py:

import re

from conftest import _call


def wait_after(inbox, first_id, attempts=3):
    query = "tag=%s&timeout=25&after=%s" % (inbox.tag, first_id)
    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 newer email arrived for tag " + inbox.tag)


def test_resend_sends_a_new_code(page, inbox):
    page.goto("http://localhost:3000/signup")
    page.fill("input[name=email]", inbox.email)
    page.click("button[type=submit]")

    first = inbox.wait_for_email()
    page.click("#resend")
    second = wait_after(inbox, first["id"])

    assert second["id"] != first["id"]
    assert re.fullmatch(r"[0-9]{4,8}", second["otp"] or "")

The from and subject filters can be added to the same query when your app sends several kinds of email to one address.

Client files instead of a helper

If you would rather not keep your own helper, the client files for JavaScript and Python do the same job: they build addresses, wait with retries on 408, and accept the from, subject and after filters. They are single files you download with curl. The daily allowance, the retention period and every error code are listed on the limits page.

Selenium instead of Playwright

The inbox fixture does not depend on the browser. Replace the page calls with your Selenium driver and keep inbox.email and inbox.wait_for_email() as they are.

Troubleshooting

Related guides: Playwright (Node), Cypress.