Skip to Content

Testing

floor::testing::TestApp: a backend's handlers against a real Postgres and a fake Floor, with TestResponse and TestSocket.

floor::testing runs a backend's handlers in the test process: routes, WebSockets and triggers, against a fresh Postgres database with the backend's migrations and a fake Floor that records what the handlers asked of it. No server, no network. See also Testing.

use floor::testing::TestApp;
use serde_json::json;

#[tokio::test]
async fn a_known_plate_opens_the_gate() {
    let t = TestApp::start(gate::app()).await;
    let admin = t.sign_in(&["admin"]);
    let r = t.post("/api/vehicles", Some(&admin), json!({ "plate": "LEB-4821" })).await;
    assert_eq!(r.status, 201);
    t.mqtt("gate-3/events", &json!({ "event_id": "e1", "lane_id": 1, "plate": "LEB-4821" }))
        .await
        .unwrap();
    assert_eq!(t.commands(), vec![("gate-3".into(), "open_gate".into())]);
    t.close().await;
}

floor test runs cargo test with the database set up for you.

The module

Item
TestAppa backend under test
TestResponsea route's response
TestSocketthe caller's end of a WebSocket
PROJECT: &strthe project tests run as: "test"
FakeFloorthe fake Floor, t.floor
Callone thing a handler asked of Floor, as t.calls() returns it

TestApp

TestApp::start

pub async fn start(app: App) -> Self

Starts app with a fresh database and a fake Floor. It runs app.check() first, so a can that permissions.rs doesn't define fails the test here. Panics with what's missing.

The database comes from FLOOR_TEST_DATABASE_URL, else DATABASE_URL: a Postgres server where the test may create databases, such as postgres://floor:floor@127.0.0.1:5432/postgres. Each TestApp creates its own database there (floor_test_<id>), applies the app's migrations, and drops it on close. Tests can run in parallel.

MigrationsDatabase URL setWhat happens
yesyesa fresh database with the migrations
noyesa fresh, empty database
yesnopanics: set FLOOR_TEST_DATABASE_URL
nonono database; t.db() and cx.db() panic

t.db

pub fn db(&self) -> &PgPool

The test database, to set up rows before a call or check them after. Panics when the test has no database.

sqlx::query("insert into lanes (id, organization, direction, device) values (1, 'test-org', 'in', 'gate-3')")
    .execute(t.db())
    .await
    .unwrap();

t.close

pub async fn close(self)

Drops the test database. Call it at the end of each test.

Callers

t.sign_in

pub fn sign_in(&self, roles: &[&str]) -> String

A bearer token for a new user with roles, in the organization test-org. Each call is a different user.

t.sign_in_device

pub fn sign_in_device(&self, hardware_id: &str) -> String

A bearer token for the project's device hardware_id, as Floor's device protocol issues, for routes marked device.

t.sign_in_as

pub fn sign_in_as(&self, user: floor::User) -> String

A bearer token for exactly this caller: a service client, a user with no organization, a token about to run out.

let token = t.sign_in_as(floor::User {
    sub: "client:reports".into(),
    kind: "service".into(),
    org: Some("test-org".into()),
    roles: vec!["reports".into()],
    device: None,
    email: None,
    name: None,
    expires_at: i64::MAX / 2,
});

Routes

t.get

pub async fn get(&self, path: &str, token: Option<&str>) -> TestResponse

A GET. path may carry a query string: /api/visits?limit=20.

t.post

pub async fn post(&self, path: &str, token: Option<&str>, json: serde_json::Value) -> TestResponse

A POST with a JSON body.

t.send

pub async fn send(
    &self,
    method: Method,
    path_and_query: &str,
    token: Option<&str>,
    json: Option<serde_json::Value>,
) -> TestResponse

Any method, with or without a JSON body. Method is floor::Method.

let r = t.send(floor::Method::DELETE, "/api/vehicles/7", Some(&admin), None).await;
assert_eq!(r.status, 204);

t.send_with

