NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / EMBEDDED ENGINE / TESTING WITH THE EMBEDDED ENGINE

Testing with the embedded engine

The embedded engine gives each test a real database that starts and stops with the test, with no server to install on a developer machine or CI runner. This page shows how to set tests up so they stay independent and leave nothing behind, given that only one engine can run in a process at a time.

Set up the dev-dependencies

toml
[dev-dependencies]
rasterizeddb_embedded = "1.1"
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tempfile = "3"

The rule: one engine per process

cargo test builds each file in tests/ as a separate program, a separate process, and runs the test functions inside one file in parallel threads of that process. The engine allows one running engine per process: a second start while one runs fails with std::io::ErrorKind::AlreadyExists. So:

  • Tests in different files never collide. Each file is its own process.
  • Tests in the same file must take turns. Hold a shared lock while a test's engine runs.

The engine's settings are process-wide too (see Settings are process-wide). A test that changes a setting changes it for the tests that run after it in the same process, and some values can be chosen only once per process. Put tests that need particular settings in a file of their own.

A test file with several tests

Each test holds a lock for as long as its engine runs, and stops the engine before it returns:

rust
// tests/notes.rs
use rasterizeddb_client::prelude::*;
use rasterizeddb_embedded::Builder;

/// One engine runs in a process at a time, and the tests in this file run
/// in parallel: each test holds this while its engine runs.
static ONE_ENGINE: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn one_engine() -> std::sync::MutexGuard<'static, ()> {
    // A test that panicked while holding the lock must not fail the others.
    ONE_ENGINE.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// On Windows the endpoint is a loopback port and needs a password.
