PolarHub
  • Agents
  • MCP Servers
  • Skills
  • PolarBear
PolarHub © 2026
技能市场测试开发ai-regression-testing
返回「测试开发」

ai-regression-testing

by affaan-m·ecc

0下载测试开发

简介

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code.

SKILL.md 详细内容

来自 ECC · 11KB

AI Regression Testing

Testing patterns specifically designed for AI-assisted development, where the same model writes code and reviews it — creating systematic blind spots that only automated tests can catch.

When to Activate

  • AI agent (Claude Code, Cursor, Codex) has modified API routes or backend logic
  • A bug was found and fixed — need to prevent re-introduction
  • Project has a sandbox/mock mode that can be leveraged for DB-free testing
  • Running /bug-check or similar review commands after code changes
  • Multiple code paths exist (sandbox vs production, feature flags, etc.)

The Core Problem

When an AI writes code and then reviews its own work, it carries the same assumptions into both steps. This creates a predictable failure pattern:

AI writes fix → AI reviews fix → AI says "looks correct" → Bug still exists

Real-world example (observed in production):

Fix 1: Added notification_settings to API response
  → Forgot to add it to the SELECT query
  → AI reviewed and missed it (same blind spot)

Fix 2: Added it to SELECT query
  → TypeScript build error (column not in generated types)
  → AI reviewed Fix 1 but didn't catch the SELECT issue

Fix 3: Changed to SELECT *
  → Fixed production path, forgot sandbox path
  → AI reviewed and missed it AGAIN (4th occurrence)

Fix 4: Test caught it instantly on first run PASS:

The pattern: sandbox/production path inconsistency is the #1 AI-introduced regression.

Sandbox-Mode API Testing

Most projects with AI-friendly architecture have a sandbox/mock mode. This is the key to fast, DB-free API testing.

Setup (Vitest + Next.js App Router)

// vitest.config.ts
import { defineConfig } from "vitest/config";
import path from "path";

export default defineConfig({
  test: {
    environment: "node",
    globals: true,
    include: ["__tests__/**/*.test.ts"],
    setupFiles: ["__tests__/setup.ts"],
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "."),
    },
  },
});
// __tests__/setup.ts
// Force sandbox mode — no database needed
process.env.SANDBOX_MODE = "true";
process.env.NEXT_PUBLIC_SUPABASE_URL = "";
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = "";

Test Helper for Next.js API Routes

// __tests__/helpers.ts
import { NextRequest } from "next/server";

export function createTestRequest(
  url: string,
  options?: {
    method?: string;
    body?: Record<string, unknown>;
    headers?: Record<string, string>;
    sandboxUserId?: string;
  },
): NextRequest {
  const { method = "GET", body, headers = {}, sandboxUserId } = options || {};
  const fullUrl = url.startsWith("http") ? url : `http://localhost:3000${url}`;
  const reqHeaders: Record<string, string> = { ...headers };

  if (sandboxUserId) {
    reqHeaders["x-sandbox-user-id"] = sandboxUserId;
  }

  const init: { method: string; headers: Record<string, string>; body?: string } = {
    method,
    headers: reqHeaders,
  };

  if (body) {
    init.body = JSON.stringify(body);
    reqHeaders["content-type"] = "application/json";
  }

  return new NextRequest(fullUrl, init);
}

export async function parseResponse(response: Response) {
  const json = await response.json();
  return { status: response.status, json };
}

Writing Regression Tests

The key principle: write tests for bugs that were found, not for code that works.

// __tests__/api/user/profile.test.ts
import { describe, it, expect } from "vitest";
import { createTestRequest, parseResponse } from "../../helpers";
import { GET, PATCH } from "@/app/api/user/profile/route";

// Define the contract — what fields MUST be in the response
const REQUIRED_FIELDS = [
  "id",
  "email",
  "full_name",
  "phone",
  "role",
  "created_at",
  "avatar_url",
  "notification_settings",  // ← Added after bug found it missing
];

