mcpField
T
tdd

tdd

github.com/prowler-cloud测试与质量15.1k58 次安装今天更新
代码仓库

关于 tdd

tdd 是面向 Prowler UI、SDK 和 API 开发的测试驱动开发技能,指导开发者按 RED、GREEN、REFACTOR 循环工作,并针对不同技术栈提供测试流程。

主要功能

  1. 01遵循 RED、GREEN、REFACTOR 循环
  2. 02先评估现有测试与覆盖率
  3. 03针对新功能和缺陷编写测试
  4. 04逐步扩展测试以验证真实逻辑
  5. 05提供 UI、SDK 和 API 测试命令

适用场景

  1. 01为 UI 新功能补充 Vitest 测试
  2. 02复现并修复 SDK 缺陷
  3. 03在 API 重构前建立测试基线

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/prowler-cloud/prowler --skill tdd

安装后在 Claude Code 中输入/tdd确认已加载。

详细介绍

TDD 循环(强制)

+-----------------------------------------+
|  RED -> GREEN -> REFACTOR               |
|     ^                        |          |
|     +------------------------+          |
+-----------------------------------------+

问题不是“要不要编写测试?”,而是“需要哪些测试?”


TDD 三定律

  1. 在有失败的测试之前,不编写生产代码
  2. 测试只写到足以失败为止
  3. 代码只写到足以通过为止

确定技术栈

开始之前,先确定你正在处理哪个组件:

所在目录技术栈测试运行器测试模式详情
ui/TypeScript / ReactVitest + RTL*.test.{ts,tsx}(同目录)参见 vitest 技能
prowler/Pythonpytest + mototests/ 中的 *_test.py(后缀)参见 prowler-test-sdk 技能
api/Python / Djangopytest + djangoapi/src/backend/**/tests/ 中的 test_*.py(前缀)参见 prowler-test-api 技能

阶段 0:评估(始终首先进行)

编写任何代码之前:

UI(ui/)
# 1. Find existing tests
fd "*.test.tsx" ui/components/feature/

# 2. Check coverage
pnpm test:coverage -- components/feature/

# 3. Read existing tests
SDK(prowler/)
# 1. Find existing tests
fd "*_test.py" tests/providers/aws/services/ec2/

# 2. Run specific test
uv run pytest tests/providers/aws/services/ec2/ec2_ami_public/ -v

# 3. Read existing tests
API(api/)
# 1. Find existing tests
fd "test_*.py" api/src/backend/api/tests/

# 2. Run specific test
uv run pytest api/src/backend/api/tests/test_models.py -v

# 3. Read existing tests
决策树(所有技术栈)
+------------------------------------------+
|     Does test file exist for this code?  |
+----------+-----------------------+-------+
           | NO                    | YES
           v                       v
+------------------+    +------------------+
| CREATE test file |    | Check coverage   |
| -> Phase 1: RED  |    | for your change  |
+------------------+    +--------+---------+
                                 |
                        +--------+--------+
                        | Missing cases?  |
                        +---+---------+---+
                            | YES     | NO
                            v         v
                    +-----------+ +-----------+
                    | ADD tests | | Proceed   |
                    | Phase 1   | | Phase 2   |
                    +-----------+ +-----------+

阶段 1:RED——编写失败的测试

新功能
UI(Vitest)
describe("PriceCalculator", () => {
  it("should return 0 for quantities below threshold", () => {
    // Given
    const quantity = 3;

    // When
    const result = calculateDiscount(quantity);

    // Then
    expect(result).toBe(0);
  });
});
SDK(pytest)
class Test_ec2_ami_public:
    @mock_aws
    def test_no_public_amis(self):
        # Given - No AMIs exist
        aws_provider = set_mocked_aws_provider([AWS_REGION_US_EAST_1])

        with mock.patch("prowler...ec2_service", new=EC2(aws_provider)):
            from prowler...ec2_ami_public import ec2_ami_public

            # When
            check = ec2_ami_public()
            result = check.execute()

            # Then
            assert len(result) == 0
API(pytest-django)
@pytest.mark.django_db
class TestResourceModel:
    def test_create_resource_with_tags(self, aws_provider):
        # Given
        provider = aws_provider
        tenant_id = provider.tenant_id

        # When
        resource = Resource.objects.create(
            tenant_id=tenant_id, provider=provider,
            uid="arn:aws:ec2:us-east-1:123456789:instance/i-1234",
            name="test", region="us-east-1", service="ec2", type="instance",
        )

        # Then
        assert resource.uid == "arn:aws:ec2:us-east-1:123456789:instance/i-1234"

