mcpField
P
python-tdd-with-uv

python-tdd-with-uv

github.com/revitalb-port测试与质量062 次安装10 周前更新
代码仓库

关于 python-tdd-with-uv

指导 Python 开发者使用 uv 管理依赖和环境,并遵循测试优先开发流程的技能。它采用小步的 RED–GREEN–REFACTOR 循环,并使用 pytest。

主要功能

  1. 01指导纵向切片 TDD 循环
  2. 02使用 uv 管理依赖和环境
  3. 03每次改动后运行 pytest
  4. 04测试可观察行为
  5. 05仅在系统边界使用 Mock

适用场景

  1. 01使用 pytest 和 uv 开始 Python 项目
  2. 02每次通过一个测试实现行为
  3. 03运行指定测试或覆盖率测试

安装

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

$npx skills add https://github.com/revitalb-port/skills-registry-demo --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