describe("GET /api/user/profile", () => {
  it("returns all required fields", async () => {
    const req = createTestRequest("/api/user/profile");
    const res = await GET(req);
    const { status, json } = await parseResponse(res);

    expect(status).toBe(200);
    for (const field of REQUIRED_FIELDS) {
      expect(json.data).toHaveProperty(field);
    }
  });

  // Regression test — this exact bug was introduced by AI 4 times
  it("notification_settings is not undefined (BUG-R1 regression)", async () => {
    const req = createTestRequest("/api/user/profile");
    const res = await GET(req);
    const { json } = await parseResponse(res);

    expect("notification_settings" in json.data).toBe(true);
    const ns = json.data.notification_settings;
    expect(ns === null || typeof ns === "object").toBe(true);
  });
});

Testing Sandbox/Production Parity

The most common AI regression: fixing production path but forgetting sandbox path (or vice versa).

// Test that sandbox responses match the expected contract
describe("GET /api/user/messages (conversation list)", () => {
  it("includes partner_name in sandbox mode", async () => {
    const req = createTestRequest("/api/user/messages", {
      sandboxUserId: "user-001",
    });
    const res = await GET(req);
    const { json } = await parseResponse(res);

    // This caught a bug where partner_name was added
    // to production path but not sandbox path
    if (json.data.length > 0) {
      for (const conv of json.data) {
        expect("partner_name" in conv).toBe(true);
      }
    }
  });
});

Integrating Tests into Bug-Check Workflow

Custom Command Definition

<!-- .claude/commands/bug-check.md -->
# Bug Check

## Step 1: Automated Tests (mandatory, cannot skip)

Run these commands FIRST before any code review:

    npm run test       # Vitest test suite
    npm run build      # TypeScript type check + build

- If tests fail → report as highest priority bug
- If build fails → report type errors as highest priority
- Only proceed to Step 2 if both pass

## Step 2: Code Review (AI review)

1. Sandbox / production path consistency
2. API response shape matches frontend expectations
3. SELECT clause completeness
4. Error handling with rollback
5. Optimistic update race conditions

## Step 3: For each bug fixed, propose a regression test

The Workflow

User: "バグチェックして" (or "/bug-check")
  │
  ├─ Step 1: npm run test
  │   ├─ FAIL → Bug found mechanically (no AI judgment needed)
  │   └─ PASS → Continue
  │
  ├─ Step 2: npm run build
  │   ├─ FAIL → Type error found mechanically
  │   └─ PASS → Continue
  │
  ├─ Step 3: AI code review (with known blind spots in mind)
  │   └─ Findings reported
  │
  └─ Step 4: For each fix, write a regression test
      └─ Next bug-check catches if fix breaks

Common AI Regression Patterns

Pattern 1: Sandbox/Production Path Mismatch

Frequency: Most common (observed in 3 out of 4 regressions)

// FAIL: AI adds field to production path only
if (isSandboxMode()) {
  return { data: { id, email, name } };  // Missing new field
}
// Production path
return { data: { id, email, name, notification_settings } };

// PASS: Both paths must return the same shape
if (isSandboxMode()) {
  return { data: { id, email, name, notification_settings: null } };
}
return { data: { id, email, name, notification_settings } };

Test to catch it:

it("sandbox and production return same fields", async () => {
  // In test env, sandbox mode is forced ON
  const res = await GET(createTestRequest("/api/user/profile"));
  const { json } = await parseResponse(res);

  for (const field of REQUIRED_FIELDS) {
    expect(json.data).toHaveProperty(field);
  }
});

Pattern 2: SELECT Clause Omission

Frequency: Common with Supabase/Prisma when adding new columns

// FAIL: New column added to response but not to SELECT
const { data } = await supabase
  .from("users")
  .select("id, email, name")  // notification_settings not here
  .single();

return { data: { ...data, notification_settings: data.notification_settings } };
// → notification_settings is always undefined

// PASS: Use SELECT * or explicitly include new columns
const { data } = await supabase
  .from("users")
  .select("*")
  .single();

