Перейти к основному содержимому
Эта страница ещё не переведена

Ниже показан английский оригинал.

Testing a compio app

testing::compio::TestApp runs a compio service's app on the test's own compio runtime, with every broker connected in process. The test hands it the production app, unchanged, and drives it with the calls a tokio test makes: broker, settle, advance and shutdown. The logger the app selects with .logger(..) is applied at start, so a test reads the diagnostics the production app emits. The test is a plain #[test] that blocks on one future of a compio::runtime::Runtime.

The harness runs the app as the one core of the test's runtime: it drives every subscription and worker there, a threads(n) mount as n workers of it, and does not reproduce the cores, the pinning or the hand-off between cores. Core::current() is core 0 of 1 in a test.

One TestApp runs at a time on a thread, because the clock it holds is one per thread.

Time​

The harness holds the runner's virtual clock from start until it is dropped. Retries, batch deadlines and ruststream::runtime::compio::time::sleep wait until advance moves the clock, and the app then handles what fell due. A handler that calls compio::time::sleep directly waits on compio's own timers, and advance does not reach it.

settle returns once everything delivered is handled, up to what waits on the clock. A publish through a broker handle settles on its own.

Example​

A service with one handler, and the test that publishes to it and reads what it received:

/// Acknowledges every reading.
#[subscriber(LocalMemorySource::new("readings"))]
async fn on_reading(reading: &Reading<'_>) -> HandlerOutcome {
let _ = reading.0;
HandlerOutcome::ack()
}

fn app() -> RustStream {
RustStream::new(AppInfo::new("readings", "0.1.0"))
.with_broker(Bus::new(), |b| b.include(on_reading))
}
#[test]
fn a_published_reading_is_handled_and_acknowledged() -> Result<(), Box<dyn Error>> {
Runtime::new()?.block_on(async {
let tb = TestApp::start(app()).await?;
tb.broker::<Bus>().message(&Sent(b"21")).publish().await?;

tb.broker::<Bus>()
.subscriber("readings")
.assert_called_once()
.with_raw(b"21")
.settled(HandlerOutcome::ack());
tb.shutdown().await?;
Ok(())
})
}

Replies​

A reply is recorded on its destination, and published::<M>(name) reads it:

/// The alarm a full tank raises.
#[derive(Outgoing, Serialized)]
#[outgoing(name = "alarms")]
struct Alarm(Vec<u8>);

/// The slot alarms leave through.
#[derive(OutSlot)]
#[publishes(Alarm)]
struct Alarms;

/// Shows every level, in percent.
#[subscriber(LocalMemorySource::new("levels"), reply)]
async fn show(level: &Level<'_>) -> Shown {
Shown([level.0, b" %"].concat())
}

/// Raises an alarm for every level.
#[subscriber(LocalMemorySource::new("tank"))]
async fn watch(level: &Level<'_>, Out(alarms): Out<impl Publisher, Alarms>) -> HandlerOutcome {
match alarms.message(&Alarm(level.0.to_vec())).publish().await {
Ok(()) => HandlerOutcome::ack(),
Err(_) => HandlerOutcome::retry(),
}
}

fn app() -> RustStream {
RustStream::new(AppInfo::new("tank", "0.1.0")).with_broker(Bus::new(), |b| {
b.include(show)
.out_reply(LocalMemoryPublish)
.include(watch)
.out(Alarms, LocalMemoryPublish)
})
}
#[test]
fn a_reply_reaches_its_destination() -> Result<(), Box<dyn Error>> {
Runtime::new()?.block_on(async {
let tb = TestApp::start(app()).await?;
tb.broker::<Bus>()
.message(&Sent(b"80"))
.to("levels")
.publish()
.await?;

tb.broker::<Bus>()
.published::<()>("display")
.assert_called_once()
.with_raw(b"80 %");
tb.shutdown().await?;
Ok(())
})
}

Out slots​

tb.out::<M>() opens the record of the Out slot marked M, as the out page describes:

#[test]
fn a_slot_publish_is_read_back_through_the_slot() -> Result<(), Box<dyn Error>> {
Runtime::new()?.block_on(async {
let tb = TestApp::start(app()).await?;
tb.broker::<Bus>()
.message(&Sent(b"full"))
.to("tank")
.publish()
.await?;

tb.out::<Alarms>().assert_called_once().with_raw(b"full");
tb.shutdown().await?;
Ok(())
})
}

A retry on the virtual clock​

A delayed retry is redelivered once advance has moved the clock past its delay:

/// Asks for a retry later on a first delivery, and acknowledges the copy that carries its retry
/// count.
#[subscriber(LocalMemorySource::new("jobs"))]
async fn on_job(job: &Job<'_>, ctx: &mut Context<'_>) -> HandlerOutcome {
let _ = job.0;
match ctx.headers().get_str(RETRY_COUNT_HEADER) {
Some("1") => HandlerOutcome::ack(),
_ => HandlerOutcome::retry_after(LATER),
}
}

fn app() -> RustStream {
RustStream::new(AppInfo::new("jobs", "0.1.0")).with_broker(Bus::new(), |b| {
b.include(on_job).out_retry(LocalMemoryPublish)
})
}
#[test]
fn a_retry_is_redelivered_only_once_its_delay_has_passed() -> Result<(), Box<dyn Error>> {
Runtime::new()?.block_on(async {
let tb = TestApp::start(app()).await?;
tb.broker::<Bus>()
.message(&Sent(b"job"))
.to("jobs")
.publish()
.await?;

tb.advance(Duration::from_secs(4)).await?;
tb.broker::<Bus>()
.subscriber("jobs")
.assert_called_once()
.settled(HandlerOutcome::retry_after(LATER));

tb.advance(Duration::from_secs(1)).await?;
let jobs = tb.broker::<Bus>();
let calls = jobs.subscriber("jobs").assert_called(2);
assert_eq!(
calls.outcomes().last(),
Some(&Outcome::Ack),
"the copy carries its retry count to the handler"
);
tb.shutdown().await?;
Ok(())
})
}