下面显示的是英文原文。
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:
- Macros
- Manual
/// 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))
}
/// Acknowledges every reading.
struct OnReading;
impl Handle<Frame<'_>> for OnReading {
fn handle(
&self,
reading: &Frame<'_>,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
let _ = reading.0;
ready(Ok(()))
}
}
fn app() -> RustStream {
RustStream::new(AppInfo::new("readings", "0.1.0")).with_broker(Bus::new(), |b| {
b.include(subscriber(LocalMemorySource::new("readings"), OnReading).build())
})
}
- Macros
- Manual
#[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(())
})
}
#[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"))
.to("readings")
.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:
- Macros
- Manual
/// 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)
})
}
/// The slot alarms leave through.
struct Alarms;
impl OutSlot for Alarms {
const NAME: &'static str = "Alarms";
type Destination = Reads;
}
impl PublishedThrough<Alarms> for Alarm {}
/// Shows every level, in percent.
struct Show;
impl Handle<Frame<'_>, Shown> for Show {
fn handle(
&self,
level: &Frame<'_>,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<Shown, HandlerOutcome>> {
ready(Ok(Shown([level.0, b" %"].concat())))
}
}
/// Raises an alarm for every level.
struct Watch;
impl<Entry> Handle<Frame<'_>, (), Outs<(Entry,)>> for Watch
where
Entry: OutEntry<Alarms, Wire: Publisher>,
{
async fn handle(
&self,
level: &Frame<'_>,
outs: &Outs<(Entry,)>,
_ctx: &mut Context<'_>,
) -> Result<(), HandlerOutcome> {
outs.get(Alarms)
.message(&Alarm(level.0.to_vec()))
.publish()
.await
.map_err(|_| HandlerOutcome::retry())
}
}
fn app() -> RustStream {
RustStream::new(AppInfo::new("tank", "0.1.0")).with_broker(Bus::new(), |b| {
b.include(
subscriber(LocalMemorySource::new("levels"), Show)
.reply()
.build(),
)
.out_reply(LocalMemoryPublish)
.include(subscriber(LocalMemorySource::new("tank"), Watch).build())
.out(Alarms, LocalMemoryPublish)
})
}
- Macros
- Manual
#[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(())
})
}
#[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:
- Macros
- Manual
#[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(())
})
}
#[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:
- Macros
- Manual
/// 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)
})
}
/// Asks for a retry later on a first delivery, and acknowledges the copy that carries its
/// retry count.
struct OnJob;
impl Handle<Frame<'_>> for OnJob {
fn handle(
&self,
job: &Frame<'_>,
_outs: &(),
ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
let _ = job.0;
ready(match ctx.headers().get_str(RETRY_COUNT_HEADER) {
Some("1") => Ok(()),
_ => Err(HandlerOutcome::retry_after(LATER)),
})
}
}
fn app() -> RustStream {
RustStream::new(AppInfo::new("jobs", "0.1.0")).with_broker(Bus::new(), |b| {
b.include(subscriber(LocalMemorySource::new("jobs"), OnJob).build())
.out_retry(LocalMemoryPublish)
})
}
- Macros
- Manual
#[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(())
})
}
#[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(())
})
}