Skip to Content

Testing

Test a backend's routes, triggers and sockets against a real Postgres and a fake Floor with floor test and TestApp.

A backend's tests run its real handlers against a real Postgres, with a fake Floor standing in for floord. The fake answers every cx call and records it, so a test can send a plate event and then check that the gate was told to open. At the end of this page you can write and run such tests. You need a local Postgres, as in Install.

1. Write a test

Tests go in tests/, as for any crate. floor new writes tests/app.rs with one:

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, "{}", r.text());

    t.mqtt("dev-1/events", &json!({ "event_id": "e1", "lane_id": 1, "plate": "LEB-4821" }))
        .await
        .unwrap();
    assert_eq!(t.commands(), vec![("dev-1".to_owned(), "open_gate".to_owned())]);
    assert_eq!(t.published()[0].0, "app:lanes");

    t.close().await;
}

TestApp::start builds the app as it would start on Floor, so the same checks apply: a can that permissions.rs doesn't define fails the test.

2. Run the tests

floor test
floor test visits -- --nocapture       # arguments after it go to cargo test

floor test runs cargo test for the backend with:

  • FLOOR_TEST_DATABASE_URL set to the local Postgres (FLOOR_DEV_POSTGRES, default postgres://floor:floor@127.0.0.1:5432/postgres). --postgres <url> picks another.
  • Checked queries built against <name>_dev with its SQL migrations applied, unless the crate has .sqlx/, in which case they build offline from it.

cargo test works too, with FLOOR_TEST_DATABASE_URL set yourself.

The database

Each TestApp makes a fresh database on FLOOR_TEST_DATABASE_URL, applies the backend's migrations (SQL and Rust), and drops it on close(). Tests don't share data and can run in parallel. The Postgres role needs to create databases.

  • t.db() is the test database's pool, for setting up rows or checking them.
  • A backend with migrations and no FLOOR_TEST_DATABASE_URL panics with what to set.
  • Call t.close().await at the end of each test. A test that panics before it leaves its database behind; they're named floor_test_….
sqlx::query("insert into edge_events (event_id, lane_id, action, at) values ('old', 1, 'open', now() - interval '31 days')")
    .execute(t.db())
    .await
    .unwrap();

Callers

MethodGives
t.sign_in(&["guard"])A token for a new user with those roles, in the organization test-org
t.sign_in_device("dev-1")A token for the project's device dev-1, for device routes
t.sign_in_as(user)A token for a floor::User you build: another organization, no organization, a service client

Tokens the fake Floor didn't issue are refused with 401, as Floor would. The project is test, so MQTT topics are test/….

Requests

MethodSends
t.get(path, token)GET
t.post(path, token, json)POST with a JSON body
t.send(method, path, token, json)Any method: t.send(floor::Method::DELETE, "/api/vehicles/3", Some(&admin), None)
t.send_with(method, path, token, headers, json)The same, with extra headers
t.ws(path, token)Opens a WebSocket, or returns the refusal (WebSockets)

The path can carry a query: t.get("/api/visits?limit=5", Some(&guard)). A response has status, headers and body, and:

  • r.json::<T>() parses the body (and panics with the body when it isn't T);
  • r.text() gives it as text;
  • r.header("content-type") reads a header.

Triggers

Each runs the handler and returns what its ack would say: Ok(()), or Err with the message.

MethodRuns
t.mqtt("dev-1/events", &body)The #[mqtt] handler whose filter matches; the project prefix is added
t.tick("sweep.sweep")The #[every] handler of that name
t.cron("prune.prune")The #[cron] handler of that name, as Floor's cron would start it
t.job("receipts", &body)The #[job] handler for that queue, attempt 1
t.device("online", json!({ "device": "dev-1" }))The #[device] handlers for that event
// A lane on another device is refused, and the ack says why.
let e = t.mqtt("dev-9/events", &json!({ "event_id": "e4", "lane_id": 1, "plate": "LEB-4821" }))
    .await
    .unwrap_err();
assert!(e.contains("isn't on dev-9"), "{e}");

#[background] tasks don't run in tests.

The fake Floor

It answers every cx call:

  • KV keeps values in memory: a kv_set then kv_get reads back.
  • Commands, publishes, jobs, messages and blob URLs succeed, with made-up ids and URLs.
  • Device config merges set and remove and returns the result.
  • Secrets, devices, chat and OCR answer what the test set up:
t.set_secret("ANPR_API_KEY", "test-key");
t.add_device("SL-GW-0142", json!({ "lux": 34 }));   // online, active, with that health
t.answer_chat("Two visits, both closed.");          // the next cx.chat answers this
t.set_ocr_text("LEB-4821");                          // every cx.ocr finds this

A device it doesn't know is an error from cx.device_info, as on Floor.

It records every call. Read them back:

MethodReturns
t.commands()Device commands sent: (device, command)
t.published()Realtime publishes: (app:<name>, message)
t.sent()Messages sent through cx.notify, as Notifications
t.calls()Everything, in order, as floor::testing::Call
let sent = t.sent();
assert_eq!(sent[0].to, "guard@example.com");
assert_eq!(sent[0].template.as_deref(), Some("visit-approved"));

Checking the manifest and the client

app().describe() is the manifest --describe prints, and app().typescript() the client. A test can pin what the backend serves:

#[test]
fn the_manifest_lists_the_triggers() {
    let d = gate::app().describe();
    assert_eq!(d["mqtt"], json!(["+/events"]));
    assert_eq!(d["every"], json!([{ "name": "sweep.sweep", "millis": 30000 }]));
}

See Testing reference for every method.

On this page