运行 -> 必须失败: 测试引用了尚不存在的代码。

修复 Bug

先编写一个复现 Bug 的测试:

UI: expect(() => render(<DatePicker value={null} />)).not.toThrow();

SDK: assert result[0].status == "FAIL" # Currently returns PASS incorrectly

API: assert response.status_code == 403 # Currently returns 200

运行 -> 应当失败(复现 Bug)。

重构

重构前,记录当前的所有行为:

# Any stack: run ALL existing tests, they should PASS
# This is your safety net - if any fail after refactoring, you broke something

运行 -> 所有测试都应通过(基线)。


阶段 2:GREEN——编写最少代码

编写最少量的代码,让测试通过。第一个测试中可以使用硬编码。

UI:

// Test expects calculateDiscount(100, 10) === 10
function calculateDiscount() {
  return 10; // FAKE IT - hardcoded is valid for first test
}

Python(SDK/API):

# Test expects check.execute() returns 0 results
def execute(self):
    return []  # FAKE IT - hardcoded is valid for first test

测试通过了,但还没有结束……


阶段 3:三角验证(至关重要)

一个测试允许造假。多个测试会迫使你实现真正的逻辑。

添加输入不同、能让硬编码值失效的测试:

场景必需?
正常路径是
零值/空值是
边界值是
不同的有效输入是(打破造假)
错误情况是

UI:

it("should calculate 10% discount", () => {
  expect(calculateDiscount(100, 10)).toBe(10);
});

// ADD - breaks the fake:
it("should calculate 15% on 200", () => {
  expect(calculateDiscount(200, 15)).toBe(30);
});

it("should return 0 for 0% rate", () => {
  expect(calculateDiscount(100, 0)).toBe(0);
});

Python:

def test_single_public_ami(self):
    # Different input -> breaks hardcoded empty list
    assert len(result) == 1
    assert result[0].status == "FAIL"

def test_private_ami(self):
    assert result[0].status == "PASS"

现在造假的实现会失效 -> 必须实现真正的逻辑。


阶段 4:重构

测试通过 -> 在不改变行为的前提下提升代码质量。

  • 提取函数/方法
  • 改进命名
  • 添加类型/验证
  • 减少重复

每次更改后都运行测试 -> 必须保持通过。


快速参考

+------------------------------------------------+
|                 TDD WORKFLOW                    |
+------------------------------------------------+
| 0. ASSESS: What tests exist? What's missing?   |
|                                                |
| 1. RED: Write ONE failing test                 |
|    +-- Run -> Must fail with clear error       |
|                                                |
| 2. GREEN: Write MINIMUM code to pass           |
|    +-- Fake It is valid for first test         |
|                                                |
| 3. TRIANGULATE: Add tests that break the fake  |
|    +-- Different inputs, edge cases            |
|                                                |
| 4. REFACTOR: Improve with confidence           |
|    +-- Tests stay green throughout             |
|                                                |
| 5. REPEAT: Next behavior/requirement           |
+------------------------------------------------+

反模式(绝对不要做)

# ANY language:

# 1. Code first, tests after
def new_feature(): ...  # Then writing tests = USELESS

# 2. Skip triangulation
# Single test allows faking forever

# 3. Test implementation details
assert component.state.is_loading == True   # BAD - test behavior, not internals
assert mock_service.call_count == 3         # BAD - brittle coupling

# 4. All tests at once before any code
# Write ONE test, make it pass, THEN write the next

# 5. Giant test methods
# Each test should verify ONE behavior

各技术栈的命令

UI(ui/)
pnpm test                           # Watch mode
pnpm test:run                       # Single run (CI)
pnpm test:coverage                  # Coverage report
pnpm test ComponentName             # Filter by name
SDK(prowler/)
uv run pytest tests/path/ -v              # Run specific tests
uv run pytest tests/path/ -v -k "test_name"  # Filter by name
uv run pytest -n auto tests/              # Parallel run
uv run pytest --cov=./prowler tests/      # Coverage
API(api/)
uv run pytest -x --tb=short                           # Run all (stop on first fail)
uv run pytest api/src/backend/api/tests/test_file.py     # Specific file
uv run pytest -k "test_name" -v                       # Filter by name

评论

支持 Markdown