用 pytest 在 Python 中做邮件测试
pytest 的 fixture 天生适合邮件测试:每个测试拿到一个全新的邮箱,用完即止,永远看不到别的测试的邮件。
第 1 步:辅助函数
# inbox.py - disposable inboxes from QuickInbox's free API (no key needed)
import re, time, requests
BASE = "https://quickinbox.net"
def create_inbox(minutes=10):
r = requests.post(f"{BASE}/api/generate", json={"minutes": minutes})
r.raise_for_status()
address = r.json()["address"]
return address, address.split("@")[0]
def wait_for_email(local, subject="", timeout=60, interval=2):
deadline = time.time() + timeout
while time.time() < deadline:
r = requests.get(f"{BASE}/api/inbox/{local}")
if r.ok:
for m in r.json().get("messages", []):
if subject in m["subject"]:
return m # id, from, subject, text, html, receivedAt
time.sleep(interval)
raise TimeoutError(f"No email with subject {subject!r} in {timeout}s")
def extract_code(email):
m = re.search(r"\b(\d{4,8})\b", email.get("text") or "")
if not m:
raise ValueError("No code found")
return m.group(1)
def extract_link(email, pattern):
for url in re.findall(r'href="([^"]+)"', email.get("html") or ""):
url = url.replace("&", "&")
if re.search(pattern, url):
return url
raise ValueError(f"No link matching {pattern}")第 2 步:fixture
# conftest.py
import pytest
import inbox
@pytest.fixture
def test_inbox():
address, local = inbox.create_inbox(minutes=10)
class Box:
pass
box = Box()
box.address = address
box.wait = lambda subject="", timeout=60: inbox.wait_for_email(local, subject, timeout)
return box第 3 步:测试
# test_emails.py
import inbox
from myapp.accounts import register, request_password_reset
def test_verification_link(test_inbox):
register(test_inbox.address, "Correct-Horse-42")
email = test_inbox.wait("Verify")
link = inbox.extract_link(email, r"/verify\?token=")
assert link.startswith("https://staging.example.com/")
def test_reset_code(test_inbox):
request_password_reset(test_inbox.address)
email = test_inbox.wait("Reset")
assert len(inbox.extract_code(email)) == 6并行运行
用 pytest -n auto(pytest-xdist)时,每个测试仍然有自己的邮箱。免费 API 每个 IP 每分钟大约能创建 10 个新地址,所以更大的测试套件请把 fixture 换成 Business API:任何 namespace.tag@quickinbox.net 地址无需创建调用即可使用,用 GET /api/business/mail 读取邮件。
Django 和 Flask
在 Django 中,测试运行器会换成内存邮件后端。对这些测试,请改回你真实的 SMTP 或 API 后端(例如用 @override_settings(EMAIL_BACKEND=...)),让邮件真正从应用发出。在 Flask 中,确保这组测试的 MAIL_SUPPRESS_SEND 是关闭的。
相关指南
现在就试:上面的免费接口无需注册,文档在临时邮箱 API 页面。如需私有邮箱、webhook 和大规模 CI,QuickInbox Business API 提供每月 5,000 封邮件的免费套餐。