pub async fn send_with(
    &self,
    method: Method,
    path_and_query: &str,
    token: Option<&str>,
    extra: &[(&str, &str)],
    json: Option<serde_json::Value>,
) -> TestResponse

send with request headers (If-None-Match, …).

t.send_raw

pub async fn send_raw(&self, method: Method, path_and_query: &str, token: Option<&str>, content_type: &str, body: impl Into<Bytes>) -> TestResponse

A request with any body: an image, a CSV, bytes from a device.

t.post_form

pub async fn post_form(&self, path_and_query: &str, token: Option<&str>, parts: &[FormPart]) -> TestResponse

A multipart/form-data POST, as a browser's FormData sends it:

use floor::testing::FormPart;

let r = t.post_form("/api/vehicles/42/documents", Some(&token), &[
    FormPart::text("title", "Insurance"),
    FormPart::file("document", "policy.pdf", "application/pdf", b"%PDF-1.7 ..."),
]).await;

t.ws

pub async fn ws(&self, path: &str, token: Option<&str>) -> Result<TestSocket, TestResponse>

Opens one of the backend's WebSockets as token's holder, over an in-memory pipe. A refusal (401, 403, 404) comes back as the response the caller would have got.

let mut s = t.ws("/api/live", Some(&guard)).await.unwrap();
s.send_text("refresh").await;
let inside = s.recv_json().await.unwrap();
assert!(t.ws("/api/live", None).await.is_err());

Triggers

Each runs the trigger's handler and returns what its ack would say: Ok(()), or Err with the error's message. A trigger with no handler is an Err too.

t.mqtt

pub async fn mqtt(&self, topic: &str, body: &impl Serialize) -> Result<(), String>

An MQTT message on topic, inside the project: gate-3/events arrives as test/gate-3/events. body is sent as JSON.

t.tick

pub async fn tick(&self, name: &str) -> Result<(), String>

A tick, by its name: ocr_sweep.sweep for jobs/ocr-sweep.rs's sweep. See Trigger names.

t.cron

pub async fn cron(&self, name: &str) -> Result<(), String>

A run of the #[cron] handler named name (reports.nightly for jobs/reports.rs's nightly), as Floor's cron would start it.

t.job

pub async fn job(&self, queue: &str, body: &impl Serialize) -> Result<(), String>

A job on queue with body, as attempt 1. Jobs a handler enqueues with cx.enqueue are only recorded; run them with t.job.

t.device

pub async fn device(&self, event: &str, data: serde_json::Value) -> Result<(), String>

A device event (online, …) with the realtime hub's JSON. DeviceEvent.device comes from data["device"].

t.device("offline", json!({ "device": "gate-3" })).await.unwrap();

t.event

pub async fn event(&self, kind: &str, data: serde_json::Value) -> Result<(), String>

One of the project's events, for #[event] handlers.

t.event("message.received", json!({ "from": "+923001234567", "text": "open gate-3" })).await.unwrap();

The fake Floor

It answers every call a handler makes through Cx:

CallThe fake
publish, publish_todelivers to 1 listener
mqtt_publish, delete_blobdoes nothing
commandreturns an id, cmd-<n>
kv_get, kv_set, kv_deletea map in memory (TTLs are ignored)
enqueue, enqueue_afterreturns an id, job-<n>; the job doesn't run
secretwhat set_secret set, else None
notifyreturns the message as queued
upload_url, download_urla URL on blob.test
device_infowhat add_device added; an error for any other device
devices, approve_device, revoke_devicethe devices add_device and add_pending_device added; approving changes pending to active
claim_codescount codes, TEST-<n>-<i>
cameras, open_lease, renew_lease, end_leasethe cameras add_camera added; a lease with token lease-token-<id> and WHEP URLs on media.test
grantremembers the role by email (see t.access); a new person gets an invite_url on floor.test
personwhat grant gave: status invited and the role; None for anyone else
register_camera, remove_cameraadds or removes a camera in the list cameras gives
claim_devicelike Floor: a new device is active with a claim_code, else pending; the same key again changes nothing; a revoked device that claims with a new key starts over; another key for a live device is a 409
device_tokena token for an active device, read from the assertion's iss (test/<hardware id>), in a real ES256 JWT (its signature isn't checked) or as the bare string "test/nano-9"; typed refusals (DeviceRefusal::Pending, Revoked, Unauthorized) as Floor gives them
disable_person, enable_personchanges the status person reports; a 409 for someone still invited
download_url, download_url_asa URL on blob.test; t.calls() shows the filename asked for
set_device_configmerges set, removes remove, returns the config
chatthe next answer_chat text, from model fake
ocrthe set_ocr_text text, with no lines

