Xpersona
R

Rust Testing Code Review

CLAWHUB · Unverified

Reviews Rust test code for unit test patterns, integration test structure, async testing, mocking approaches, and property-based testing. Covers Rust 2024 ed... Skill: Rust Testing Code Review Owner: anderskev Summary: Reviews Rust test code for unit test patterns, integration test structure, async testing, mocking approaches, and property-based testing. Covers Rust 2024 ed... Tags: latest:1.0.5 Version history: v1.0.5 | 2026-06-01T02:26:27.275Z | auto - Updated the review-verification-protocol reference in SKILL.md to use a relative path, improving integration with other sk

62
Rank
84
Safety
1.5k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.5K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:rust-testing-code-review
  1. Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-anderskev-rust-testing-code-review/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

145,268 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: rust-testing-code-review
description: Reviews Rust test code for unit test patterns, integration test structure, async testing, mocking approaches, and property-based testing. Covers Rust 2024 edition changes including async fn in traits for mocks, #[expect] lint suppression, LazyLock test fixtures, and temporary scope changes affecting test assertions. Use when reviewing _test.rs files, #[cfg(test)] modules, or test infrastructure in Rust projects. Covers tokio::test, test fixtures, and assertion patterns.
---

# Rust Testing Code Review

## Review Workflow

1. **Check Rust edition** — Note edition in `Cargo.toml` (2021 vs 2024). Edition 2024 changes temporary scoping in `if let` and tail expressions, and makes `#[expect]` the preferred lint suppression
2. **Check test organization** — Unit tests in `#[cfg(test)]` modules, integration tests in `tests/` directory
3. **Check async test setup** — `#[tokio::test]` for async tests, proper runtime configuration. Check for `async-trait` on mocks that could use native `async fn` in traits
4. **Check assertions** — Meaningful messages, correct assertion type. Review `if let` assertions for edition 2024 temporary scope changes
5. **Check test isolation** — No shared mutable state between tests, proper setup/teardown. Prefer `LazyLock` over `lazy_static!`/`once_cell` for shared fixtures
6. **Check coverage patterns** — Error paths tested, edge cases covered

## Gates (hard)

Do not advance to **Output Format** until each pass condition is satisfied (yes/no with a concrete artifact).

1. **Edition recorded** — Open the target crate’s `Cargo.toml` (or workspace `[workspace.package]` / inherited edition) and note the `edition` value. **Pass:** you can quote `edition = "…"` (or document “inherited from workspace”) before citing Rust 2024–specific behavior (`if let` / tail temporary drops, `#[expect]` vs `#[allow]` migration, native `async fn` in traits as default). If edition is not `2024`, do **not** report those items as edition-2024 regressions; at most **Informational** if still useful.
2. **`dyn` vs static async mocks** — Before suggesting native `async fn` in traits instead of `async-trait`, check whether the mock is used as `dyn Trait`. **Pass:** if `dyn` is required, you either skip that suggestion or align with **Valid Patterns** (`async-trait` still needed).
3. **Verification protocol** — **Pass:** steps from the [review-verification-protocol](../review-verification-protocol/SKILL.md) skill are done before any finding is listed (see **Before Submitting Findings**).

## Output Format

Report findings as:

```text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
```

## Quick Reference

| Issue Type | Reference |
|------------|-----------|
| Unit tests, assertions, naming, snapshots, rstest, doc tests, `#[expect]`, `LazyLock` fixtures, tail expression scope | [references/unit-tests.md](references/unit-tests.md) |
| Integra

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "rust-testing-code-review",
  "version": "1.0.5",
  "publishedAt": 1780280787275
}

references/advanced-testing.md

# Advanced Testing

## Fuzzing

Fuzzing generates semi-random inputs to find crashes. Modern fuzzers use code coverage to explore paths efficiently. Use for parsers, deserializers, codec implementations, and anything accepting untrusted input.

### cargo-fuzz with libfuzzer

```rust
#![no_main]
use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    if let Ok(s) = std::str::from_utf8(data) {
        let _ = url::Url::parse(s); // looking for panics, not checking results
    }
});
```

For complex types, derive `Arbitrary` to convert raw bytes into structured inputs:

```rust
#[derive(arbitrary::Arbitrary, Debug)]
struct FuzzInput { key: String, value: Vec<u8>, ttl: u32 }

fuzz_target!(|input: FuzzInput| {
    let mut cache = Cache::new();
    cache.insert(&input.key, &input.value, input.ttl);
});
```

