property-based-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseProperty-Based Testing
基于属性的测试
Expert knowledge for property-based testing - automatically generating test cases to verify code properties rather than testing specific examples.
关于基于属性的测试的专业知识——自动生成测试用例以验证代码属性,而非测试特定示例。
When to Use This Skill
何时使用此技能
| Use this skill when... | Use another skill instead when... |
|---|---|
| Testing mathematical properties (commutative, associative) | Writing specific example-based unit tests |
| Testing encode/decode roundtrips | Setting up test runner configuration |
| Finding edge cases automatically | Doing E2E browser testing |
| Validating data transformations and invariants | Analyzing test quality or smells |
| Testing API contracts with generated data | Running mutation testing |
| 适合使用此技能的场景... | 适合使用其他技能的场景... |
|---|---|
| 测试数学属性(交换律、结合律) | 编写基于特定示例的单元测试 |
| 测试编码/解码往返流程 | 配置测试运行器 |
| 自动发现边界情况 | 进行端到端浏览器测试 |
| 验证数据转换与不变量 | 分析测试质量或测试坏味道 |
| 使用生成的数据测试API契约 | 运行变异测试 |
Core Expertise
核心专业知识
Property-Based Testing Concept
- Traditional testing: Test specific examples
- Property-based testing: Test properties that should hold for all inputs
- Generators: Automatically create diverse test inputs
- Shrinking: Minimize failing cases to simplest example
- Coverage: Explore edge cases humans might miss
When to Use Property-Based Testing
- Mathematical operations (commutative, associative properties)
- Encoders/decoders (roundtrip properties)
- Parsers and serializers
- Data transformations
- API contracts
- Invariants and constraints
基于属性的测试概念
- 传统测试:测试特定示例
- 基于属性的测试:测试对所有输入都应成立的属性
- 生成器:自动创建多样化的测试输入
- 简化(Shrinking):将失败案例简化为最简单的示例
- 覆盖范围:探索人类可能遗漏的边界情况
何时使用基于属性的测试
- 数学运算(交换律、结合律等属性)
- 编码器/解码器(往返属性)
- 解析器与序列化器
- 数据转换
- API契约
- 不变量与约束
TypeScript/JavaScript (fast-check)
TypeScript/JavaScript(fast-check)
Installation
安装
bash
undefinedbash
undefinedUsing Bun
Using Bun
bun add -d fast-check
bun add -d fast-check
Using npm
Using npm
npm install -D fast-check
undefinednpm install -D fast-check
undefinedBasic Example
基础示例
typescript
import { test } from 'vitest'
import * as fc from 'fast-check'
// Property-based test
test('reverse twice returns original - property based', () => {
fc.assert(
fc.property(
fc.array(fc.integer()), // Generate random arrays of integers
(arr) => {
expect(reverse(reverse(arr))).toEqual(arr)
}
)
)
})
// fast-check automatically generates 100s of test cases!typescript
import { test } from 'vitest'
import * as fc from 'fast-check'
// Property-based test
test('reverse twice returns original - property based', () => {
fc.assert(
fc.property(
fc.array(fc.integer()), // Generate random arrays of integers
(arr) => {
expect(reverse(reverse(arr))).toEqual(arr)
}
)
)
})
// fast-check automatically generates 100s of test cases!Key Generators (Quick Reference)
常用生成器速查
| Generator | Description |
|---|---|
| Any integer (with optional min/max) |
| Natural numbers (>= 0) |
| Floating-point numbers |
| Any string (with optional length) |
| Email format strings |
| Arrays of arbitrary type |
| Object with typed fields |
| Boolean values |
| Pick from options |
| Fixed-size tuples |
| Union types |
| Value or null |
| Date objects |
| 生成器 | 描述 |
|---|---|
| 任意整数(可指定最小值/最大值) |
| 自然数(>= 0) |
| 浮点数 |
| 任意字符串(可指定长度) |
| 邮箱格式字符串 |
| 任意类型的数组 |
| 带类型字段的对象 |
| 布尔值 |
| 从选项中选择 |
| 固定大小的元组 |
| 联合类型 |
| 值或null |
| 日期对象 |
Common Properties to Test
可测试的常见属性
| Property | Pattern | Example |
|---|---|---|
| Roundtrip | | encode/decode, serialize/parse |
| Idempotence | | sort, normalize, format |
| Commutativity | | add, merge, union |
| Associativity | | add, concat |
| Identity | | multiply by 1, add 0 |
| Inverse | | encrypt/decrypt |
| 属性 | 模式 | 示例 |
|---|---|---|
| 往返 | | 编码/解码、序列化/解析 |
| 幂等性 | | 排序、标准化、格式化 |
| 交换律 | | 加法、合并、联合 |
| 结合律 | | 加法、拼接 |
| 单位元 | | 乘以1、加0 |
| 逆运算 | | 加密/解密 |
Configuration
配置
typescript
fc.assert(property, {
numRuns: 1000, // Run 1000 tests (default: 100)
seed: 42, // Reproducible tests
endOnFailure: true, // Stop after first failure
})typescript
fc.assert(property, {
numRuns: 1000, // Run 1000 tests (default: 100)
seed: 42, // Reproducible tests
endOnFailure: true, // Stop after first failure
})Preconditions
前置条件
typescript
fc.pre(b !== 0) // Skip cases where b is 0typescript
fc.pre(b !== 0) // Skip cases where b is 0Python (Hypothesis)
Python(Hypothesis)
Installation
安装
bash
undefinedbash
undefinedUsing uv
Using uv
uv add --dev hypothesis
uv add --dev hypothesis
Using pip
Using pip
pip install hypothesis
undefinedpip install hypothesis
undefinedBasic Example
基础示例
python
from hypothesis import given, strategies as st
@given(st.lists(st.integers()))
def test_reverse_twice_property(arr):
assert reverse(reverse(arr)) == arr
# Hypothesis automatically generates 100s of test cases!python
from hypothesis import given, strategies as st
@given(st.lists(st.integers()))
def test_reverse_twice_property(arr):
assert reverse(reverse(arr)) == arr
# Hypothesis automatically generates 100s of test cases!Key Strategies (Quick Reference)
常用策略速查
| Strategy | Description |
|---|---|
| Any integer (with optional bounds) |
| Floating-point numbers |
| Any string (with optional size) |
| Byte strings |
| Lists of given strategy |
| Unique value sets |
| Dictionaries |
| Boolean values |
| Pick from options |
| Fixed-size tuples |
| Union types |
| Date/time values |
| Build objects from strategies |
| 策略 | 描述 |
|---|---|
| 任意整数(可指定范围) |
| 浮点数 |
| 任意字符串(可指定大小) |
| 字节字符串 |
| 基于给定策略的列表 |
| 唯一值集合 |
| 字典 |
| 布尔值 |
| 从选项中选择 |
| 固定大小的元组 |
| 联合类型 |
| 日期/时间值 |
| 从策略构建对象 |
Configuration
配置
python
from hypothesis import given, settings, strategies as st
@settings(max_examples=1000, deadline=None)
@given(st.lists(st.integers()))
def test_with_custom_settings(arr):
assert sort(arr) == sorted(arr)python
from hypothesis import given, settings, strategies as st
@settings(max_examples=1000, deadline=None)
@given(st.lists(st.integers()))
def test_with_custom_settings(arr):
assert sort(arr) == sorted(arr)Assumptions
假设条件
python
from hypothesis import assume
assume(b != 0) # Skip cases where b is 0python
from hypothesis import assume
assume(b != 0) # Skip cases where b is 0Stateful Testing
有状态测试
Hypothesis supports stateful testing via for testing sequences of operations against invariants.
RuleBasedStateMachineHypothesis支持通过进行有状态测试,用于针对不变量测试操作序列。
RuleBasedStateMachineAgentic Optimizations
智能优化
| Context | Command |
|---|---|
| Quick TS test | |
| Quick Python test | |
| CI TS test | |
| CI Python test | |
| Reproducible | |
| Fast iteration | |
For detailed examples, advanced patterns, and best practices, see REFERENCE.md.
| 场景 | 命令 |
|---|---|
| 快速TS测试 | |
| 快速Python测试 | |
| CI环境TS测试 | |
| CI环境Python测试 | |
| 可复现测试 | |
| 快速迭代 | |
有关详细示例、高级模式和最佳实践,请参阅REFERENCE.md。
See Also
另请参阅
- - Unit testing framework
vitest-testing - - Python pytest testing
python-testing - - Detecting test smells
test-quality-analysis - - Validate test effectiveness
mutation-testing
- - 单元测试框架
vitest-testing - - Python pytest测试
python-testing - - 检测测试坏味道
test-quality-analysis - - 验证测试有效性
mutation-testing
References
参考资料
- fast-check: https://fast-check.dev/
- Hypothesis: https://hypothesis.readthedocs.io/
- Property-Based Testing: https://fsharpforfunandprofit.com/posts/property-based-testing/
- fast-check: https://fast-check.dev/
- Hypothesis: https://hypothesis.readthedocs.io/
- Property-Based Testing: https://fsharpforfunandprofit.com/posts/property-based-testing/