property-based-testing
Use when implementing serialization/parsing, data transformations, algorithms with mathematical properties, API contracts, or state machines where testing all edge cases is impractical — especially when you can describe invariants rather than specific input/output pairs.
What this skill does
# Property-Based Testing
## Overview
Instead of testing specific examples, describe **properties that must always hold** and let the framework generate hundreds of random inputs to find counterexamples. Think in invariants, not examples.
PBT complements example-based tests — it doesn't replace them. Use both.
## Property Taxonomy
| Property | Description | Signature |
|----------|-------------|-----------|
| **Round-trip** | Encode then decode returns original | `decode(encode(x)) == x` |
| **Invariant** | Property always holds regardless of input | `len(sort(xs)) == len(xs)` |
| **Idempotence** | Applying twice equals applying once | `f(f(x)) == f(x)` |
| **Commutativity** | Order doesn't matter | `f(a, b) == f(b, a)` |
| **Associativity** | Grouping doesn't matter | `f(f(a,b),c) == f(a,f(b,c))` |
| **Oracle** | Compare fast impl against trusted slow impl | `fast_sort(xs) == reference_sort(xs)` |
| **Metamorphic** | Known input transformation → known output change | `sort(xs + [min]) starts with min` |
## Where It Shines
- **Parsing & serialization** — JSON, CSV, Protobuf, custom formats (round-trip is natural)
- **Data transformation pipelines** — normalization, canonicalization, ETL logic
- **Algorithms** — sort stability, search correctness, graph traversal properties
- **API contracts** — Pydantic model validation, request/response schemas
- **State machines** — any sequence of valid transitions preserves invariants
## Where It Struggles
- UI rendering (hard to express as properties)
- Side-effectful code without good mocks
- Properties you haven't thought of (PBT only finds bugs you have a property for)
- Performance-sensitive hot paths (generates many inputs by default)
## Quick Reference by Language
| Language | Library | Install |
|----------|---------|---------|
| Python | `hypothesis` | `uv add hypothesis` |
| TypeScript/JS | `fast-check` | `npm add -D fast-check` |
| Rust | `proptest` | `cargo add proptest --dev` |
| Go | `rapid` | `go get pgregory.net/rapid` |
| Java/Scala | `jqwik` / `ScalaCheck` | Maven/sbt |
## Examples
`examples.py` in this directory contains **two runnable Hypothesis tests per property type** (14 tests total). Copy and adapt them as a starting point.
```
pytest skills/property-based-testing/examples.py # requires: uv add hypothesis pytest
```
## Hypothesis (Python) Example
```python
from hypothesis import given, settings, assume
from hypothesis import strategies as st
from myapp.models import UserSchema
import json
# Round-trip: serialize → deserialize returns original
@given(st.builds(UserSchema, name=st.text(min_size=1), age=st.integers(18, 120)))
def test_user_schema_round_trip(user):
serialized = user.model_dump_json()
restored = UserSchema.model_validate_json(serialized)
assert restored == user
# Idempotence: normalizing twice = normalizing once
@given(st.text())
def test_normalize_idempotent(s):
assert normalize(normalize(s)) == normalize(s)
# Invariant: sort preserves length and elements
@given(st.lists(st.integers()))
def test_sort_invariants(xs):
result = my_sort(xs)
assert len(result) == len(xs) # length preserved
assert sorted(result) == sorted(xs) # same elements
assert all(result[i] <= result[i+1] # ordered
for i in range(len(result)-1))
# Metamorphic: adding the minimum value produces a known first element
@given(st.lists(st.integers(), min_size=1))
def test_sort_metamorphic(xs):
minimum = min(xs)
result = my_sort(xs)
assert result[0] == minimum
# Oracle: compare new fast implementation against trusted reference
@given(st.lists(st.integers()))
def test_fast_sort_matches_reference(xs):
assert fast_sort(xs) == sorted(xs)
```
## fast-check (TypeScript) Example
```typescript
import fc from 'fast-check';
// Round-trip for a custom serializer
test('serialize/parse round-trip', () => {
fc.assert(
fc.property(fc.record({ id: fc.uuid(), value: fc.string() }), (record) => {
expect(parse(serialize(record))).toEqual(record);
})
);
});
// Commutativity: merge order doesn't matter for non-conflicting keys
test('merge is commutative for disjoint objects', () => {
fc.assert(
fc.property(
fc.record({ a: fc.integer() }),
fc.record({ b: fc.integer() }),
(left, right) => {
expect(merge(left, right)).toEqual(merge(right, left));
}
)
);
});
```
## Thinking in Properties Checklist
Before writing any data transformation or algorithm, ask:
- [ ] Does encode/decode round-trip? (`decode(encode(x)) == x`)
- [ ] Does applying this twice give the same result? (idempotence)
- [ ] What size invariants hold? (lengths, counts, set membership)
- [ ] Does order of inputs matter? Could it be commutative?
- [ ] Can I compare this against a slower trusted implementation? (oracle)
- [ ] What transformation of the input produces a predictable output change? (metamorphic)
## Common Mistakes
| Mistake | Fix |
|---------|-----|
| Writing properties that only hold for your examples | Use `assume()` to filter, not constrain strategies |
| Generating too-large inputs causing timeouts | Use `max_size` on collections; add `@settings(max_examples=50)` |
| Forgetting to shrink: hard to debug failures | Hypothesis shrinks automatically; fast-check uses `fc.property` |
| Testing implementation details, not behavior | Properties should describe what, not how |
| Abandoning PBT when first property is hard | Start with round-trip — it's almost always expressible |
## Starting Point Recipe
1. **Find the round-trip** — if you serialize/transform data, this is free
2. **List invariants** — what must always be true about the output's shape/size/type?
3. **Check idempotence** — normalization, formatting, and cleanup functions almost always have this
4. **Add an oracle** — if you're optimizing an existing implementation, diff against it
5. **Look for metamorphic relations** — "if I change input X, output changes predictably by Y"
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.