Guide · pytest

Waiting for an OTP in pytest

A pytest test that submits a signup form with a mailsocket inbox address, then blocks on the wait endpoint until the OTP arrives. This is an HTTP-call example against the real wait endpoint — mailsocket ships no official pytest plugin.

Before you start

  • Create an inbox and an API key. Sign up, verify your email, and open the dashboard. Your first inbox is created automatically, and you can mint an API key in one click.
  • Grab your inbox address. It is <routing_key>@in.inboxpipe.net — the public id (inbox_…) is not the routing key, so read the full address from the dashboard.
  • Point your signup form at that address. Replace https://app.example.com/signup and the selectors below with your real form.

The flow

  1. Submit the signup form with the mailsocket inbox address.
  2. Block on GET /api/v1/inboxes/{id}/messages/wait with require=otp — the call returns the OTP the moment it arrives.
  3. Assert the OTP is present (and match its shape, e.g. 4–8 digits).

Copy-paste example

Never hardcode your API key — read it from the environment. Set MAILSOCKET_API_KEY, MAILSOCKET_INBOX_ID and MAILSOCKET_INBOX_ADDRESS before running.

pytest
import os
import requests

BASE = os.environ.get("MAILSOCKET_API_BASE", "https://dash.mailsocket.app")
API_KEY = os.environ["MAILSOCKET_API_KEY"]
INBOX_ADDRESS = os.environ["MAILSOCKET_INBOX_ADDRESS"]  # e.g. [email protected]


def wait_for_otp(inbox_id, timeout=20):
    """Block on the wait endpoint until an OTP arrives, or return None."""
    resp = requests.get(
        f"{BASE}/api/v1/inboxes/{inbox_id}/messages/wait",
        params={"require": "otp", "timeout": timeout},
        headers={"Authorization": f"Bearer {API_KEY}"},
        timeout=timeout + 10,
    )
    if resp.status_code == 204:
        return None  # waited, nothing yet — success, not an error
    resp.raise_for_status()
    return resp.json()["data"]["otp"]


def test_signup_delivers_otp():
    inbox_id = os.environ["MAILSOCKET_INBOX_ID"]
    # 1. Trigger the signup with a mailsocket inbox address.
    requests.post("https://app.example.com/signup", json={"email": INBOX_ADDRESS})
    # 2. Wait for the OTP in one blocking call (no polling loop).
    otp = wait_for_otp(inbox_id)
    # 3. Assert the code arrived.
    assert otp is not None
    assert otp.isdigit() and 4 <= len(otp) <= 8

Want the Playwright version too?

A ready-to-copy Playwright spec ships in this repository at examples/playwright/otp-signup.spec.ts — see the quickstart.