Saltar a contenido

Week 20 - Testing Strategy: Unit, Property, Fuzz, Miri, Integration

20.1 Conceptual Core

  • A production Rust codebase has five test surfaces:
  • Unit (#[test] in mod tests)-fast, in-crate, mock-free where possible.
  • Integration (tests/ directory)-public-API only, one binary per file.
  • Property-based (proptest, quickcheck)-invariants, not examples.
  • Fuzzing (cargo-fuzz with libFuzzer, or afl.rs)-adversarial inputs.
  • Model checking / Miri-concurrency interleavings and UB detection.
  • Each surface answers a different question. Skipping one leaves a class of bugs uncovered.

20.2 Mechanical Detail

  • proptest: shrinking-aware property testing. proptest! { #[test] fn round_trip(x in 0..1000u32) { ... } }. Use it for serialization round-trips, parsers, sort/search.
  • cargo-fuzz: cargo +nightly fuzz init && cargo +nightly fuzz add my_target. Each target is a fuzz_target!(|data: &[u8]| { ... }). Run continuously on a CI runner, store the corpus.
  • arbitrary crate: derive Arbitrary for your domain types so fuzz inputs are well-typed.
  • insta for snapshot tests: golden-file testing for proc-macro expansions, Debug outputs, serialized formats.
  • testcontainers: spin up Postgres/Kafka/Redis from inside #[tokio::test]. The right tool for adapter integration tests in a hexagonal codebase.

20.3 Lab-"Test-Pyramid the URL Shortener"

  • Property-test the alias-generation function (idempotent, collision-resistant under birthday-bound assumptions).
  • Fuzz the public HTTP handlers via the axum::Router directly (no socket).
  • Integration-test the Postgres adapter against a real Postgres in testcontainers.
  • Snapshot-test the OpenAPI spec with insta.
  • Achieve 90%+ coverage per cargo-llvm-cov.

20.4 Idiomatic & Clippy Drill

  • clippy::should_panic_without_expect, clippy::panic_in_result_fn, clippy::tests_outside_test_module.

20.5 Production Hardening Slice

  • Add a continuous-fuzzing job (e.g., on a scheduled GitHub Action). Persist the corpus as an artifact. Any new crash file is a P0 issue; document the triage flow in SECURITY.md.

Month 5 Capstone Deliverable

A production-shaped url-shortener-prod/ workspace: - Hexagonal layout with adapter isolation enforced by cargo deny. - Zero-copy parser on the wire. - tracing + Prometheus + Jaeger. - Five test surfaces wired into CI. - A one-page RUNBOOK.md describing alarms, dashboards, and rollback procedures.

This is the first artifact in the curriculum that resembles a real production service. Treat it as your portfolio piece.

Comments