Kandra

kandra-test

kandra-test is Kandra's test-support module, io.kandra.test.*, offering two genuinely different testing styles for code that uses KandraRepository/KandraSuspendRepository, plus helpers for running the second style against a live cluster:

StyleEntry pointBackingSpeedWhat it actually exercises
Fake-session unit testKandraTestUtils.inMemory(...)FakeKandraSession (in-process, no network)instantThe real repository, StatementBuilder and BatchEngine code paths run to completion, so you can assert on the structure of what was built — which statements, in what order. It stores no data and never returns rows.
Testcontainers integration testKandraTestcontainers.freshKeyspace(...)real cassandra:4.1 container (or a live cluster, see KandraTestBackend)slow (container start + real CQL)The full, real KandraRepository/KandraSuspendRepository API against real DDL/DML

Pick the fake when the question is "did save() build the batch I expect?" and the container when the question is "did the right data come back?" or anything involving LWT outcomes — the fake cannot return rows or fail an LWT.

Why this exists as a separate module

kandra-test exposes kandra-core and kandra-runtime as api dependencies (its public types return theirs) plus, notably, compileOnly Testcontainers (Cassandra and the base testcontainers artifact used by the multi-DC fixture) and compileOnly JUnit (for KandraCloud.assumeConfigured()) — none of them are forced onto every consumer's runtime classpath just because they add kandra-test for FakeKandraSession; only a consumer who actually calls KandraTestcontainers needs to also bring Testcontainers themselves at test time. As a test-only module in the first place, keeping it separate from kandra-core/kandra-runtime means production code never accidentally pulls in JUnit, Testcontainers, or a fake driver implementation — kandra-test is meant to be a testImplementation, never an implementation, dependency.

Added in 0.5.1

KandraTestUtils.reset() and KandraRuntime.closeAndReset() clear the schema registry without an internal-API opt-in; FakeKandraSession.capturedStatementViews()/capturedBatchViews() return a public CapturedStatement(cql, values) (with isUnset(i)); KandraTestcontainers.newContainerSession(keyspace) opens a Docker-only session with 30 s timeouts; and the DataStax driver is now an api dependency of kandra-test, kandra-runtime and kandra-ktor. None of this is in 0.5.0.

FakeKandraSession

class FakeKandraSession : CqlSession

An in-process implementation of the DataStax driver's CqlSession interface — no network, no ScyllaDB process.

class FakeKandraSessionCaptureTest {
    private val fakeSession = FakeKandraSession()
 
    @AfterEach
    fun tearDown() { fakeSession.reset() }
 
    @Test
    fun `execute captures batch statements for inspection`() {
        // SimpleStatement doesn't need prepare()/bind(), so it works fine under the fake.
        val batch = BatchStatement.newInstance(DefaultBatchType.LOGGED)
            .add(SimpleStatement.newInstance("INSERT INTO users (id, name) VALUES (?, ?)", "u1", "Ada"))
            .add(SimpleStatement.newInstance("INSERT INTO user_email_lookup (email, id) VALUES (?, ?)", "ada@x.com", "u1"))
 
        val result = fakeSession.execute(batch)
 
        assertEquals(1, fakeSession.capturedBatches().size)
        assertEquals(2, fakeSession.capturedBatches().single().size)
        assertEquals(true, result.wasApplied())   // always true — cannot simulate LWT failure here
    }
}
MemberBehavior
capturedStatements(): List<Statement<*>>Snapshot of every statement (batch or not) passed through the synchronous execute(Statement<*>) overload, in call order.
capturedBatches(): List<BatchStatement>capturedStatements() filtered to BatchStatements — save/delete/update/saveAll all route through a LOGGED batch.
reset()Clears the captured statements — the only stateful thing to reset between assertions.
tableContents(tableName): List<Map<String, Any?>>Always returns emptyList(), literally, regardless of tableName or anything previously executed. Despite the name, it is not backed by anything captured.
execute(statement)Appends the statement to the captured list; always returns FakeResultSet.empty() regardless of the statement — an empty result set with wasApplied() == true.
executeAsync(statement)Always resolves to an empty FakeAsyncResultSet. Does not capture anything — only the synchronous overload does.
prepare(query)Returns FakePreparedStatement(query). Its .bind(...) returns a working structural FakeBoundStatement that records the positionally-bound values — no real CQL type encoding.
Repository calls run end-to-end under the fake — but only structurally

