停止测试成功。杀掉数据库。🧨

发布: (2025年12月11日 GMT+8 18:00)
4 min read
原文: Dev.to

Source: Dev.to

介绍

面向 QA 的混沌工程

面向 QA 的混沌工程简介。学习如何通过 Docker 和 Playwright 注入故障来测试系统的弹性。

我们痴迷于“幸福路径”。

在传统 QA 中,我们验证当一切都完美时应用是否正常工作:

  • 网络稳定。
  • 数据库在 5 ms 内响应。
  • 第三方 API 在线。

但在生产环境中,没有什么是完美的。Pod 会崩溃,网络会延迟,数据库会锁死。

当这些情况发生时,普通的 Selenium/Playwright 测试只会显示 Failed。它并不会告诉你应用是如何失败的。是显示了友好的错误信息,还是出现了白屏并抛出原始堆栈?

这时 混沌工程 就派上用场了。

从 QA 到弹性工程

混沌工程不仅仅是站点可靠性工程师(SRE)的专利。作为现代 QA,我们需要停止问“它能工作吗?”而是要问“当它出错时会怎样?”

今天,我将向你展示如何使用 Python、Playwright 和 Docker SDK 编写一个 混沌测试

目标

我们不会等数据库自行失效,而是在测试进行中有意杀掉它,并验证前端是否能够优雅地处理。

技术栈

  • Python – 测试逻辑
  • Playwright – UI 交互
  • Docker SDK – 混沌注入器

代码 🐍

import docker
import time
from playwright.sync_api import Page, expect

def test_database_failure_resilience(page: Page):
    # 1. Setup: Connect to Docker
    client = docker.from_env()

    # Target your specific database container
    try:
        db_container = client.containers.get("postgres-prod")
    except docker.errors.NotFound:
        raise Exception("Database container not found! Is Docker running?")

    # 2. Happy Path: Verify the app loads normally
    print("✅ Step 1: Loading Dashboard...")
    page.goto("http://localhost:3000/dashboard")
    expect(page.locator(".user-balance")).to_be_visible()

    # 🧨 CHAOS TIME: Kill the Database
    print("🔥 Step 2: Injecting Chaos (Stopping DB)...")
    db_container.stop()

    # 3. Resilience Assertion
    # The app should NOT show a white screen or crash.
    # It SHOULD show a friendly "Connection Lost" toast or retry button.
    print("👀 Step 3: Verifying graceful degradation...")

    # Trigger an action that requires the DB
    page.reload()

    # Assert UI handles the error
    expect(page.locator(".error-toast")).to_contain_text("Connection lost")
    expect(page.locator(".retry-button")).to_be_visible()

    # 🩹 RECOVERY: Bring the Database back
    print("🩹 Step 4: Healing the infrastructure...")
    db_container.start()

    # Give the app a moment to reconnect (or trigger a manual retry)
    page.locator(".retry-button").click()

    # 4. Self‑Healing Assertion
    # The app should recover without requiring a full page refresh
    expect(page.locator(".user-balance")).to_be_visible()
    print("✅ Test Passed: System is resilient.")

为什么这很重要

如果你运行此测试时,应用显示了 500 Server Error 页面,那么你已经发现了一个 bug——不是功能性 bug,而是 架构性 bug

通过在回归套件中加入“混沌测试”,你可以确保你的产品不仅能工作,还能生存下来

想要更多混沌?

我撰写 The 5‑Minute QA——面向高级 QA 与 SDET 的每日简报。每天早晨,我会发送一条关于 混沌工程 的可操作技巧。

👉 订阅此处获取邮件提示

Back to Blog

相关文章

阅读更多 »

别再买Mac来修复 CSS 了

“黑客”方式在 Windows 与 Linux 上调试 Safari 说实话:Safari 已经成了新的 Internet Explorer。作为网页开发者,我们主要使用 Chromium Chrome……