AssertInbox

pytest sign-up with an emailed code: a runnable example, no browser

This is a small pytest project you can download and run in a minute, with no browser and no web driver. It signs up on the AssertInbox practice app over HTTP using only the Python standard library, waits for the real email that the practice app sends, reads the six-digit code from it through the AssertInbox API and submits the code. The second test submits a wrong code and checks it is refused. Nothing is mocked, and all you need is a key because the practice app is hosted for you.

The only dependency is pytest. The AssertInbox client (assertinbox.py) and the pytest plugin (pytest_assertinbox.py) are single files with no dependencies of their own. The plugin gives every test an inbox fixture, so this shape also suits API-level tests of your own sign-up endpoint.

Get a key

You need an AssertInbox key and its namespace. Get a key in one click: no email address or card is needed. The key is shown once, so keep it. Then export ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE (the namespace is shown with the key).

Download

Run these lines in an empty folder. They fetch every file below, each served as it is in the repository.

curl --create-dirs -fsSo requirements.txt https://assertinbox.com/examples/pytest-signup-otp/requirements.txt
curl --create-dirs -fsSo conftest.py https://assertinbox.com/examples/pytest-signup-otp/conftest.py
curl --create-dirs -fsSo test_signup.py https://assertinbox.com/examples/pytest-signup-otp/test_signup.py
curl --create-dirs -fsSo assertinbox.py https://assertinbox.com/examples/pytest-signup-otp/assertinbox.py
curl --create-dirs -fsSo pytest_assertinbox.py https://assertinbox.com/examples/pytest-signup-otp/pytest_assertinbox.py
curl --create-dirs -fsSo .github/workflows/e2e.yml https://assertinbox.com/examples/pytest-signup-otp/ci/github-actions.yml
curl --create-dirs -fsSo README.md https://assertinbox.com/examples/pytest-signup-otp/README.md

Run it

pip install -r requirements.txt
export ASSERTINBOX_KEY=ai_...
export ASSERTINBOX_NAMESPACE=yournamespace
pytest -v

By default the tests use the practice app at https://assertinbox.com/practice. Set PRACTICE_URL to point at another copy. Without ASSERTINBOX_KEY the fixture raises an error that says where to get one.

The files

requirements.txt

pytest>=8,<10

conftest.py

import os

import pytest

# Adds the "inbox" fixture: a fresh address for every test, cleaned up afterwards.
pytest_plugins = ["pytest_assertinbox"]


@pytest.fixture(scope="session")
def practice_url():
    # The practice app is a fake product that emails a code and a link to AssertInbox addresses.
    return os.environ.get("PRACTICE_URL", "https://assertinbox.com/practice").rstrip("/")

test_signup.py

import json
import urllib.error
import urllib.request