fn builder(b: Builder) -> Builder {
    if cfg!(unix) { b } else { b.password("app", "test-password") }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn inserts_and_counts() {
    let _one = one_engine();
    let db = builder(Builder::in_memory()).worker_threads(2).start().await.unwrap();
    let client = db.connect().await.unwrap();

    client.run("CREATE TABLE notes (id BIGINT, body TEXT)").await.unwrap();
    client
        .exec("INSERT INTO notes VALUES ($1, $2), ($3, $4)", params![1i64, "a", 2i64, "b"])
        .await
        .unwrap();
    let n: i64 = client.fetch_scalar("SELECT COUNT(*) FROM notes", params![]).await.unwrap();
    assert_eq!(n, 2);

    drop(client);
    db.shutdown().await.unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_rolled_back_transaction_leaves_nothing() {
    let _one = one_engine();
    let db = builder(Builder::in_memory()).worker_threads(2).start().await.unwrap();
    let client = db.connect().await.unwrap();

    client.run("CREATE TABLE t (id BIGINT)").await.unwrap();
    let tx = client.begin().await.unwrap();
    tx.exec("INSERT INTO t VALUES ($1)", params![1i64]).await.unwrap();
    tx.rollback().await.unwrap();
    let n: i64 = client.fetch_scalar("SELECT COUNT(*) FROM t", params![]).await.unwrap();
    assert_eq!(n, 0);

    drop(client);
    db.shutdown().await.unwrap();
}

Notes on this pattern:

  • Builder::in_memory() is the quickest start and leaves no files. Each test gets an empty database.
  • worker_threads(2) keeps each engine small. By default the engine starts one thread per CPU.
  • The lock is a std::sync::Mutex, held across .await. That is fine here because each test has its own runtime and holds the lock for its whole body.
  • #[tokio::test(flavor = "multi_thread")] is what the crate's own tests use.
  • A test that panics drops its Embedded while unwinding, which stops the engine before the lock is released.

Tests that need a directory

Use a temporary directory for anything that must survive a restart, such as persistence, reopening, or settings saved in rasterizeddb.conf. Declare the directory before the engine, so the engine is stopped before the directory is deleted:

rust
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rows_survive_a_restart() {
    let _one = one_engine();
    let dir = tempfile::tempdir().unwrap(); // dropped last: deleted after the engine stops

    {
        let db = builder(Builder::open(dir.path())).worker_threads(2).start().await.unwrap();
        let client = db.connect().await.unwrap();
        client.run("CREATE TABLE kept (id BIGINT)").await.unwrap();
        client.run("INSERT INTO kept VALUES (1), (2), (3)").await.unwrap();
        drop(client);
        db.shutdown().await.unwrap();
    }

    // The same directory, a new engine, in the same process.
    let db = builder(Builder::open(dir.path())).worker_threads(2).start().await.unwrap();
    let client = db.connect().await.unwrap();
    let n: i64 = client.fetch_scalar("SELECT COUNT(*) FROM kept", params![]).await.unwrap();
    assert_eq!(n, 3);
    drop(client);
    db.shutdown().await.unwrap();
}

To check that your code copes with an engine that is stopped by being dropped rather than by shutdown, drop the Embedded in the first block instead. A drop also stops cleanly.

Tests that change settings

Settings belong to the process, and values such as batch_size, query_threads or join_memory_mb can be chosen once per process. A later start that asks for a different value fails with InvalidInput. Two patterns keep such tests reliable:

  • A file per configuration. Put the tests for each set of settings in a tests/ file of their own, so each set starts in a fresh process.
  • One test function with ordered phases. When several starts must happen in a known order (start with a setting, SET CONFIG, restart and check), write them as one test function. Separate test functions would race on the shared settings.
rust
// tests/low_memory.rs: a process of its own, because the settings are the process's.
use rasterizeddb_client::prelude::*;
use rasterizeddb_embedded::Builder;

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn works_under_the_low_memory_preset() {
    let dir = tempfile::tempdir().unwrap();
    let mut b = Builder::open(dir.path()).worker_threads(2).low_memory().join_memory_mb(128);
    if cfg!(not(unix)) {
        b = b.password("app", "test-password");
    }
    let db = b.start().await.unwrap();
    let client = db.connect().await.unwrap();

    client.run("CREATE TABLE items (id BIGINT PRIMARY KEY, grp BIGINT)").await.unwrap();
    client.run("INSERT INTO items VALUES (1, 1), (2, 1), (3, 2)").await.unwrap();
    let n: i64 = client
        .fetch_scalar("SELECT COUNT(*) FROM items WHERE grp = $1", params![1i64])
        .await
        .unwrap();
    assert_eq!(n, 2);

    drop(client);
    db.shutdown().await.unwrap();
}

A file with a single test function needs no lock.

Tests outside an async runtime

A plain #[test] can start and stop the engine with the blocking calls, and build a runtime for the client:

rust
#[test]
fn starts_and_stops_without_a_runtime() {
    let _one = one_engine();
    let db = builder(Builder::in_memory()).worker_threads(1).start_blocking().unwrap();
    assert!(!db.endpoint().is_empty());

    let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
    rt.block_on(async {
        let client = db.connect().await.unwrap();
        client.run("CREATE TABLE t (id BIGINT)").await.unwrap();
    });

    db.shutdown_blocking().unwrap();
}

Running tests in parallel and on CI

  • cargo test runs one test file at a time and the tests inside a file in parallel, so with the lock above, at most one engine runs at once.
  • Each engine is a full database engine. On a small CI runner, keep worker_threads low, prefer in_memory(), and keep the data each test writes small.
  • On Windows CI, the tests need the password helper (builder above): without it, start fails with InvalidInput.
  • On x86-64 runners, the CPU must have AVX2, or start fails with ErrorKind::Unsupported and names the missing instructions. Check this first if every test fails at start.

Cleaning up

  • Temporary directories from tempfile::tempdir() are deleted when the TempDir drops, which is why it must be declared before the engine.
  • The private socket directory (rdb-embedded-<pid>-<random> under the temporary directory, Unix only) is removed at shutdown or drop. A test process that is killed, for example by a CI timeout, leaves both it and its TempDirs behind. Clean the temporary directory on long-lived CI machines.
  • The directory lock ends with the process, so a killed test never leaves a directory that the next run cannot open.

Limits

  • One engine per process: tests in one file must serialise their engines.
  • Settings are process-wide, and some values can be chosen once per process. Tests that need different values belong in different files.
  • A test that leaves its Client or Embedded in a static keeps the engine running for the rest of the process, and later tests in that file cannot start one. Keep both local to the test.
✓ page rendered in 142 µs axum + tera + htmx · no other javascript