Testing harness for Spacetimedb - Compile tests as reducers or procedures and easily run them.
README.md

spacetimedb-test-harness #

This project makes SpacetimeDB modules testable from Rust.

SpacetimeDB module code does not behave like ordinary Rust library code in tests. Reducers expect SpacetimeDB host context, the real behavior usually only exists after publishing a module, and useful outside-in tests need a running server, test-only reducers, generated test bindings, and boilerplate for publishing a unique database per test.

spacetimedb-test-harness provides that missing harness. It can publish a test module, connect generated Rust bindings, call reducers or procedures, wait for callbacks, subscribe to tables, and clean up test databases. cargo-test-stdb adds the runner piece: it starts a short-lived local SpacetimeDB server for a test run and passes the right environment variables to the tests.

Attribute Test Example #

For simple module-internal flows, put the test next to the reducer code:

use spacetimedb::{ReducerContext, Table};

#[spacetimedb::table(accessor = greeting, public)]
pub struct Greeting {
    text: String,
}

#[spacetimedb::reducer]
pub fn add_greeting(ctx: &ReducerContext, text: String) {
    ctx.db.greeting().insert(Greeting { text });
}

#[cfg(feature = "test-reducers")]
#[spacetimedb_test_harness::reducer_test]
#[spacetimedb::reducer]
pub fn test_add_greeting(ctx: &ReducerContext) -> Result<(), String> {
    add_greeting(ctx, "hello".to_owned());

    ctx.db
        .greeting()
        .iter()
        .any(|greeting| greeting.text == "hello")
        .then_some(())
        .ok_or_else(|| "expected greeting to be inserted".to_owned())
}

The macro keeps the reducer as a real SpacetimeDB reducer, then generates a native Rust test that publishes the module, connects test bindings, calls test_add_greeting_then, waits for the callback, and deletes the database after success.

#[spacetimedb_test_harness::procedure_test] does the same for no-argument test procedures.

Manual Test Example #

Use a manual test when the test should drive the module from the outside: multiple reducer calls, subscriptions, identities, or cache assertions.

#[cfg(test)]
#[rustfmt::skip]
mod module_bindings_tests;

#[cfg(test)]
mod stdb_tests {
    use std::error::Error;

    use spacetimedb_sdk::{DbContext as _, Table as _};
    use spacetimedb_test_harness::prelude::*;

    use super::module_bindings_tests::{
        add_greeting as _, DbConnection, GreetingTableAccess as _,
    };

    #[test]
    fn add_greeting_updates_subscribed_cache() -> Result<(), Box<dyn Error>> {
        let published = StdbTestHarness::from_env()?.publish_module_unique()?;
        let (conn, _worker) = connect_stdb_module!(published, DbConnection)?;

        conn.subscription_builder()
            .subscribe_and_wait(|builder| builder.subscribe(["SELECT * FROM greeting"]))?;

        call_reducer_ok(|callback| {
            conn.reducers
                .add_greeting_then("hello".to_owned(), callback)
        })??;

        assert!(
            conn.db.greeting().iter().any(|greeting| greeting.text == "hello"),
            "expected greeting to be visible in the client cache"
        );

        conn.disconnect()?;
        published.delete()?;
        Ok(())
    }
}

The ?? is intentional for reducers: the first ? handles failure to send the request, the second handles the reducer callback result.

Module Setup #

In your SpacetimeDB module crate:

[features]
test-reducers = []

[profile.stdb-harness]
inherits = "release"

[dependencies]
spacetimedb = "2.6"
spacetimedb-test-harness = { version = "0.1", default-features = false, features = ["macros"] }

[dev-dependencies]
spacetimedb-sdk = "2.6"
spacetimedb-test-harness = "0.1"

If this crate is not published yet, replace the version = "0.1" dependency with a git or local path dependency.

Use a separate build profile for the harness. stdb-harness inherits release so SpacetimeDB gets an optimized Wasm build, but it avoids fighting with whatever spacetime dev is building at the same time.

Add generated test bindings inside the module crate:

#[cfg(test)]
#[rustfmt::skip]
mod module_bindings_tests;

Generate them explicitly before running tests:

spacetime generate \
  --lang rust \
  --module-path spacetimedb \
  --out-dir spacetimedb/src/module_bindings_tests \
  --build-options="--features=test-reducers --profile=stdb-harness" \
  --yes

Do not generate bindings from inside the tests. Tests should consume the already-generated module_bindings_tests module.

cargo-test-stdb #

Install the runner:

cargo install --git https://tangled.org/frath.tngl.sh/spacetimedb-test-harness-rs cargo-test-stdb

From a checkout:

cargo install --path crates/cargo-test-stdb

With Nix:

nix profile add 'git+https://tangled.org/frath.tngl.sh/spacetimedb-test-harness-rs'

From a checkout:

nix profile add .#cargo-test-stdb

Run tests through the runner:

cargo test-stdb \
  --module-path spacetimedb \
  --build-options="--features=test-reducers --profile=stdb-harness" \
  -- cargo test --manifest-path spacetimedb/Cargo.toml --features test-reducers

By default, cargo-test-stdb:

  • starts spacetime start on a free local port,
  • uses a temporary SpacetimeDB root directory,
  • builds or publishes the module for each test through the harness,
  • sets STDB_TEST_SERVER, STDB_TEST_MODULE_PATH, STDB_TEST_BUILD_OPTIONS, and STDB_TEST_SPACETIME_ROOT_DIR,
  • runs the command after --,
  • lets successful tests delete their own databases,
  • removes the temporary server directory after the run.

Pass --skip-delete if the server lifetime should be the only cleanup boundary.

For an already-running server:

cargo test-stdb \
  --server http://127.0.0.1:3000 \
  --module-path spacetimedb \
  --build-options="--features=test-reducers --profile=stdb-harness" \
  -- cargo test --manifest-path spacetimedb/Cargo.toml --features test-reducers

In that mode, successful tests still delete their databases unless --skip-delete is set.

Developing This Project #

This repository contains:

  • crates/spacetimedb-test-harness: the Rust harness library.
  • crates/spacetimedb-test-harness-macros: attribute and helper macros.
  • crates/cargo-test-stdb: the Cargo subcommand runner.
  • stdb-test-module/spacetimedb: a small SpacetimeDB module used by tests.
  • stdb-test-module/bindings: normal generated bindings for the sample module.

Useful commands:

just
just gen-test-bindings
just ci-checks
just ci-integration
just ci

just ci-integration uses cargo-test-stdb and temporary SpacetimeDB servers. just integration-test targets an already-running server at http://127.0.0.1:3000.

Generated bindings are committed for the sample module. Do not hand-edit files under stdb-test-module/spacetimedb/src/module_bindings_tests.

License #

Licensed under either MIT or Apache-2.0.