**Flag when:**
- Fuzz targets exist without a `corpus/` directory (no seed inputs)
- Fuzz targets check return values instead of letting panics surface
- Parsers or protocol handlers lack fuzz targets entirely

## Property-Based Testing

Verifies invariants hold across generated inputs rather than checking specific cases.

```rust
use proptest::prelude::*;

proptest! {
    #[test]
    fn round_trip_serialization(input in any::<MyStruct>()) {
        let bytes = input.serialize();
        let decoded = MyStruct::deserialize(&bytes).unwrap();
        prop_assert_eq!(input, decoded);
    }

    #[test]
    fn sort_is_idempotent(mut v in prop::collection::vec(any::<i32>(), 0..100)) {
        v.sort();
        let sorted = v.clone();
        v.sort();
        prop_assert_eq!(v, sorted);
    }
}
```

Test stateful types with operation sequences via `Vec<Op>` where `Op` is an enum of possible actions. Testers minimize failing sequences automatically.

**Flag when:**
- proptest strategies are overly narrow (e.g., `1..5` when valid range is `0..u64::MAX`)
- Property tests check only success, not invariants (no `prop_assert!`)
- Data structures lack operation-sequence testing for stateful invariants

## Miri

Miri interprets Rust's MIR to detect undefined behavior in unsafe code. Run with `cargo +nightly miri test`.

**Catches:** Uninitialized memory reads, use-after-free, out-of-bounds pointer access, invalid exclusive references (Stacked Borrows violations), misaligned accesses.
**Misses:** Data races (use Loom), logic bugs, performance issues, FFI calls to non-Rust code.

**Flag when:**
- Crate contains `unsafe` blocks but CI does not run `cargo miri test`
- Miri is disabled for tests that exercise unsafe code paths
- Raw pointer arithmetic lacks Miri coverage

## Loom

Exhaustively tests concurrent code by exploring all thread interleavings at synchronization points.

```rust
#[test]
fn concurrent_counter() {
    loom::model(|| {
        let counter = loom::sync::Arc::new(loom::sync::atomic::AtomicUsize::new(0));
        let c1 = counter.clone();
        let t = loom::thread::spawn(move || {
            c1.fetch_add(1, Ordering::SeqCst);
       

references/concurrency-testing.md

# Concurrency Testing

Testing hand-rolled concurrent Rust requires tools that `cargo test` cannot
provide. This reference focuses on `loom`, `cargo miri`, and complementary
tools used to *review* tests for concurrent code. For the patterns being
tested, see [../../rust-code-review/references/concurrency-primitives.md],
[../../rust-code-review/references/memory-ordering.md], and
[../../rust-code-review/references/lock-free-patterns.md].

## 1. Why concurrent code needs special testing

`cargo test` runs each test in a single OS thread (or up to
`--test-threads=N` worker threads, one test per worker). Within a single
test, every `thread::spawn` produces *one* interleaving of memory
operations. That interleaving is whatever the OS scheduler happened to
produce on this run, on this CPU, under this load. The next run may
produce the same interleaving a million times in a row.

Atomic ordering bugs are non-deterministic and platform-dependent. The
canonical example is `Relaxed` used on a flag that publishes non-atomic
data: x86-64's strong memory model effectively promotes `Relaxed` to
`Release`, so the bug is invisible there. ARM64 and RISC-V reorder
freely, and the same code corrupts ~0.4% of operations on Apple M1
(Mara Bos, *Rust Atomics and Locks*, Chapter 7). "Passes on CI" is not
evidence when CI is x86-64.

The Rust compiler *does not* catch atomic ordering bugs. The book is
explicit: the "fearless concurrency" claim covers data races (the
borrow checker prevents two threads from holding `&mut T`), not memory
ordering. `Acquire`/`Release`/`SeqCst` are *contracts*; the compiler
enforces type signatures (`load(Release)` panics, `load(AcqRel)`
panics), not happens-before relationships.

Two tools change this:

- **`loom`** — a model checker. Replaces `std::sync` and `std::thread`
  with versions that explore every legal interleaving of memory
  operations, then runs each interleaving to find the one that violates
  your assertions.
- **`cargo miri`** — a MIR interpreter. Runs your test under a model
  that catches undefined behavior (uninit reads, use-after-free,
  alignment violations, data races, certain weak-memory observations,
  Stacked/Tree Borrows violations).

They are complementary, not redundant. Loom explores *which*
interleaving could fail; Miri checks *whether* a given interleaving has
UB. Neither subsumes the other.

### Review checks

- `[FILE:LINE] CONCURRENT_CODE_NO_LOOM_TESTS` — module uses raw atomics,
  `UnsafeCell`, hand-rolled `Mutex`/channel/refcount, or `unsafe impl
  Send/Sync`, and has no `#[cfg(loom)]` test harness.
