CI / Asserzioni
Dimostra che l'email inviata dalla tua applicazione è corretta, da uno step della pipeline o dal test runner che usi già.
Due modi di fare asserzioni
La tua applicazione invia a una sandbox Mailclutch via SMTP, esattamente come fa in staging. La domanda che un test si pone a quel punto è: è arrivata l'email giusta, ed è corretta? L'API risponde con due livelli di coinvolgimento:
| Approccio | Cosa scrivi | Quando sceglierlo |
|---|---|---|
| expect | Una chiamata: quale messaggio, e cosa deve essere vero. Risponde superato o fallito | Step di CI, e la maggior parte dei test. I controlli che ti servono sono nel vocabolario |
| wait, poi lettura | Una chiamata resta bloccata fino al messaggio; a verificarlo è il tuo codice | Un'asserzione che il vocabolario non prevede, o un flusso che prosegue a partire dall'email |
Entrambi lavorano sulla stessa sandbox, con lo stesso token, e sono semplice HTTP: nessun SDK, nessuna libreria client, niente da tenere aggiornato.
Expect: un verdetto in una sola chiamata
POST /sandboxes/{sandbox_id}/expect riceve due cose. I selettori dicono a quale messaggio si riferisce l'aspettativa (un destinatario, un mittente, un oggetto), così un'email di benvenuto arrivata accanto al reset che stai testando non dà fastidio. I controlli dicono cosa deve essere vero: stringhe presenti nel corpo, un link che corrisponde a un pattern, un codice monouso, nessuna variabile di template rimasta non renderizzata, un punteggio minimo di deliverability, un numero esatto di allegati. La chiamata attende il primo messaggio che corrisponde ai selettori, esegue tutti i controlli e risponde 200 con ok: true oppure 422 con ok: false.
curl -sS --fail-with-body "https://app.mailclutch.com/api/v1/sandboxes/$MAILCLUTCH_SANDBOX_ID/expect" \ -H "Authorization: Bearer $MAILCLUTCH_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "timeout": 30, "expect": { "to": "user@example.com", "subject_contains": "Reset your password", "has_link_matching": "^https://app\\.acme\\.dev/reset/", "no_unrendered_variables": true } }' # --fail-with-body (curl 7.76 or later) turns the 422 of a failed expectation # into a non-zero exit and keeps the response: the step is red, and the failures # are in the output. Plain --fail exits the same way but prints no body.
const API = 'https://app.mailclutch.com/api/v1'; const headers = { Authorization: `Bearer ${process.env.MAILCLUTCH_TOKEN}`, 'Content-Type': 'application/json', }; test('the password reset email is right', async ({ page }) => { await requestPasswordReset('user@example.com'); const res = await fetch(`${API}/sandboxes/${process.env.MAILCLUTCH_SANDBOX_ID}/expect`, { method: 'POST', headers, body: JSON.stringify({ timeout: 30, expect: { to: 'user@example.com', subject_contains: 'Reset your password', has_link_matching: '^https://app\\.acme\\.dev/reset/', no_unrendered_variables: true, }, }), }); const verdict = await res.json(); // 200 → ok: true. 422 → ok: false, one entry per failed rule. expect(verdict.failures).toEqual([]); // The same call extracted the link: carry on with the flow. await page.goto(verdict.extracted.matched_link); });
import os import requests API = "https://app.mailclutch.com/api/v1" headers = {"Authorization": f"Bearer {os.environ['MAILCLUTCH_TOKEN']}"} def test_password_reset_email(page): request_password_reset("user@example.com") verdict = requests.post( f"{API}/sandboxes/{os.environ['MAILCLUTCH_SANDBOX_ID']}/expect", headers=headers, json={ "timeout": 30, "expect": { "to": "user@example.com", "subject_contains": "Reset your password", "has_link_matching": r"^https://app\.acme\.dev/reset/", "no_unrendered_variables": True, }, }, ).json() # 200 → ok: True. 422 → ok: False, one entry per failed rule. assert verdict["failures"] == [] # The same call extracted the link: carry on with the flow. page.goto(verdict["extracted"]["matched_link"])
use Illuminate\Support\Facades\Http; it('sends a correct password reset email', function () { requestPasswordReset('user@example.com'); $verdict = Http::withToken(env('MAILCLUTCH_TOKEN')) ->post('https://app.mailclutch.com/api/v1/sandboxes/'.env('MAILCLUTCH_SANDBOX_ID').'/expect', [ 'timeout' => 30, 'expect' => [ 'to' => 'user@example.com', 'subject_contains' => 'Reset your password', 'has_link_matching' => '^https://app\.acme\.dev/reset/', 'no_unrendered_variables' => true, ], ])->json(); // 200 → ok: true. 422 → ok: false, one entry per failed rule. expect($verdict['failures'])->toBe([]); });
Il lavoro lo fanno due parti della risposta. failures è il messaggio dell'asserzione: una voce per ogni regola non rispettata, ciascuna con ciò che era atteso e ciò che c'era, così uno step rosso in un log di CI dice il perché al primo sguardo. extracted torna in entrambi i casi, con tutti i link, il codice monouso e il link che corrisponde al tuo pattern: lo step successivo del test li segue senza un'altra chiamata.
Anche l'assenza, entro il tempo limite, di messaggi che corrispondono ai selettori è un 422, con un unico errore arrival e il conteggio degli altri messaggi arrivati nel frattempo: un invio mai avvenuto e un invio finito all'indirizzo sbagliato non si somigliano. Il vocabolario completo di selettori e controlli è nel riferimento di wait ed expect.
Due parole su deliverability_at_least: la tua applicazione consegna la posta alla sandbox via SMTP autenticato, senza passare dal tuo relay di produzione, quindi SPF, DKIM e DMARC non vengono verificati e non entrano nel punteggio. Un punteggio alto dice che il messaggio in sé è sano, non che lo sia la tua autenticazione: l'analisi lo segnala con authentication_verified: false. Per testare l'autenticazione, invia un'email vera dal tuo server di produzione all'indirizzo forward_email della sandbox.
Wait, poi le asserzioni le fai tu
POST /sandboxes/{sandbox_id}/wait è la prima metà di expect, da sola: resta bloccata finché non arriva un messaggio che corrisponde ai filtri, poi ne restituisce id e riepilogo. Da lì il messaggio è tuo: puoi leggerne corpo e allegati e i link e codici estratti, e i controlli li scrivi nel tuo framework di test, con la sua libreria di asserzioni e i suoi messaggi di errore.
const API = 'https://app.mailclutch.com/api/v1'; const headers = { Authorization: `Bearer ${process.env.MAILCLUTCH_TOKEN}` }; const SANDBOX = process.env.MAILCLUTCH_SANDBOX_ID; test('the reset link works', async ({ page }) => { await requestPasswordReset('user@example.com'); // Blocks until a matching message arrives, or the timeout passes. const wait = await fetch(`${API}/sandboxes/${SANDBOX}/wait`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ timeout: 30, subject_contains: 'Reset your password' }), }).then((res) => res.json()); expect(wait.matched, `${wait.other_messages_since ?? 0} other message(s) arrived`).toBe(true); // Now read it the way you want: here, the links it contains. const { links } = await fetch(`${API}/emails/${wait.email.id}/extract`, { headers }) .then((res) => res.json()); const reset = links.find((link) => link.host === 'app.acme.dev'); expect(reset).toBeDefined(); await page.goto(reset.url); await expect(page.getByRole('heading', { name: 'Choose a new password' })).toBeVisible(); });
import os import requests API = "https://app.mailclutch.com/api/v1" headers = {"Authorization": f"Bearer {os.environ['MAILCLUTCH_TOKEN']}"} SANDBOX = os.environ["MAILCLUTCH_SANDBOX_ID"] def test_reset_link_works(page): request_password_reset("user@example.com") # Blocks until a matching message arrives, or the timeout passes. wait = requests.post( f"{API}/sandboxes/{SANDBOX}/wait", headers=headers, json={"timeout": 30, "subject_contains": "Reset your password"}, ).json() assert wait["matched"], f"{wait.get('other_messages_since', 0)} other message(s) arrived" # Now read it the way you want: here, the links it contains. extract = requests.get(f"{API}/emails/{wait['email']['id']}/extract", headers=headers).json() reset = next(link for link in extract["links"] if link["host"] == "app.acme.dev") page.goto(reset["url"]) assert page.get_by_role("heading", name="Choose a new password").is_visible()
use Illuminate\Support\Facades\Http; it('sends a working reset link', function () { $api = 'https://app.mailclutch.com/api/v1'; $sandbox = env('MAILCLUTCH_SANDBOX_ID'); $client = Http::withToken(env('MAILCLUTCH_TOKEN')); requestPasswordReset('user@example.com'); // Blocks until a matching message arrives, or the timeout passes. $wait = $client->post("$api/sandboxes/$sandbox/wait", [ 'timeout' => 30, 'subject_contains' => 'Reset your password', ])->json(); expect($wait['matched'])->toBeTrue(); // Now read it the way you want: here, the links it contains. $extract = $client->get("$api/emails/{$wait['email']['id']}/extract")->json(); $reset = collect($extract['links'])->firstWhere('host', 'app.acme.dev'); expect($reset)->not->toBeNull(); expect($reset['url'])->toStartWith('https://app.acme.dev/reset/'); });
Se nulla corrisponde entro il tempo limite la risposta è 422 con matched: false: leggi quindi il corpo invece di sollevare un'eccezione sullo stato, come fanno questi esempi. Il conteggio degli altri messaggi che contiene dice se è fallito l'invio o se è sbagliato il filtro. Entrambe le chiamate contano solo la posta arrivata dopo il loro avvio, così un messaggio già presente nella sandbox non può far passare per buono un invio rotto. Quando l'invio avviene prima dell'attesa (uno step della pipeline fa partire l'email, uno step successivo attende) passa since con il momento di inizio dell'esecuzione.
Una sandbox per esecuzione
Una sandbox condivisa va svuotata e non può servire due esecuzioni insieme. L'alternativa è una sandbox effimera: creata con un ttl all'inizio dell'esecuzione, la sua coppia SMTP passata all'applicazione sotto test, eliminata alla fine; oppure da sola allo scadere del tempo, se il runner è morto prima. Una per pull request, per branch, per cella della matrice; non rientrano nella quota di sandbox del piano.
SANDBOX=$(curl -sS --fail "https://app.mailclutch.com/api/v1/sandboxes" \ -H "Authorization: Bearer $MAILCLUTCH_TOKEN" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: run-$CI_RUN_ID" \ -d '{"name":"pr-482","ttl":"1h"}') export SMTP_HOST=$(echo "$SANDBOX" | jq -r .smtp.host) export SMTP_PORT=$(echo "$SANDBOX" | jq -r .smtp.port) export SMTP_USERNAME=$(echo "$SANDBOX" | jq -r .smtp.username) export SMTP_PASSWORD=$(echo "$SANDBOX" | jq -r .smtp.password) export MAILCLUTCH_SANDBOX_ID=$(echo "$SANDBOX" | jq -r .id)
L'Idempotency-Key conta: una richiesta ritentata non deve generare una seconda sandbox. Le due sezioni qui sotto mettono tutto in pratica: prima come job di GitHub Actions, poi dentro un test.
Un job di GitHub Actions
Una sandbox effimera per esecuzione, la sua coppia SMTP passata alla suite di test come variabili d'ambiente, un verdetto alla fine e un'eliminazione che gira anche quando i test falliscono. L'unico segreto nel repository è il token API; le credenziali SMTP vengono generate a ogni esecuzione e muoiono con la sandbox.
name: email on: [pull_request] env: MAILCLUTCH_API: https://app.mailclutch.com/api/v1 jobs: signup-email: runs-on: ubuntu-latest defaults: run: shell: bash # Adds pipefail: without it, tee hides curl's exit code. steps: - uses: actions/checkout@v4 - name: Create a sandbox for this run id: sandbox run: | RESPONSE=$(curl -sS --fail "$MAILCLUTCH_API/sandboxes" \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: gha-${{ github.run_id }}-${{ github.run_attempt }}" \ -d '{"name":"pr-${{ github.event.number }}","ttl":"1h"}') echo "id=$(echo "$RESPONSE" | jq -r .id)" >> "$GITHUB_OUTPUT" echo "SMTP_HOST=$(echo "$RESPONSE" | jq -r .smtp.host)" >> "$GITHUB_ENV" echo "SMTP_PORT=$(echo "$RESPONSE" | jq -r .smtp.port)" >> "$GITHUB_ENV" echo "SMTP_USERNAME=$(echo "$RESPONSE" | jq -r .smtp.username)" >> "$GITHUB_ENV" echo "::add-mask::$(echo "$RESPONSE" | jq -r .smtp.password)" echo "SMTP_PASSWORD=$(echo "$RESPONSE" | jq -r .smtp.password)" >> "$GITHUB_ENV" echo "RUN_STARTED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_ENV" - name: Run the flow that sends the email run: npm ci && npm run test:signup - name: The email arrived and is right run: | curl -sS --fail-with-body "$MAILCLUTCH_API/sandboxes/${{ steps.sandbox.outputs.id }}/expect" \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}" \ -H "Content-Type: application/json" \ -d @- <<JSON | tee verdict.json { "timeout": 30, "since": "$RUN_STARTED_AT", "expect": { "to": "signup-test@example.com", "subject_matches": "^Verify your email", "has_link_matching": "^https://app\\\\.acme\\\\.dev/verify/[A-Za-z0-9]+$", "no_unrendered_variables": true, "deliverability_at_least": 80 } } JSON - name: Post the rendered email on the pull request if: always() && steps.sandbox.outputs.id != '' run: | EMAIL_ID=$(jq -r '.email.id // empty' verdict.json 2>/dev/null || true) [ -z "$EMAIL_ID" ] && exit 0 URL=$(curl -sS --fail "$MAILCLUTCH_API/emails/$EMAIL_ID/shares" \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}" \ -H "Content-Type: application/json" -d '{"expires_in":"7d"}' | jq -r .url) gh pr comment ${{ github.event.number }} --body "Sign-up email on this branch: $URL" env: GH_TOKEN: ${{ github.token }} - name: Delete the sandbox if: always() && steps.sandbox.outputs.id != '' run: | curl -sS "$MAILCLUTCH_API/sandboxes/${{ steps.sandbox.outputs.id }}" -X DELETE \ -H "Authorization: Bearer ${{ secrets.MAILCLUTCH_TOKEN }}"
Cinque cose da notare. shell: bash è ciò che attiva pipefail: la shell predefinita di GitHub gira senza, quindi tee nasconderebbe il codice di uscita di curl e un'aspettativa fallita lascerebbe lo step verde. --fail-with-body conserva la risposta in verdict.json, così lo step successivo può comunque condividere l'email che non ha superato i controlli. L'Idempotency-Key include il numero del tentativo, quindi un job rilanciato ottiene una sandbox sua, mentre una richiesta ritentata ottiene la stessa. L'aspettativa porta since, perché l'email è stata inviata prima che iniziasse l'attesa. E l'ultimo step non è strettamente necessario (un'ora dopo la sandbox sparisce da sola), ma un job che pulisce dietro di sé tiene il numero di sandbox attive ben lontano dal limite di 50.
Lo stesso flusso dentro un test
Quando è la suite di test a parlare con l'API (un'esecuzione Playwright o Vitest che gestisce l'intero flusso) lo schema è lo stesso, senza la shell: crea la sandbox nel test, passa la sua coppia SMTP al codice sotto test, chiama expect ed elimina in un finally.
const API = 'https://app.mailclutch.com/api/v1'; const headers = { Authorization: `Bearer ${process.env.MAILCLUTCH_TOKEN}`, 'Content-Type': 'application/json', }; const call = async (path, init = {}) => { const res = await fetch(`${API}${path}`, { ...init, headers }); const body = await res.json(); if (!res.ok && res.status !== 422) throw new Error(`${res.status} ${body.message}`); return body; }; test('the password reset email is right', async () => { const sandbox = await call('/sandboxes', { method: 'POST', body: JSON.stringify({ name: 'reset-flow', ttl: '10m' }), }); try { const startedAt = new Date().toISOString(); await requestPasswordReset('user@example.com', sandbox.smtp); const verdict = await call(`/sandboxes/${sandbox.id}/expect`, { method: 'POST', body: JSON.stringify({ timeout: 30, since: startedAt, expect: { to: 'user@example.com', subject_contains: 'Reset your password', has_link_matching: '^https://app\\.acme\\.dev/reset/', no_unrendered_variables: true, }, }), }); // The failures array is the assertion message: expected and actual, per rule. expect(verdict.failures).toEqual([]); // Follow the link the same call extracted. await page.goto(verdict.extracted.matched_link); await expect(page.getByRole('heading', { name: 'Choose a new password' })).toBeVisible(); } finally { await call(`/sandboxes/${sandbox.id}`, { method: 'DELETE' }); } });
Un 422 da expect è un verdetto, non un errore di trasporto: per questo l'helper lo lascia passare, e il test legge failures e fallisce con quelli. Tutto il resto sulle chiamate (paginazione, chiavi, limiti) è in Convenzioni.
Token e scope
Dai alla CI un token tutto suo, con una scadenza e solo gli scope che servono all'approccio scelto, e ruotalo dalla schermata delle impostazioni quando la scadenza si avvicina:
| Per | Scope |
|---|---|
| wait, expect, elencare, leggere, estrarre | emails:read |
Il controllo deliverability_at_least | analysis:run |
| Creare ed eliminare una sandbox per esecuzione | sandboxes:create, sandboxes:delete |
| Condividere l'email renderizzata in una pull request | shares:create |
Una chiamata bloccante tiene occupato un worker, quindi wait ed expect hanno dei limiti: due alla volta per sandbox, due minuti ciascuna. Due minuti sono molto più di quanto duri qualsiasi invio reale; un test a cui ne servono di più sta aspettando un invio che non è avvenuto. La grammatica degli scope e il vincolo alle sandbox sono in Autenticazione e scope.