Skip to main content

Testing a device service

A test runs the production app unchanged on the host. The embedded TestApp runs a device service and the compio TestApp runs a compio service; both connect the broker in process, so no server and no runner are needed.

The crate​

cargo add --dev ruststream-rust-mqtt --features testing

The tests need testing next to the runtime feature of the service: embassy for a device, compio for a host.

A test​

The test declares the broker's memory as a static, as the board does, and starts the app with a broker built by MqttBroker::new over it. It publishes a message to it as another client of the server would, and asserts what the handler received and how it settled.

#[test]
fn a_job_is_answered() {
static MEMORY: ConstStaticCell<MqttState> = ConstStaticCell::new(MqttState::new());
block_on(async {
let tb = TestApp::start(app(board(MEMORY.take())))
.await
.expect("the app starts");
let jobs = tb.broker::<MqttBroker>();
jobs.message(&Sent(b"mix"))
.to("jobs/run")
.publish()
.await
.expect("the harness publishes");

jobs.subscriber("jobs/run")
.assert_called_once()
.with_raw(b"mix")
.settled(HandlerOutcome::ack());
jobs.published::<()>("jobs/done")
.assert_called_once()
.with_raw(b"done");
tb.shutdown().await.expect("the app stops");
});
}

Time​

The clock of the test is its own. A retry_after copy comes back once advance has moved the clock past its delay.

#[test]
fn a_job_is_asked_for_again_when_its_delay_has_passed() {
static MEMORY: ConstStaticCell<MqttState> = ConstStaticCell::new(MqttState::new());
block_on(async {
let tb = TestApp::start(retrying_app(board(MEMORY.take())))
.await
.expect("the app starts");
let jobs = tb.broker::<MqttBroker>();
jobs.message(&Sent(b"mix"))
.to("jobs/later")
.publish()
.await
.expect("the harness publishes");

tb.advance(Duration::from_secs(4))
.await
.expect("the clock moves");
jobs.subscriber("jobs/later").assert_called_once();
tb.advance(Duration::from_secs(1))
.await
.expect("the clock moves");
let calls = jobs.subscriber("jobs/later").assert_called(2);
assert_eq!(calls.outcomes().last(), Some(&Outcome::Ack));
tb.shutdown().await.expect("the app stops");
});
}

On compio​

A compio service is the heap variant, and its test needs no memory of its own.

#[test]
fn a_job_is_answered_on_compio() -> Result<(), Box<dyn Error>> {
Runtime::new()?.block_on(async {
let tb = TestApp::start(app()).await?;
let jobs = tb.broker::<MqttBroker>();
jobs.message(&Job { id: 7 })
.to("jobs/run")
.publish()
.await?;

jobs.subscriber("jobs/run")
.assert_called_once()
.with(&Job { id: 7 })
.settled(HandlerOutcome::ack());
jobs.published::<Done>("jobs/done")
.assert_called_once()
.with(&Done { id: 7 });
tb.shutdown().await?;
Ok(())
})
}

What the in-process transport leaves to the server, a persistent session and the handshakes of QoS 1 and 2 among them, is tested on the live stand.