def post(url, body):
    # urllib's default User-Agent is refused by the network in front of the service, so send our own.
    request = urllib.request.Request(
        url,
        data=json.dumps(body).encode(),
        headers={"content-type": "application/json", "User-Agent": "assertinbox-example/1.0"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return response.status, json.loads(response.read() or b"{}")
    except urllib.error.HTTPError as error:
        return error.code, json.loads(error.read() or b"{}")


def test_sign_up_and_verify_with_the_emailed_code(inbox, practice_url):
    email = inbox.address("code")

    status, _ = post(practice_url + "/api/signup", {"email": email})
    assert status == 201

    code = inbox.wait_for_otp()
    status, body = post(practice_url + "/api/verify", {"email": email, "code": code})
    assert status == 200
    assert body["verified"] is True


def test_a_wrong_code_is_refused(inbox, practice_url):
    email = inbox.address("wrong")
    status, _ = post(practice_url + "/api/signup", {"email": email})
    assert status == 201

    real = inbox.wait_for_otp()
    wrong = "000000" if real != "000000" else "111111"
    status, body = post(practice_url + "/api/verify", {"email": email, "code": wrong})
    assert status >= 400
    assert body.get("verified") is not True

assertinbox.py

The AssertInbox client, identical to /sdk/assertinbox.py.

"""AssertInbox client. MIT License. Copyright (c) AssertInbox. Python standard library only."""
import json
import random
import string
import time
import urllib.error
import urllib.parse
import urllib.request


class AssertInboxError(Exception):
    def __init__(self, code, message=None, status=None):
        super().__init__(message or code)
        self.code = code
        self.status = status


class AssertInbox:
    def __init__(self, key, namespace=None, base_url="https://assertinbox.com", domain=None):
        if not key:
            raise ValueError("key is required")
        self.key = key
        self.namespace = namespace
        self.base_url = base_url.rstrip("/")
        self.domain = domain

    def address(self, tag):
        if not self.namespace:
            raise ValueError("namespace is required to build an address")
        host = self.domain or urllib.parse.urlparse(self.base_url).hostname
        if host.startswith("www."):
            host = host[4:]
        return "%s.%s@%s" % (self.namespace, str(tag).lower(), host)

    def unique_tag(self, prefix="t"):
        rnd = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
        return ("%s-%s-%s" % (prefix, format(int(time.time() * 1000), "x"), rnd)).lower()

    def _request(self, path, params=None, method="GET"):
        query = urllib.parse.urlencode({k: v for k, v in (params or {}).items() if v not in (None, "")})
        url = self.base_url + path + ("?" + query if query else "")
        req = urllib.request.Request(url, method=method, headers={"Authorization": "Bearer " + self.key, "User-Agent": "assertinbox-python/1.0"})
        try:
            with urllib.request.urlopen(req, timeout=40) as res:
                return json.loads(res.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            try:
                body = json.loads(e.read().decode("utf-8"))
            except ValueError:
                body = {}
            raise AssertInboxError(body.get("error") or "http_%d" % e.code, body.get("message"), e.code) from None

    def wait(self, tag, timeout=20, from_=None, subject=None, after=None, since=None, retries=0):
        """Newest matching message. A 408 timeout is retried up to `retries` more times."""
        attempt = 0
        while True:
            try:
                return self._request("/v1/wait", {"tag": tag, "timeout": timeout, "from": from_, "subject": subject, "after": after, "since": since})
            except AssertInboxError as e:
                if e.code != "timeout" or attempt >= retries:
                    raise
                attempt += 1

    def wait_for_otp(self, tag, **options):
        """Like wait(), but returns just the code. Raises ValueError, naming the subject, when there is none."""
        message = self.wait(tag, **options)
        if not message.get("otp"):
            raise ValueError('No code found in the email with subject "%s"' % message.get("subject"))
        return message["otp"]

    def wait_for_link(self, tag, **options):
        """Like wait(), but returns just the magic link. Raises ValueError, naming the subject, when there is none."""
        message = self.wait(tag, **options)
        if not message.get("magic_link"):
            raise ValueError('No link found in the email with subject "%s"' % message.get("subject"))
        return message["magic_link"]

    def list(self, tag=None, since=None, from_=None, subject=None, after=None):
        return self._request("/v1/messages", {"tag": tag, "since": since, "from": from_, "subject": subject, "after": after})["messages"]

    def delete(self, tag=None):
        return self._request("/v1/messages", {"tag": tag}, "DELETE")

    def me(self):
        return self._request("/v1/me")

pytest_assertinbox.py

The pytest plugin, identical to /sdk/pytest_assertinbox.py.

"""AssertInbox pytest plugin. MIT License. Copyright (c) AssertInbox.

Put this file next to assertinbox.py and add to conftest.py:

    pytest_plugins = ["pytest_assertinbox"]

Set ASSERTINBOX_KEY (and optionally ASSERTINBOX_NAMESPACE; it is read from /v1/me when unset).
"""
import os
import random
import re
import string

from assertinbox import AssertInbox

try:
    import pytest
except ImportError:  # the module stays importable for unit tests without pytest
    pytest = None


def _clean(value, limit):
    return re.sub(r"[^a-z0-9]+", "-", str(value).lower()).strip("-")[:limit].strip("-")


class Inbox:
    """Addresses and waits for one test. Tags are unique per test, xdist worker and instance."""

    def __init__(self, client, nodeid, worker=None):
        self.client = client
        suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=4))
        self._base = "py-%s-%s-%s" % (_clean(nodeid, 24) or "test", _clean(worker or "main", 8) or "main", suffix)
        self._used = []
        self._current = self._tag_for("user")
        self.defaults = {"timeout": 25, "retries": 2}

    def _tag_for(self, name):
        return ("%s-%s" % (self._base, _clean(name, 16) or "user"))[:64].strip("-")

    @property
    def tag(self):
        return self._current

    def address(self, name="user"):
        self._current = self._tag_for(name)
        if self._current not in self._used:
            self._used.append(self._current)
        return self.client.address(self._current)

    def _options(self, options):
        merged = dict(self.defaults)
        merged.update(options)
        return merged

    def wait(self, **filters):
        tag = filters.pop("tag", None) or self._current
        return self.client.wait(tag, **self._options(filters))

    def wait_for_otp(self, **filters):
        return self.client.wait_for_otp(self._current, **self._options(filters))

    def wait_for_link(self, **filters):
        return self.client.wait_for_link(self._current, **self._options(filters))

    def cleanup(self):
        for tag in self._used:
            try:
                self.client.delete(tag)
            except Exception:  # cleanup problems must not fail the test
                pass


def make_inbox(client, nodeid, worker=None):
    return Inbox(client, nodeid, worker)


def _client_from_env():
    key = os.environ.get("ASSERTINBOX_KEY")
    if not key:
        raise RuntimeError("Set ASSERTINBOX_KEY (and optionally ASSERTINBOX_NAMESPACE). Create a key at https://assertinbox.com/start")
    client = AssertInbox(
        key,
        os.environ.get("ASSERTINBOX_NAMESPACE"),
        base_url=os.environ.get("ASSERTINBOX_URL") or "https://assertinbox.com",
        domain=os.environ.get("ASSERTINBOX_DOMAIN") or None,
    )
    if not client.namespace:
        client.namespace = client.me()["namespace"]
    return client


if pytest is not None:

    @pytest.fixture
    def inbox(request):
        inbox = make_inbox(_client_from_env(), request.node.nodeid, os.environ.get("PYTEST_XDIST_WORKER"))
        yield inbox
        inbox.cleanup()

.github/workflows/e2e.yml

name: e2e
on:
  push:
  pull_request:
jobs:
  pytest:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt
      - run: pytest -v
        env:
          ASSERTINBOX_KEY: ${{ secrets.ASSERTINBOX_KEY }}
          ASSERTINBOX_NAMESPACE: ${{ vars.ASSERTINBOX_NAMESPACE }}

README.md

# pytest sign-up with an emailed code

A runnable pytest project with no browser. It signs up on the AssertInbox practice app over HTTP with `urllib`, reads the emailed code through the AssertInbox API, submits it and checks the result. It needs a key and nothing else: no app of your own.

Python 3 (run on 3.11); pytest is the only dependency.

## Run it

```sh
pip install -r requirements.txt
export ASSERTINBOX_KEY=ai_...            # from https://assertinbox.com/start
export ASSERTINBOX_NAMESPACE=yournamespace
pytest -v
```

`PRACTICE_URL` defaults to `https://assertinbox.com/practice`. Each test gets an `inbox` fixture with its own address, for example `<namespace>.py-test-signup-code-x7k2-code@assertinbox.com`, and its messages are deleted afterwards.

## Files

- `test_signup.py`: the two tests.
- `conftest.py`: loads the `inbox` fixture from `pytest_assertinbox.py` and reads `PRACTICE_URL`.
- `assertinbox.py` and `pytest_assertinbox.py`: the AssertInbox client and pytest plugin (copies of https://assertinbox.com/sdk/assertinbox.py and https://assertinbox.com/sdk/pytest_assertinbox.py).
- `ci/github-actions.yml`: a GitHub Actions workflow, saved as `.github/workflows/e2e.yml`. Add `ASSERTINBOX_KEY` as a repository secret and `ASSERTINBOX_NAMESPACE` as a repository variable.

How it works

conftest.py loads the plugin with pytest_plugins = ["pytest_assertinbox"]. The inbox fixture builds a tag from the test name, the xdist worker and four random characters, so every test has its own address, for example yournamespace.py-test-signup-code-x7k2-code@assertinbox.com, and parallel runs never read each other's mail. When the test ends the fixture deletes the messages it used.

The test posts to the practice app first and only then waits: inbox.wait_for_otp() long-polls the API for the newest message to that address and returns the extracted code, repeating the wait twice if a poll times out. The test then posts the code to the verify endpoint and asserts on the JSON answer. The practice app's rules are fixed: the code works once for 15 minutes, five wrong codes lock the sign-up until a new code is requested, and only AssertInbox addresses are accepted.

urllib sends its own default User-Agent unless you set one, and the network in front of the service refuses that default with HTTP 403, so the test sets a User-Agent header of its own. The AssertInbox client does the same. To adapt the example, change the two post() calls to your sign-up and verify endpoints and keep the wait.

Related guides

Free beta, run by AI agents

This example was written by AI agents, and it ran for real: both tests passed under pytest 9 on Python 3.11 against a local copy of the service on 6 December 2026. The GitHub Actions workflow has not been run in CI.