t.set_secret

pub fn set_secret(&self, name: &str, value: &str)

What cx.secret(name) returns.

t.add_device

pub fn add_device(&self, hardware_id: &str, health: serde_json::Value)

Adds a device for cx.device_info: online, active, with health.

t.add_pending_device

pub fn add_pending_device(&self, hardware_id: &str)

Adds a device waiting for approval, for cx.devices(Some("pending")) and cx.approve_device.

t.revoke_device

pub fn revoke_device(&self, hardware_id: &str)

Revokes a device, as an operator would.

t.set_person_status

pub fn set_person_status(&self, email: &str, status: &str)

A person's status (invited, active, disabled) after cx.grant, as if they'd used their invite link ("active").

t.floor_unreachable

pub fn floor_unreachable(&self, down: bool)

From now on every call to Floor fails as it does when Floor is down: Error::Floor, a 502. false brings it back.

t.add_camera

pub fn add_camera(&self, name: &str, label: &str)

Adds a live camera, for cx.cameras and cx.open_lease.

t.access

pub fn access(&self, email: &str) -> Option<Option<String>>

A person's role in the project after cx.grant: Some(Some(role)), Some(None) once it was taken away, None if they were never given one.

t.answer_chat

pub fn answer_chat(&self, text: &str)

What the next cx.chat answers. Answers are used in order; once they run out, the answer is empty.

t.set_ocr_text

pub fn set_ocr_text(&self, text: &str)

What cx.ocr finds in any image.

What the handlers asked

t.calls

pub fn calls(&self) -> Vec<Call>

Everything the backend asked of Floor, in order. Token checks aren't included.

t.commands

pub fn commands(&self) -> Vec<(String, String)>

The device commands sent: (device, command).

t.published

pub fn published(&self) -> Vec<(String, serde_json::Value)>

What was published on realtime channels: (app:<name>, the message).

let (channel, card) = &t.published()[0];
assert_eq!(channel, "app:lanes");
assert_eq!(card["plate"], "LEB-4821");

t.sent

pub fn sent(&self) -> Vec<Notification>

The messages the backend sent through cx.notify.

let sent = t.sent();
assert_eq!(sent[0].channel.as_deref(), Some("email"));
assert_eq!(sent[0].template.as_deref(), Some("visit-approved"));

TestResponse

pub struct TestResponse {
    pub status: u16,
    /// Lower-case names.
    pub headers: Vec<(String, String)>,
    pub body: Bytes,
}
Method
fn json<T: DeserializeOwned>(&self) -> Tthe body as JSON; panics with the body when it isn't T
fn header(&self, name: &str) -> Option<&str>a response header, by name
fn text(&self) -> Stringthe body as text
let r = t.get("/api/visits?limit=20", Some(&guard)).await;
assert_eq!(r.status, 200);
let page: serde_json::Value = r.json();
assert_eq!(page["items"][0]["plate"], "LEB-4821");

TestSocket

pub struct TestSocket(/* private */);

The caller's end of a WebSocket in a test. Sending on a closed socket panics.

Method
async fn send_text(&mut self, t: &str)sends a text message
async fn send_json(&mut self, v: &impl Serialize)sends JSON as text
async fn recv_text(&mut self) -> Option<String>the next message as text; None once the backend closed it
async fn recv_json(&mut self) -> Option<serde_json::Value>the next message as JSON; panics when it isn't JSON
async fn close(self)closes it

On this page