CI / 断言
证明应用发出的邮件没有问题,可以在流水线步骤里做,也可以在你已经在用的测试运行器里做。
两种断言方式
你的应用通过 SMTP 把邮件发进 Mailclutch 沙箱,和在预发布环境中完全一样。接下来测试要问的是:该来的邮件来了吗?内容对吗?API 提供两种介入程度不同的回答方式:
| 方式 | 你要写什么 | 适用场景 |
|---|---|---|
| expect | 一次调用:指定哪封邮件、它必须满足什么。返回通过或失败 | CI 步骤和大多数测试。你需要的检查项都在内置词汇里 |
| wait,然后读取 | 一次调用阻塞等待邮件;检查由你自己的代码完成 | 内置词汇里没有的断言,或者要从邮件继续往下走的流程 |
两种方式用的是同一个沙箱、同一个令牌,而且都是纯 HTTP:没有 SDK,没有客户端库,没有需要跟着升级的东西。
Expect:一次调用给出结论
POST /sandboxes/{sandbox_id}/expect 接收两样东西。选择器指明这条预期针对哪封邮件,可以按收件人、发件人或主题筛选,这样和你正在测试的重置邮件同时到达的欢迎邮件就不会碍事。检查项指明它必须满足什么:正文包含的字符串、匹配某个模式的链接、一次性验证码、没有未渲染的模板变量、最低送达率评分、确切的附件数量。调用会等待第一封匹配选择器的邮件,执行所有检查,然后返回 200 和 ok: true,或者 422 和 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([]); });
响应中真正起作用的是两部分。failures 就是断言消息:每条未通过的规则对应一项,写明预期是什么、实际是什么,CI 日志里一个红色步骤直接说明原因,不用再去查。extracted 无论成败都会返回,包含所有链接、一次性验证码以及匹配你模式的那个链接,测试的下一步可以直接使用,不必再调用一次。
规定时间内没有邮件匹配选择器,同样返回 422,其中只有一条 arrival 失败项,并附上这段时间内到达的其他邮件数量:根本没发出去,和发到了错误的地址,看上去是不一样的。选择器和检查项的完整词汇见 wait 与 expect 参考。
关于 deliverability_at_least 多说一句:你的应用通过经过认证的 SMTP 把邮件直接交给沙箱,不经过生产环境的中继,所以 SPF、DKIM 和 DMARC 不会被验证,也不计入评分。高分说明邮件本身没问题,不代表你的发信认证没问题,分析结果中会以 authentication_verified: false 标明。要测试认证,请从生产服务器向沙箱的 forward_email 地址发一封真实邮件。
Wait:先等待,再自行断言
POST /sandboxes/{sandbox_id}/wait 就是 expect 的前半段:它一直阻塞到有邮件匹配过滤条件,然后返回这封邮件的 id 和摘要。之后怎么读由你决定:可以读正文和附件,也可以读从中提取的链接和验证码;检查则写在你的测试框架里,用它自带的断言库和失败信息。
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/'); });
规定时间内没有匹配的邮件,会返回 422 和 matched: false,所以请像这些示例一样读取响应体,不要一看到状态码就抛异常:其中的其他邮件数量能说明是发送失败了,还是过滤条件写错了。两个调用都只统计调用开始之后到达的邮件,沙箱里原有的邮件不会让一次失败的发送看起来像成功了。如果发送发生在等待之前,比如流水线里一个步骤触发邮件、下一个步骤才等待,请把运行开始的时刻通过 since 传入。
每次运行一个沙箱
共享沙箱用之前得清空,也没法同时服务两次运行。替代方案是临时沙箱:运行开始时带 ttl 创建,把它的 SMTP 凭据交给被测应用,结束时删除;如果运行器中途挂了,到期后它也会自行消失。每个拉取请求一个,每个分支一个,矩阵里每个组合一个,都不占方案的沙箱配额。
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)
Idempotency-Key 很重要:请求重试时不能再生成第二个沙箱。下面两节是完整的实际用法,先是一个 GitHub Actions 任务,然后是写在测试内部。
一个 GitHub Actions 任务
每次运行一个临时沙箱,SMTP 凭据以环境变量的形式交给测试套件,最后给出结论,并且即使测试失败也会执行删除。仓库里唯一的 secret 是 API 令牌;SMTP 凭据每次运行现生成,随沙箱一起销毁。
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 }}"
有五点值得注意。shell: bash 的作用是开启 pipefail:GitHub 的默认 shell 不带它,tee 会吞掉 curl 的退出码,预期失败了步骤却还是绿的。--fail-with-body 把响应保留在 verdict.json 里,下一步仍然可以分享那封没通过的邮件。Idempotency-Key 包含运行的尝试次数,所以重跑的任务会得到自己的沙箱,而重试的请求拿到的还是同一个。预期里带了 since,因为邮件在等待开始之前就发出了。最后一步严格来说可有可无,反正一小时后沙箱会自行消失;但任务自己收拾干净,存活的沙箱数量才不会逼近 50 个的上限。
同样的流程,写在测试内部
如果由测试套件自己调用 API,比如整个流程都由一次 Playwright 或 Vitest 运行负责,结构不变,只是不需要 shell:在测试里生成沙箱,把 SMTP 凭据交给被测代码,执行 expect,然后在 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' }); } });
expect 返回的 422 是结论,不是传输错误,所以辅助函数会把它放行:测试读取 failures,并据此判定失败。关于这些调用的其他细节,如分页、键和限制,见约定。
令牌与作用域
给 CI 一个专用令牌,设好有效期,只授予所用方式需要的作用域;快到期时在设置页面轮换:
| 用途 | 作用域 |
|---|---|
| wait、expect、列出、读取、提取 | emails:read |
检查 deliverability_at_least | analysis:run |
| 每次运行生成并删除一个沙箱 | sandboxes:create, sandboxes:delete |
| 在拉取请求中分享渲染后的邮件 | shares:create |
阻塞式调用会占住一个 worker,所以 wait 和 expect 有上限:每个沙箱同时两个,每个最长两分钟。两分钟远超任何一次真实发送所需的时间;需要等更久的测试,等的其实是一封根本没发出来的邮件。作用域的写法和沙箱绑定见认证与作用域。