AssertInbox

Test sign-up emails from Go with the testing package

If your back end is written in Go, the sign-up test can be a plain go test that needs no browser and no third-party module. The test posts to your sign-up endpoint with a unique address, waits for the email with the AssertInbox API, and asserts the subject, the format of the one-time code and the host of the link. It uses only net/http and encoding/json from the standard library, and t.Parallel() with a unique tag per test so the tests never read each other's mail.

What your app needs

A running instance of your service, in a staging or CI environment, whose sign-up handler sends a real email through SMTP or a mail provider. The example assumes a form post to /signup with an email field, answered with a status below 400, and an email with the word verify in its subject, a six-digit code and a link. Change the path, the fields and the expectations to match your service. Set APP_URL to the service under 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, including id, subject, otp, 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. 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 helper

Save this as signup_helper_test.go in the package directory of your tests. Because the name ends in _test.go, it is compiled only for tests. newInbox builds a unique tag from the clock, the process id and the test name, registers a cleanup that deletes the messages, and skips the test when the key is not set. waitForEmail retries on a 408 timeout, up to three times 25 seconds.

package signup_test

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"
	"testing"
	"time"
)

const api = "https://assertinbox.com"

type message struct {
	ID        string   `json:"id"`
	Subject   string   `json:"subject"`
	OTP       string   `json:"otp"`
	MagicLink string   `json:"magic_link"`
	Links     []string `json:"links"`
}

type inbox struct {
	tag   string
	email string
}

var httpClient = &http.Client{Timeout: 40 * time.Second}

// newInbox returns a unique address for one test. It skips the test when the key is not set.
func newInbox(t *testing.T) inbox {
	t.Helper()
	namespace := os.Getenv("ASSERTINBOX_NAMESPACE")
	if os.Getenv("ASSERTINBOX_KEY") == "" || namespace == "" {
		t.Skip("ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE are not set")
	}
	tag := strings.ToLower(fmt.Sprintf("go-%d-%d", time.Now().UnixNano()/1e6, os.Getpid()))
	tag += strings.ToLower(strings.ReplaceAll(t.Name(), "/", "-"))
	box := inbox{tag: tag, email: namespace + "." + tag + "@assertinbox.com"}
	t.Cleanup(func() { box.clear() })
	return box
}

func call(method, path string, params url.Values) (*http.Response, error) {
	req, err := http.NewRequest(method, api+path+"?"+params.Encode(), nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("ASSERTINBOX_KEY"))
	return httpClient.Do(req)
}

// waitForEmail returns the newest matching message. It retries on 408, the long-poll timeout.
func (b inbox) waitForEmail(subject string) (message, error) {
	params := url.Values{"tag": {b.tag}, "timeout": {"25"}}
	if subject != "" {
		params.Set("subject", subject)
	}
	for attempt := 0; attempt < 3; attempt++ {
		res, err := call(http.MethodGet, "/v1/wait", params)
		if err != nil {
			return message{}, err
		}
		var msg message
		decodeErr := json.NewDecoder(res.Body).Decode(&msg)
		res.Body.Close()
		switch res.StatusCode {
		case http.StatusOK:
			return msg, decodeErr
		case http.StatusRequestTimeout:
			continue
		default:
			return message{}, fmt.Errorf("AssertInbox returned HTTP %d", res.StatusCode)
		}
	}
	return message{}, errors.New("no email arrived for tag " + b.tag)
}

func (b inbox) clear() {
	res, err := call(http.MethodDelete, "/v1/messages", url.Values{"tag": {b.tag}})
	if err == nil {
		res.Body.Close()
	}
}

The tests

Save this as signup_test.go in the same directory. Both tests call t.Parallel(), and each one has its own address, so they run side by side. Use plain test names without spaces or capital letters beyond the usual TestXxx form, because the name becomes part of the tag.

package signup_test

import (
	"net/http"
	"net/url"
	"os"
	"regexp"
	"strings"
	"testing"
)

var codePattern = regexp.MustCompile(`^[0-9]{6}$`)

func appURL() string {
	if v := os.Getenv("APP_URL"); v != "" {
		return v
	}
	return "http://localhost:8080"
}

func signUp(t *testing.T, email string) {
	t.Helper()
	res, err := http.PostForm(appURL()+"/signup", url.Values{"email": {email}})
	if err != nil {
		t.Fatal(err)
	}
	res.Body.Close()
	if res.StatusCode >= 400 {
		t.Fatalf("sign-up returned HTTP %d", res.StatusCode)
	}
}

func TestSignupEmailHasCode(t *testing.T) {
	t.Parallel()
	box := newInbox(t)
	signUp(t, box.email)

	msg, err := box.waitForEmail("verify")
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(strings.ToLower(msg.Subject), "verify") {
		t.Errorf("unexpected subject %q", msg.Subject)
	}
	if !codePattern.MatchString(msg.OTP) {
		t.Errorf("otp %q is not six digits", msg.OTP)
	}
}

func TestSignupEmailLinkHost(t *testing.T) {
	t.Parallel()
	box := newInbox(t)
	signUp(t, box.email)

	msg, err := box.waitForEmail("verify")
	if err != nil {
		t.Fatal(err)
	}
	link, err := url.Parse(msg.MagicLink)
	if err != nil || msg.MagicLink == "" {
		t.Fatalf("no usable link in the email: %q", msg.MagicLink)
	}
	want, _ := url.Parse(appURL())
	if link.Host != want.Host {
		t.Errorf("link host %q, want %q", link.Host, want.Host)
	}
}

Run them with go test ./... -run Signup -v. The first test checks that the subject contains the expected word and that otp is exactly six digits. The second parses magic_link and compares its host with the host of APP_URL, which catches links that point at localhost or at the wrong environment.

A second email to the same address

When a test triggers two emails for one address, for example sign-up and then resend, the second wait can return the first message again. Read the id of the first message and pass it as the after query parameter on the next wait, so the call returns only a newer message. Extend waitForEmail with an after argument the same way as subject. The tag and the id contain only characters that need no escaping, and url.Values encodes them anyway.

Using the API from other places

The helper is about forty lines because the API is plain HTTP and JSON. The same calls work from shell with curl, as described in the docs. Go has no client file, so the helper above is the client. The daily allowance and all error codes are on the limits page.

Troubleshooting

Next steps

Read Reliable email tests for unique tags, retries and cleanup. Related guides: API-only sign-up tests in Node.js, email tests in GitHub Actions 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.