Pattern 3: Error State Leakage

Frequency: Moderate — when adding error handling to existing components

// FAIL: Error state set but old data not cleared
catch (err) {
  setError("Failed to load");
  // reservations still shows data from previous tab!
}

// PASS: Clear related state on error
catch (err) {
  setReservations([]);  // Clear stale data
  setError("Failed to load");
}

Pattern 4: Optimistic Update Without Proper Rollback

// FAIL: No rollback on failure
const handleRemove = async (id: string) => {
  setItems(prev => prev.filter(i => i.id !== id));
  await fetch(`/api/items/${id}`, { method: "DELETE" });
  // If API fails, item is gone from UI but still in DB
};

// PASS: Capture previous state and rollback on failure
const handleRemove = async (id: string) => {
  const prevItems = [...items];
  setItems(prev => prev.filter(i => i.id !== id));
  try {
    const res = await fetch(`/api/items/${id}`, { method: "DELETE" });
    if (!res.ok) throw new Error("API error");
  } catch {
    setItems(prevItems);  // Rollback
    alert("削除に失敗しました");
  }
};

Strategy: Test Where Bugs Were Found

Don't aim for 100% coverage. Instead:

Bug found in /api/user/profile     → Write test for profile API
Bug found in /api/user/messages    → Write test for messages API
Bug found in /api/user/favorites   → Write test for favorites API
No bug in /api/user/notifications  → Don't write test (yet)

Why this works with AI development:

  1. AI tends to make the same category of mistake repeatedly
  2. Bugs cluster in complex areas (auth, multi-path logic, state management)
  3. Once tested, that exact regression cannot happen again
  4. Test count grows organically with bug fixes — no wasted effort

Quick Reference

AI Regression PatternTest StrategyPriority
Sandbox/production mismatchAssert same response shape in sandbox modeHigh
SELECT clause omissionAssert all required fields in responseHigh
Error state leakageAssert state cleanup on errorMedium
Missing rollbackAssert state restored on API failureMedium
Type cast masking nullAssert field is not undefinedMedium

DO / DON'T

DO:

  • Write tests immediately after finding a bug (before fixing it if possible)
  • Test the API response shape, not the implementation
  • Run tests as the first step of every bug-check
  • Keep tests fast (< 1 second total with sandbox mode)
  • Name tests after the bug they prevent (e.g., "BUG-R1 regression")

DON'T:

  • Write tests for code that has never had a bug
  • Trust AI self-review as a substitute for automated tests
  • Skip sandbox path testing because "it's just mock data"
  • Write integration tests when unit tests suffice
  • Aim for coverage percentage — aim for regression prevention

相关 Skills(来自「测试开发」)

测试用例生成 Skills v2.0

包含 15 个子 Skill 的测试用例生成流水线,从产品说明书读取、需求分析、测试策略、正负向用例编写、质量审查到 Excel 输出。

50

Simulink HIL Modeling Standard

通用 Simulink HIL 建模、重构、迁移、评审和发布规范。用于设计 Plant/Control/IO/Bus/Fault/Monitor 架构,定义 Subsystem、Bus、ValueType、MonBus 和 Variant 接口,治理数据字典、参数、采样时间、多核任务、引用组件和初始化流程,检查 .slx/.mdl/.sldd/MATLAB Project,或为实时 HIL 模型生成合规报告、迁移方案、测试计划与发布证据。

47

ICDConverter AVIAGE Template

航空电子系统 ICD 接口控制文件(AVIAGE SYSTEMS 格式)转标准 Template 格式转换专家,适用于 ICD 转换、接口控制文件格式统一和帧结构解析。

2

ICDConverter TIU

面向航空电子 ICD Excel 文件的标准 Template 格式转换 Skill,支持协议帧分析、颜色编码识别、字段元数据索引、帧长度校验和 Excel 输出。

2

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

0

benchmark-methodology