Until 0.4.7, FakePreparedStatement.bind(...) unconditionally threw UnsupportedOperationException, which made the whole repository surface unusable through KandraTestUtils.inMemory(...) (GH #28 / ISS-040). That is fixed: repo.save, findById, delete, update, saveAll, raw and the rest run to completion through the real StatementBuilder/BatchEngine. What the fake still does not do: encode or decode CQL types, store rows, return rows from reads, or report anything but wasApplied() == true — so you cannot simulate a failed LWT (saveIfNotExists() == false) or an optimistic-lock conflict through it. Use Testcontainers for those; see /battle-scars/testing-lwt-and-fakes.

KandraTestUtils.inMemory(...) / io.kandra.test.KandraRuntime

object KandraTestUtils {
    fun inMemory(vararg classes: KClass<*>): KandraRuntime
}
 
class KandraRuntime internal constructor(val session: CqlSession) : AutoCloseable {
    fun <T : Any> repository(klass: KClass<T>): KandraRepository<T>
    fun <T : Any> suspendRepository(klass: KClass<T>): KandraSuspendRepository<T>
    override fun close()   // cancels pending eventual-write coroutines; does NOT close session or clear SchemaRegistry
}
@Test
fun `save builds one LOGGED batch with the expected INSERT`() {
    val runtime = KandraTestUtils.inMemory(User::class)
    val session = runtime.session as FakeKandraSession      // the fake wired into this runtime
    val repo = runtime.repository(User::class)
 
    repo.save(User(id = "u1", name = "Ada"))
 
    val batch = session.capturedBatches().single()
    val queries = batch.map { (it as BoundStatement).preparedStatement.query }
    assertEquals(listOf("INSERT INTO users (id, name) VALUES (?, ?)"), queries)
 
    runtime.close()
    SchemaRegistry.clear()   // schema registration is process-global — reset between tests
}

Use runtime.session, not a separate FakeKandraSession() — inMemory(...) creates its own, and a second instance would never see the runtime's statements. The fake's bound-value accessor (FakeBoundStatement.boundValues()) is internal to kandra-test, so from your own module assert on the public driver API (BoundStatement.preparedStatement.query) as above.

inMemory(...) calls SchemaRegistry.register(it) for each class (additive, process-global — never cleared automatically) and returns a KandraRuntime wrapping a fresh FakeKandraSession.

Two different KandraRuntime classes, two different calling conventions

io.kandra.test.KandraRuntime (this class) is a different class from the production io.kandra.runtime.KandraRuntime used by KandraTestcontainers below — same simple name, different package, different constructor shape, different repository-lookup calling convention. io.kandra.test.KandraRuntime.repository(User::class) takes an explicit KClass argument; KandraRuntimeHandle.repository<User>() (below) is reified, no argument. Mixing up the call style between the two test styles is an easy copy-paste mistake when switching between them.

KandraTestcontainers

object KandraTestcontainers {
    val container: CassandraContainer<*>
    fun freshKeyspace(
        vararg classes: KClass<*>,
        replicationFactor: Int = 1,
        statementBuilderConsistencyConfig: ConsistencyConfig = ConsistencyConfig(),
    ): KandraRuntimeHandle
}
 
class KandraRuntimeHandle(
    val runtime: io.kandra.runtime.KandraRuntime,   // the real production runtime, not a test double
    val keyspace: String,
) {
    inline fun <reified T : Any> repository(): KandraRepository<T>
    inline fun <reified T : Any> suspendRepository(): KandraSuspendRepository<T>
    fun close()
}

container is by lazy { CassandraContainer("cassandra:4.1").withExposedPorts(9042).also { it.start(); awaitReady(it) } } — Kotlin's default by lazy mode is SYNCHRONIZED, so this is a thread-safe singleton shared across every test class in the same JVM. .start() runs inside the lazy initializer itself, so the very first access from any test class blocks synchronously while Testcontainers pulls/starts the container — can take tens of seconds on a cold Docker cache. After start() it also polls until CQL is genuinely serving (a query plus a create/drop-keyspace DDL probe, 3-minute deadline, then IllegalStateException), so the first test does not pay for the cold start. There is no shutdown code anywhere in this file; the container runs until the JVM exits and Testcontainers' Ryuk reaper cleans it up.

freshKeyspace(vararg classes):

  1. Generates keyspace = "kandra_test_${UUID.randomUUID()...}" — fresh per call, so concurrent test classes never collide.
  2. Opens a throwaway bootstrap session, runs CREATE KEYSPACE IF NOT EXISTS ... SimpleStrategy, replication_factor = <replicationFactor> (default 1), closes it.
  3. Opens a second, real session with .withKeyspace(keyspace) — the session everything else uses.
  4. For each class: SchemaRegistry.register(klass) (same process-global registry as the fake-session path), then executes every statement from DdlGenerator.allStatements(schema) — real CREATE TABLE (and @LookupIndex lookup tables) against the container.
  5. Builds StatementBuilder, a fresh CoroutineScope, BatchEngine, and the production io.kandra.runtime.KandraRuntime — the same class Ktor wires up in real apps, not a test double.
class UserRepositoryIntegrationTest {
    private val db = KandraTestcontainers.freshKeyspace(User::class)
    private val userRepo = db.repository<User>()             // reified — no ::class argument
    private val userSuspendRepo = db.suspendRepository<User>()
 
    @AfterEach
    fun tearDown() {
        db.close()   // drops db.keyspace and closes db's own session; the shared container stays up
    }
 
    @Test
    fun `save then findById round-trips through real ScyllaDB-compatible CQL`() {
        val user = User(id = "u1", name = "Ada", email = "ada@example.com")
        userRepo.save(user)
        assertEquals(user, userRepo.findById(user.id))
    }
}
close() swallows teardown errors; the container image is Cassandra, not ScyllaDB

KandraRuntimeHandle.close() wraps both DROP KEYSPACE IF EXISTS $keyspace and session.close() in runCatching — a failed teardown neither fails your test nor logs anything from this code. It also does not call SchemaRegistry.clear() and does not stop the shared container, which stays running for the rest of the JVM's life; only your per-call keyspace is isolated and dropped. Separately: the container image is real Apache Cassandra 4.1, not an actual ScyllaDB image — Kandra targets ScyllaDB in production, but this module's integration tests run against Cassandra-protocol compatibility, not the real target database. If a difference between Cassandra and ScyllaDB's exact query-planner behavior matters to what you're testing, this container won't surface it.

Testcontainers dependency (0.5.2 — [#190](https://github.com/Dev-Pasaka/kandra/issues/190))

Since 0.5.2 kandra-test brings org.testcontainers:cassandra and org.testcontainers:testcontainers (1.21.4) as api dependencies. On 0.5.1 add testImplementation("org.testcontainers:cassandra:1.21.4") yourself, or KandraTestcontainers.freshKeyspace() fails with NoClassDefFoundError: org/testcontainers/containers/CassandraContainer.

KandraTestBackend and KandraCloud — run the same tests against a live cluster

KandraTestBackend is the shared connection provider for live tests. KANDRA_TEST_BACKEND unset or docker uses the Testcontainers container above (behaviour unchanged); cloud uses the cluster described by the KANDRA_CLOUD_* environment and fails fast if KANDRA_CLOUD_CONTACT_POINTS is unset. KandraTestcontainers.freshKeyspace(...) honours the switch, so a suite written against the container can be pointed at a real cluster without code changes.

object KandraTestBackend {
    val isCloud: Boolean
    val contactPointsCsv: String            // host:port CSV, ready for KandraConfig.contactPoints
    val localDatacenter: String
    val username: String; val password: String   // blank on Docker; never log
    fun effectiveRf(requested: Int): Int         // cloud: RF 1 becomes 3
    fun keyspaceName(tag: String): String        // docker: kandra_<tag>_<32 hex>; cloud: kt_<tag>_<8 hex>
    fun newSession(keyspace: String? = null): CqlSession   // 30 s request/schema timeouts; caller closes
    fun freshKeyspace(tag: String, rf: Int = 1): FreshKeyspace   // AutoCloseable; close() always drops the keyspace
}

On the cloud backend keyspaces get AND tablets = {'enabled': false} and RF 1 is bumped to 3, so assert replication metadata against effectiveRf(...), not the value you requested. Every session uses 30-second timeouts — the driver's 2-second default is too tight for DDL against a cold container or over a WAN.

KandraCloud is the environment-driven harness underneath it. Nothing about the cluster lives in the repo:

VariableMeaning
KANDRA_CLOUD_CONTACT_POINTSComma-separated host[:port] (port defaults to 9042). Unset means unconfigured.
KANDRA_CLOUD_USERNAME / KANDRA_CLOUD_PASSWORDPlain auth credentials.
KANDRA_CLOUD_LOCAL_DCLocal datacenter; defaults to AWS_US_EAST_1.
KANDRA_CLOUD_TLStrue enables TLS and rewrites port 9042 to 9142 (KANDRA_CLOUD_SSL=true is the legacy spelling, JVM trust store).
KANDRA_CLOUD_CA_PEMPath to a CA PEM; an in-memory trust store is built from it.
KANDRA_CLOUD_TRUSTSTORE / KANDRA_CLOUD_TRUSTSTORE_PASSWORDAlternative custom trust store.
@BeforeAll @JvmStatic fun gate() = KandraCloud.assumeConfigured()   // skips, never fails, when unconfigured
 
@Test fun works() = KandraCloud.freshKeyspace("smoke").use { ks ->
    ks.session.execute("CREATE TABLE t (id int PRIMARY KEY)")   // session is bound to ks.name
}
Shared cluster rules

Only create keyspaces through these helpers (the kt_ prefix), always close the handle so the keyspace is dropped, and never touch keyspaces you did not create. Never commit values for the KANDRA_CLOUD_* variables. Not every suite can run against a cloud cluster: the SSL round-trip and multi-DC suites need their own containers.

KandraMultiDcTestcontainers — a two-datacenter fixture

A separate, Docker-only Compose fixture: two gossiping cassandra:4.1 nodes (dc1, dc2) on dynamically chosen ports, for testing DC failover behaviour. It is for failover mechanics, not a substitute for a genuine multi-region cluster.

object KandraMultiDcTestcontainers {
    const val DC1 = "dc1"; const val DC2 = "dc2"
    fun contactPoint(dc: String): InetSocketAddress
    fun pause(dc: String); fun unpause(dc: String); fun unpauseAll()
    fun freshNetworkTopologyKeyspace(
        vararg classes: KClass<*>,
        localDatacenter: String = DC1,
        dcReplicationMap: Map<String, Int> = mapOf(DC1 to 1, DC2 to 1),
        statementBuilderConsistencyConfig: ConsistencyConfig = ConsistencyConfig(),
    ): KandraRuntimeHandle   // keyspace kandra_multidc_<uuid>, NetworkTopologyStrategy; close() drops it
}
 
class KandraMultiDcFixtureException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)

KandraMultiDcFixtureException is thrown when the fixture itself cannot start — a chosen port still collided after three attempts, or Docker is not running. Always call unpauseAll() in @AfterEach after pausing a datacenter.

Gotchas worth double-checking in review

  • SchemaRegistry is process-global and neither test style clears it automatically — call SchemaRegistry.clear() yourself in @AfterEach if a test depends on a clean registry (e.g. asserting a schema-validation failure that only fires on first registration).
  • FakeKandraSession.tableContents(...) always returns emptyList() — never use it to assert on saved data; there is nothing behind it. Assert on capturedStatements()/capturedBatches() instead.
  • FakeResultSet.wasApplied() is hardcoded true, with no seam to flip it — you cannot simulate a failed LWT (saveIfNotExists() == false, an optimistic-lock conflict) through FakeKandraSession. Testcontainers is the only way to exercise those paths.
  • The first integration test to touch KandraTestcontainers.container in a JVM run is noticeably slower than the rest — it's paying for the container start that every subsequent freshKeyspace() call reuses.

Full API reference

kandra-test on Dokka → · FakeKandraSession → · KandraTestcontainers → · KandraTestBackend → · KandraCloud →

Where this shows up elsewhere on this site