用途:这是一个面向 Python 的属性测试(property-based testing)技能,使用 Hypothesis 自动生成测试用例,用于验证代码性质并发现难以预料的边界情况。
主要能力:支持基本属性测试、显式边界用例叠加、无效输入跳过(assume)、自定义复合策略(@composite)、从类型注解生成数据(from_type),以及 NumPy、Django 等策略扩展。常见属性模式包括序列化往返、幂等性、不变量保持、与参考实现对比(oracle)。
使用方式:安装命令为 uv add --dev hypothesis pytest,可选扩展 uv add --dev hypothesis[numpy] 与 uv add --dev hypothesis[django]。可在 pyproject.toml 中配置 [tool.hypothesis] 的 max_examples、deadline,并定义 dev、ci 等 profile,通过 settings.load_profile("ci") 激活。核心装饰器有 @given、@example、@settings。CI 中可运行 pytest --hypothesis-show-statistics --hypothesis-profile=ci --hypothesis-seed=...,失败时可上传 .hypothesis/ 目录。常用调试命令包括 pytest -x --hypothesis-seed=0 -q、pytest --hypothesis-seed=42 等。
适用与限制:用 Hypothesis 的场景包括测试数学性质、需要大量有效输入、验证序列化往返、寻找不可预测边界、测试多参数 API;不宜用于测试特定已知边界、已知业务逻辑值、具体错误信息、外部系统集成和 UI 行为。非 Python 语言应改用对应语言的属性测试工具。资料中未提供收费、价格与平台信息。