proptest
proptest — property-based testing for Rust (Hypothesis-style). Generates thousands of random inputs to find counterexamples to invariants, with shrinking to minimal failing case. Critical for crypto, parsers, state machines, and finance code where edge cases matter. Includes strategies (gen functions), regression tracking, and integration with cargo test. Alternative: quickcheck (simpler API, less powerful). USE WHEN: user mentions "proptest", "property-based test", "proptest!", "Strategy", "Arbitrary", "shrink", "quickcheck", "regression file", "fuzz-light", "proptest-derive" DO NOT USE FOR: Generic Rust unit tests - use `testing/rust-testing` DO NOT USE FOR: Fuzzing with mutator (cargo-fuzz, AFL) - use bitcoin/testing/fuzz DO NOT USE FOR: KMP property testing - use `testing/kotest` (has built-in property)
What this skill does
# proptest — Property-Based Testing in Rust
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `proptest`.
## Why Property-Based Testing
Unit tests check specific examples; property tests check **invariants** (must hold for ALL inputs):
```rust
// Unit test: one example
#[test]
fn add_examples() {
assert_eq!(add(2, 3), 5);
}
// Property test: invariant for any pair
proptest! {
#[test]
fn add_commutative(a: i32, b: i32) {
prop_assert_eq!(add(a, b), add(b, a));
}
}
```
proptest generates ~256 random `(a, b)` pairs by default. If any fails, **shrinks** to minimal example. Catches edge cases (0, MAX, MIN, negative, etc.) you'd never write manually.
Critical for:
- **Crypto code** — encrypt/decrypt round-trip, signature verify
- **Parsers/serializers** — `parse(serialize(x)) == x` for any `x`
- **Finance** — total preserved across operations
- **State machines** — invariants hold across transitions
- **Wallet code** — coin selection, fee calculation, descriptor parsing
## Setup
```toml
[dev-dependencies]
proptest = "1.5"
proptest-derive = "0.5" # for #[derive(Arbitrary)]
```
## Basic Property Test
```rust
use proptest::prelude::*;
fn reverse(s: &str) -> String {
s.chars().rev().collect()
}
proptest! {
#[test]
fn reverse_twice_is_identity(s in ".*") { // any string
prop_assert_eq!(reverse(&reverse(&s)), s);
}
#[test]
fn reverse_preserves_length(s in ".*") {
prop_assert_eq!(reverse(&s).len(), s.len());
}
}
```
`s in ".*"` is a regex strategy — generates strings matching the regex. Powerful for parsers.
## Strategies — Generating Inputs
### Primitives
```rust
proptest! {
#[test]
fn test_int(x in 0i32..=100) { // bounded int
prop_assert!(x >= 0 && x <= 100);
}
#[test]
fn test_int_any(x in any::<i32>()) { // any i32
// ...
}
#[test]
fn test_uint(x: u64) { // syntactic sugar for any::<u64>()
// ...
}
#[test]
fn test_float(f in -1000.0f64..1000.0) {
// ...
}
}
```
### Strings via Regex
```rust
proptest! {
#[test]
fn test_email(email in r"[a-z]{1,10}@[a-z]{1,10}\.(com|org|net)") {
// valid-looking email strings
}
#[test]
fn test_btc_addr(addr in r"bc1[a-z0-9]{38,42}") {
// bech32-style strings
}
}
```
### Collections
```rust
use proptest::collection::vec;
proptest! {
#[test]
fn test_vec(v in vec(0u32..1000, 0..100)) { // Vec<u32>, len 0-100
prop_assert!(v.iter().all(|&x| x < 1000));
}
#[test]
fn test_btreemap(m in proptest::collection::btree_map(0u32..100, ".*", 1..10)) {
// BTreeMap<u32, String> with 1-10 entries
}
}
```
### Tuples and Combinations
```rust
proptest! {
#[test]
fn test_pair((a, b) in (0i32..100, 0i32..100)) {
prop_assert!(a >= 0 && b >= 0);
}
#[test]
fn test_either(x in prop_oneof![Just(0), Just(1), 2..=10]) {
// 1/3 chance each: 0, 1, or random in 2..=10
prop_assert!(x >= 0);
}
}
```
### Custom Strategies
```rust
fn arb_wallet() -> impl Strategy<Value = Wallet> {
(
"[a-z]{1,20}", // name
0u64..21_000_000_00000000, // balance in sats
prop::collection::vec(arb_address(), 1..10),
).prop_map(|(name, balance, addresses)| {
Wallet { name, balance, addresses }
})
}
fn arb_address() -> impl Strategy<Value = Address> {
r"bc1[a-z0-9]{38,42}".prop_map(Address)
}
proptest! {
#[test]
fn wallet_balance_matches_addresses(w in arb_wallet()) {
let computed: u64 = w.addresses.iter().map(|a| a.balance()).sum();
prop_assert_eq!(computed, w.balance);
}
}
```
### `#[derive(Arbitrary)]`
```rust
use proptest_derive::Arbitrary;
#[derive(Debug, Arbitrary)]
struct Tx {
#[proptest(strategy = "0u64..21_000_000_00000000")]
amount_sats: u64,
#[proptest(regex = "bc1[a-z0-9]{38,42}")]
address: String,
#[proptest(strategy = "1u64..1000")]
fee_rate: u64,
}
proptest! {
#[test]
fn tx_total_at_most_supply(tx: Tx) {
prop_assert!(tx.amount_sats + tx.fee_rate * 250 <= 21_000_000_00000000);
}
}
```
## Common Property Patterns
### Round-trip
```rust
proptest! {
#[test]
fn serialize_deserialize_roundtrip(w in arb_wallet()) {
let json = serde_json::to_string(&w).unwrap();
let parsed: Wallet = serde_json::from_str(&json).unwrap();
prop_assert_eq!(parsed, w);
}
#[test]
fn encrypt_decrypt_roundtrip(plaintext: Vec<u8>, key in arb_key()) {
let ciphertext = encrypt(&plaintext, &key);
let decrypted = decrypt(&ciphertext, &key).unwrap();
prop_assert_eq!(decrypted, plaintext);
}
}
```
### Invariants
```rust
proptest! {
#[test]
fn coin_selection_total_at_least_target(
utxos in vec(0u64..1_000_000, 1..50),
target in 1u64..500_000,
) {
prop_assume!(utxos.iter().sum::<u64>() >= target); // skip impossible cases
let selected = select_coins(&utxos, target);
let total: u64 = selected.iter().sum();
prop_assert!(total >= target);
}
}
```
`prop_assume!` skips invalid inputs without failing the test.
### Equivalence
```rust
proptest! {
#[test]
fn fast_sort_equals_std_sort(mut v: Vec<i32>) {
let mut std_sorted = v.clone();
std_sorted.sort();
my_fast_sort(&mut v);
prop_assert_eq!(v, std_sorted);
}
}
```
### Idempotence
```rust
proptest! {
#[test]
fn normalize_is_idempotent(s in ".*") {
let once = normalize(&s);
let twice = normalize(&once);
prop_assert_eq!(once, twice);
}
}
```
## Shrinking
When a property fails, proptest tries to find the **minimal failing input**. Output:
```
proptest: TestCaseError: Property failed at "src/wallet.rs:42:9"
proptest: ... Original failure: input: "abcdef", balance: 1000000
proptest: ... Shrunk to: input: "", balance: 0
```
Shrunk values are easier to debug. proptest auto-shrinks integers toward 0, strings toward empty, collections toward shorter, etc.
## Regression Files
When proptest finds a failure, it saves the input to `proptest-regressions/<test_name>.txt`. On next run, it **always tests these inputs first** — ensures the fix holds.
```
proptest-regressions/wallet.txt:
# Seeds for failure cases proptest has generated in the past.
xx 6e7b3a92 1000 "" 0
```
Commit this file to git — provides regression suite for known bugs.
## Configuration
```rust
proptest! {
#![proptest_config(ProptestConfig {
cases: 1000, // default 256
max_shrink_iters: 10000,
timeout: 5000, // ms per test case
.. ProptestConfig::default()
})]
#[test]
fn slow_property(x: u64) { /* ... */ }
}
```
For CI: increase `cases` for thorough coverage, decrease for speed.
## Stateful Property Tests
For state machines (e.g., wallet operations):
```rust
use proptest_state_machine::*;
#[derive(Debug, Clone)]
enum Op {
Deposit(u64),
Withdraw(u64),
GetBalance,
}
struct WalletStateMachine;
impl StateMachineTest for WalletStateMachine {
type SystemUnderTest = Wallet;
type Reference = u64; // model: just a balance
fn init_test(_ref_state: &Self::Reference) -> Self::SystemUnderTest {
Wallet::new()
}
fn apply(state: Self::SystemUnderTest, _: &Self::Reference, transition: Self::Transition)
-> Self::SystemUnderTest
{
match transition {
Op::Deposit(amount) => state.deposit(amount),
Op::Withdraw(amount) => state.withdraw(amount),
Op::GetBalance => state,
}
}
fn check_invariants(state: &Self::SystemUnderTest, ref_state: &Self::Reference) {
assert_eq!(state.balance(), *ref_state);
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.