>- Use after competitive-platform-analysis has produced a tiered competitor set. Scores each competitor across nine weighted dimensions (positioning, voice, visual craft, offer packaging, evidence, enterprise-readiness, thought leadership, pricing, client's strategic tension) with explicit 1–5 rubrics and a tension-plot. Precedes competitive-report-structure.

0

给 Agent 的安装提示词

复制下方脚本发给 AI,Agent 会自动完成下载和解压

Download and install a skill. Follow these steps EXACTLY. If any step fails, STOP and report the error.

SKILL_NAME="ai-regression-testing"
DOWNLOAD_URL="/downloads/ecc-skills/ai-regression-testing.zip"
INSTALL_CMD="Download ai-regression-testing.zip and extract it into your Agent skills directory."

STEP 1 - FIND SKILL DIRECTORY
[ -d "$HOME/.agents/skills" ] && echo "USER: $HOME/.agents/skills"
[ -d "$PWD/.agents/skills" ] && echo "PROJECT: $PWD/.agents/skills"
for d in "$HOME"/.*/skills; do [ -d "$d" ] && echo "USER: $d"; done
for d in "$PWD"/.*/skills; do [ -d "$d" ] && echo "PROJECT: $d"; done

Decide based on output (deduplicate lines first):
a) Only USER lines -> INSTALL_DIR="<that dir>/$SKILL_NAME"
b) Only PROJECT lines -> INSTALL_DIR="<that dir>/$SKILL_NAME"
c) Both USER and PROJECT -> ask the user to pick global install or project install.
d) Nothing found -> mkdir -p "$HOME/.agents/skills"; INSTALL_DIR="$HOME/.agents/skills/$SKILL_NAME"

STEP 2 - PREPARE
[ -f "$INSTALL_DIR/SKILL.md" ] && echo "EXISTS" || echo "NEW"
# If EXISTS, ask user whether to overwrite. If no, STOP.
mkdir -p "$INSTALL_DIR"

STEP 3 - DOWNLOAD
TMPDIR=$(mktemp -d)
curl -fSL -o "$TMPDIR/skill.zip" "$DOWNLOAD_URL" 2>/dev/null || wget -q -O "$TMPDIR/skill.zip" "$DOWNLOAD_URL"
# If both fail, try INSTALL_CMD as fallback: $INSTALL_CMD
# If still fail, STOP.

STEP 4 - EXTRACT & INSTALL
unzip -o "$TMPDIR/skill.zip" -d "$TMPDIR/ext" 2>/dev/null || python3 -m zipfile -e "$TMPDIR/skill.zip" "$TMPDIR/ext"
# If both fail, this is not a valid ZIP. STOP.

SKILL_PATH=$(find "$TMPDIR/ext" -maxdepth 2 -name "SKILL.md" -print | head -1)
if [ -n "$SKILL_PATH" ]; then
  cp -R "$(dirname "$SKILL_PATH")"/. "$INSTALL_DIR"/
else
  echo "FATAL: SKILL.md not found"; find "$TMPDIR/ext" -type f
fi

STEP 5 - VERIFY
head -5 "$INSTALL_DIR/SKILL.md"

DONE
Read "$INSTALL_DIR/SKILL.md" and follow its instructions to finish the user's task.
粘贴到 Claude / Cursor / Codex 等 Agent 后,会按步骤自动安装到 ~/.agents/skills/

自动安装

通过 PolarBear 协议从 ZIP 地址导入 Skill

Skill 压缩包地址
/downloads/ecc-skills/ai-regression-testing.zip

polarbear://skills/download?name=ai-regression-testing&url=%2Fdownloads%2Fecc-skills%2Fai-regression-testing.zip

手动安装

3 步完成

  1. 1

    下载 Skill 压缩包

    下载 ZIP
  2. 2

    将其解压到 Agent 的 Skills 目录

    ~/.agents/skills/ai-regression-testing/
  3. 3

    重启或重新加载 Agent,让 Skill 可用

    重启 Agent 客户端,或刷新会话后即可调用此 Skill。

来源

平台
ecc
作者
affaan-m
Slug
ai-regression-testing
在源站查看