- `[FILE:LINE] UNSAFE_HEAVY_NO_MIRI` — crate has non-trivial `unsafe`
  blocks touching atomics or pointer arithmetic with no `cargo +nightly
  miri test` step in CI.
- `[FILE:LINE] X86_ONLY_TEST_COVERAGE` — concurrency tests run only on
  `target_arch = "x86_64"` (no ARM64/aarch64 runner, no loom).

## 2. `loom`

`loom = "0.7"` (current stable line) is a *permutation-testing model
checker* for concurrent Ru

references/integration-tests.md

# Integration Tests

## Test Directory Structure

```
project/
├── src/
│   └── lib.rs
└── tests/
    ├── common/
    │   └── mod.rs       # shared test utilities
    ├── api_test.rs       # integration test suite
    └── workflow_test.rs  # integration test suite
```

Each file in `tests/` is compiled as a separate crate with access only to the public API.

## Shared Test Utilities

```rust
// tests/common/mod.rs
use my_crate::Config;

pub fn test_config() -> Config {
    Config {
        database_url: std::env::var("TEST_DATABASE_URL")
            .unwrap_or_else(|_| "postgres://localhost:5433/test".into()),
        ..Config::default()
    }
}

pub async fn setup_test_db(pool: &PgPool) {
    sqlx::query("TRUNCATE users, orders CASCADE")
        .execute(pool)
        .await
        .expect("failed to clean test database");
}
```

```rust
// tests/api_test.rs
mod common;

#[tokio::test]
async fn test_create_user_returns_201() {
    let config = common::test_config();
    // ...
}
```

## Async Integration Tests

```rust
#[tokio::test]
async fn test_event_bus_delivers_to_all_subscribers() {
    let (tx, _) = broadcast::channel(100);

    let mut rx1 = tx.subscribe();
    let mut rx2 = tx.subscribe();

    tx.send(Event::new("test")).unwrap();

    let event1 = rx1.recv().await.unwrap();
    let event2 = rx2.recv().await.unwrap();

    assert_eq!(event1.name, "test");
    assert_eq!(event2.name, "test");
}
```

### Multi-Threaded Tests

When testing concurrent behavior, use `#[tokio::test(flavor = "multi_thread")]`:

```rust
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_state_updates() {
    let state = Arc::new(Mutex::new(Vec::new()));
    let mut handles = Vec::new();

    for i in 0..10 {
        let state = Arc::clone(&state);
        handles.push(tokio::spawn(async move {
            let mut guard = state.lock().await;
            guard.push(i);
        }));
    }

    for handle in handles {
        handle.await.unwrap();
    }

    let guard = state.lock().await;
    assert_eq!(guard.len(), 10);
}
```

## Database Integration Tests

### Test Isolation

Each test should start with a clean state. Options:

1. **Truncate tables** — Fast, works for most cases
2. **Transaction rollback** — Test runs inside a transaction that's rolled back
3. **Separate database per test** — Most isolated, slowest

```rust
// Transaction rollback pattern
#[tokio::test]
async fn test_insert_user() {
    let pool = PgPool::connect(&test_database_url()).await.unwrap();
    let mut tx = pool.begin().await.unwrap();

    let user = sqlx::query_as!(User, "INSERT INTO users (name) VALUES ($1) RETURNING *", "Test")
        .fetch_one(&mut *tx)
        .await
        .unwrap();

    assert_eq!(user.name, "Test");
    // tx dropped here — rolls back automatically
}
```

### sqlx::test Macro

The `#[sqlx::test]` macro simplifies database test setup by automatically creating a fresh test database, running migrations, and cleaning up aft

Sponsored

Ads related to Rust Testing Code Review and adjacent AI workflows.