mcpField
P
python-tdd-with-uv

python-tdd-with-uv

github.com/spencerpauly测试与质量868414 次安装13 周前更新
代码仓库

关于 python-tdd-with-uv

一项面向 Python 项目的测试驱动开发技能,使用 uv 管理依赖并运行 pytest,强调小步进行红绿重构循环和针对行为编写测试。

主要功能

  1. 01使用 uv 初始化 Python 项目
  2. 02每轮只编写一个失败测试
  3. 03遵循红绿重构流程
  4. 04通过 uv 运行 pytest
  5. 05测试可观察到的行为

适用场景

  1. 01在 Python 项目中开始 TDD
  2. 02以小步方式添加并测试功能
  3. 03运行指定或完整 pytest 测试
  4. 04使用 uv 管理项目依赖

安装

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

$npx skills add https://github.com/spencerpauly/awesome-cursor-skills --skill python-tdd-with-uv

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

详细介绍

使用 uv 进行 Python TDD

使用 uv 快速管理依赖和环境,采用测试优先的方式编写 Python 代码。

设置项目

  1. 检查是否已安装 uv:uv --version
  2. 如果项目没有 pyproject.toml,请初始化:
    uv init
    
  3. 将 pytest 添加为开发依赖:
    uv add --dev pytest pytest-cov
    
  4. 确认测试运行器正常工作:
    uv run pytest --co
    

TDD 工作流 — 垂直切片

以小步循环推进。一次最多只编写一个失败的测试。

规划阶段

编写代码前,请回答:

  1. 需要对接口进行哪些更改?(函数、类、API)
  2. 哪些行为最重要?(优先处理关键路径)
  3. 能否针对可测试性进行设计?(注入依赖、避免全局状态)
循环
RED   → Write ONE failing test for the next behavior
GREEN → Write the MINIMUM code to make it pass
REFACTOR → Clean up without changing behavior
REPEAT

规则:

  • 必须先有失败的测试,才能编写实现代码
  • 一次最多只编写一个失败的测试
  • 每次更改后都运行 uv run pytest
  • 测试必须断言可观察到的行为,而非实现细节
  • 仅在系统边界(I/O、网络、时钟)使用 Mock
测试文件结构
# tests/test_<module>.py

class TestFeatureName:
    """Group related behaviors."""

    def test_does_expected_thing_when_given_input(self):
        result = function_under_test(input_value)
        assert result == expected

    def test_raises_when_given_invalid_input(self):
        with pytest.raises(ValueError):
            function_under_test(bad_input)
运行测试
uv run pytest                      # all tests
uv run pytest tests/test_foo.py    # single file
uv run pytest -k "test_name"       # by name pattern
uv run pytest --cov=src            # with coverage
uv run pytest -x                   # stop on first failure

uv 基础知识

uv add <package>           # add dependency
uv add --dev <package>     # add dev dependency
uv remove <package>        # remove dependency
uv sync                    # sync environment from lockfile
uv run <command>           # run in managed environment
uv lock                    # regenerate lockfile
  • 始终使用 uv run 执行命令,切勿手动激活虚拟环境
  • 同时提交 pyproject.toml 和 uv.lock

参考资料

评论

支持 Markdown