AssertInbox

Selenium with Python: email verification tests

A Selenium test that signs up a user has to read the verification email, and the email never reaches the browser. This guide shows Selenium 4 with Python and pytest: a fixture gives every test its own address, explicit waits drive the page, and the standard library fetches the message from AssertInbox. The test types the one-time code first and then follows the magic_link in a second test.

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, with otp, magic_link and links already extracted. Messages are deleted after 24 hours. A unique tag per test is a private inbox, so parallel tests never read each other's mail.

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.

Install the test tools with pip install selenium pytest pytest-xdist. Selenium 4 downloads a matching browser driver itself through Selenium Manager, so no separate driver setup is needed for Chrome.

The fixtures

Put this in conftest.py. The inbox fixture creates a tag and removes its messages afterwards. The driver fixture starts a headless Chrome and closes it after the test.

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

import pytest
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, attempts=3, after=None):
        params = {"tag": self.tag, "timeout": 25}
        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}))


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


@pytest.fixture
def driver():
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")
    browser = webdriver.Chrome(options=options)
    yield browser
    browser.quit()

The tests

Save this as test_signup.py. Replace the URL, the field names and the success text with those of your app. Every interaction after a page change goes through WebDriverWait, so the test waits for the element it needs instead of sleeping.

import os
import re

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

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


def submit_signup(driver, email):
    driver.get(APP + "/signup")
    wait = WebDriverWait(driver, 15)
    wait.until(EC.visibility_of_element_located((By.NAME, "email"))).send_keys(email)
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()


def test_signup_with_code(driver, inbox):
    submit_signup(driver, inbox.email)

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

    wait = WebDriverWait(driver, 15)
    wait.until(EC.visibility_of_element_located((By.NAME, "code"))).send_keys(mail["otp"])
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
    wait.until(EC.text_to_be_present_in_element((By.TAG_NAME, "body"), "Email verified"))


def test_signup_with_magic_link(driver, inbox):
    submit_signup(driver, inbox.email)

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

    driver.get(mail["magic_link"])
    WebDriverWait(driver, 15).until(
        EC.text_to_be_present_in_element((By.TAG_NAME, "body"), "Email verified")
    )

Run pytest for one browser at a time or pytest -n 4 with pytest-xdist for four in parallel.

Explicit waits, not sleeps

Two different waits are involved and they should stay separate. The email wait is a server-side long poll: one HTTP call that returns as soon as the message arrives. The page waits are Selenium's explicit waits, which poll the DOM until a condition is true or the timeout passes. Avoid time.sleep and implicit waits for this flow; a fixed sleep is either too short on a slow day or wastes time on every run.

Parallel runs with pytest-xdist

With pytest -n 4, each worker process imports conftest.py and every test calls the inbox fixture, which builds a tag from the time and a random suffix. Two workers therefore never wait on the same address. The namespace stays the same for all of them because it belongs to your key. If your app rate-limits sign-ups per source, set a lower worker count rather than reusing addresses.

When the app sends a second email

A "resend code" button sends a new message to the same address. /v1/wait returns the newest message for the tag, which could be the old one. Pass the id of the message you already read as after and the call returns only a newer message:

def test_resend_code(driver, inbox):
    submit_signup(driver, inbox.email)
    first = inbox.wait_for_email()

    WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.ID, "resend"))
    ).click()
    second = inbox.wait_for_email(after=first["id"])

    assert second["id"] != first["id"]
    assert second["otp"]

Troubleshooting

Related guides: pytest and Playwright for Python, Playwright (Node), Cypress. The Python client file can replace the helper class above.