1. Add moonpool
Add the two crates to the [dev-dependencies] of your crate. The default features ofmoonpool give the simulator and the Tokio providers.
[dev-dependencies]
moonpool = "0.8"
async-trait = "0.1"2. Write the first test
Put this file in tests/chaos.rs. Server is the system under test: aProcess that the simulator boots again after each reboot. Client is the test driver: aWorkload that survives the reboots and judges the run. The builder runs ten seeds with network faults on.
use std::time::Duration;
use async_trait::async_trait;
use moonpool::prelude::*;
use moonpool::{Chaos, ChaosMode, SimulationResult, assert_always, assert_sometimes};
/// The system under test. A fresh instance boots on every (re)start.
struct Server;
#[async_trait]
impl Process for Server {
fn name(&self) -> &str {
"server"
}
async fn run(&mut self, ctx: &SimContext) -> SimulationResult<()> {
let listener = ctx.network().bind(ctx.my_ip()).await?;
loop {
// The deterministic select!: the branch order comes from the seed.
moonpool::select! {
accepted = listener.accept() => drop(accepted),
() = ctx.shutdown().cancelled() => return Ok(()),
}
}
}
}
/// The test driver. It survives server reboots and judges the run.
struct Client;
#[async_trait]
impl Workload for Client {
fn name(&self) -> &str {
"client"
}
async fn run(&mut self, ctx: &SimContext) -> SimulationResult<()> {
let servers = ctx.topology().all_process_ips();
assert_always!(servers.len() == 1, "one server process per seed");
for _ in 0..20 {
// Bound every step with simulated time, so no fault wedges the client.
let attempt = ctx
.time()
.timeout(Duration::from_millis(500), ctx.network().connect(&servers[0]))
.await;
assert_sometimes!(matches!(attempt, Ok(Ok(_))), "client connects");
let _ = ctx.time().sleep(Duration::from_millis(50)).await;
}
Ok(())
}
}
#[test]
fn server_accepts_under_chaos() -> Result<(), moonpool::SimulationError> {
let report = SimulationBuilder::new()
.processes(1, || Box::new(Server))
.workload(Client)
.enable_chaos([Chaos::Network(ChaosMode::Swarm)])
.set_iterations(10)
.run()?;
report.eprint();
assert_eq!(report.failed_runs, 0);
Ok(())
}3. Run it
cargo test --test chaos -- --nocaptureTen seeds run in milliseconds of wall time. Each seed simulates a few seconds: the clock jumps to the next event, so no test waits.
4. Read the report
report.eprint() writes the report to stderr. This is one real run. The seeds and the wall times change from run to run.
━━━ Simulation Report ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
10 iterations 10 passed 0 failed ✓ 100.0%
Base seed 1794411774351454324 (replay the run with .base_seed(1794411774351454324))
Wall Time 3ms avg 35ms total
Sim Time 2.01s avg
Events 100 avg
━━━ Assertions (5) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ always "one server process per seed" 10 pass 0 fail
✓ sometimes "client connects" 193 / 200 (96.5%)
✓ reachable "network: a connect is refused" 1 / 1 (100.0%)
✓ reachable "network: an asymmetric receive partit..." 1 / 1 (100.0%)
✓ reachable "network: interface clogged" 4 / 4 (100.0%)
━━━ Seeds ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#1 seed=16680885789437997585 4ms 2.38s sim 104 events
#2 seed=12518977033248852711 3ms 1.50s sim 102 events
#3 seed=15604186992324754263 3ms 2.33s sim 103 events
…- ✓ 100.0%: no seed failed, panicked or stopped.
- Base seed: the seed of the whole campaign.
.base_seed(…)runs the same ten seeds again. - always with 0 fail: the invariant held each time.
- sometimes and reachable with ✓: the rare path fired at least once. The
network:rows come from the simulator: they show that the faults happened.
5. Replay a failing seed
When a seed fails, the report names it under Faulty seeds and prints the line to replay it. Run that seed alone:
SimulationBuilder::new()
.processes(1, || Box::new(Server))
.workload(Client)
.enable_chaos([Chaos::Network(ChaosMode::Swarm)])
.set_debug_seeds(vec![7891])
.set_iterations(1)
.run()?;The same seed gives the same run: the same order of the tasks, the same latency for each message, the same faults. Raise the log level and read the trace back from the first wrong event.
Next
- Your First Simulation builds a test step by step.
- Running and Observing explains each part of the report.
- Debugging a Failing Seed goes from a red seed to the bug.
- Using Providers in Production runs the same code on Tokio.