CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-testcontainers--cassandra

Testcontainers implementation for Apache Cassandra, providing lightweight, throwaway database instances for Java integration testing

Overview
Eval results
Files

connection-access.mddocs/

Connection and Access

Methods for obtaining connection information and establishing DataStax driver sessions for query execution.

Capabilities

Connection Information

Get connection details required for establishing DataStax driver sessions to the Cassandra container.

/**
 * Retrieve an InetSocketAddress for connecting to the Cassandra container via the driver.
 * @return InetSocketAddress representation of this Cassandra container's host and port
 */
public InetSocketAddress getContactPoint();

/**
 * Retrieve the Local Datacenter for connecting to the Cassandra container via the driver.
 * @return The configured local Datacenter name (default: "datacenter1")
 */
public String getLocalDatacenter();

Usage Examples:

import org.testcontainers.cassandra.CassandraContainer;
import com.datastax.oss.driver.api.core.CqlSession;
import java.net.InetSocketAddress;

try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")) {
    cassandra.start();
    
    // Get connection information
    InetSocketAddress contactPoint = cassandra.getContactPoint();
    String datacenter = cassandra.getLocalDatacenter();
    
    // Create DataStax driver 4.x session
    CqlSession session = CqlSession.builder()
        .addContactPoint(contactPoint)
        .withLocalDatacenter(datacenter)
        .build();
    
    // Use session for queries
    ResultSet result = session.execute("SELECT release_version FROM system.local");
    session.close();
}

Authentication Credentials

Access default authentication credentials for Cassandra connections when authentication is enabled.

/**
 * Get username.
 * By default, Cassandra has authenticator: AllowAllAuthenticator in cassandra.yaml.
 * If username and password need to be used, then authenticator should be set as PasswordAuthenticator
 * (through custom Cassandra configuration) and through CQL with default cassandra-cassandra credentials
 * user management should be modified.
 * @return Default username ("cassandra")
 */
public String getUsername();

/**
 * Get password.
 * By default, Cassandra has authenticator: AllowAllAuthenticator in cassandra.yaml.
 * If username and password need to be used, then authenticator should be set as PasswordAuthenticator
 * (through custom Cassandra configuration) and through CQL with default cassandra-cassandra credentials
 * user management should be modified.
 * @return Default password ("cassandra")
 */
public String getPassword();

Usage Examples:

// Connection with authentication enabled
try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")
    .withConfigurationOverride("cassandra-auth-enabled")) {
    cassandra.start();
    
    // Create authenticated session
    CqlSession session = CqlSession.builder()
        .addContactPoint(cassandra.getContactPoint())
        .withLocalDatacenter(cassandra.getLocalDatacenter())
        .withAuthCredentials(cassandra.getUsername(), cassandra.getPassword())
        .build();
    
    // Execute queries with authentication
    ResultSet result = session.execute("SELECT * FROM system_auth.roles");
    session.close();
}

DataStax Driver Integration Patterns

DataStax Driver 4.x (Recommended)

Modern driver integration using CqlSession builder pattern.

import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;

// Basic connection
CqlSession session = CqlSession.builder()
    .addContactPoint(cassandra.getContactPoint())
    .withLocalDatacenter(cassandra.getLocalDatacenter())
    .build();

// Connection with authentication
CqlSession sessionAuth = CqlSession.builder()
    .addContactPoint(cassandra.getContactPoint())
    .withLocalDatacenter(cassandra.getLocalDatacenter())
    .withAuthCredentials(cassandra.getUsername(), cassandra.getPassword())
    .build();

// Execute queries
ResultSet resultSet = session.execute("SELECT release_version FROM system.local");
Row row = resultSet.one();
String version = row.getString("release_version");

Legacy DataStax Driver 3.x (Deprecated)

The deprecated container class provides methods for creating legacy Cluster objects.

/**
 * Get configured Cluster for DataStax driver 3.x
 * @deprecated For Cassandra driver 3.x, use getHost() and getMappedPort(int) with
 * the driver's Cluster.Builder addContactPoint(String) and withPort(int) methods.
 * For Cassandra driver 4.x, use getContactPoint() and getLocalDatacenter() with
 * the driver's CqlSession.builder() methods.
 * @return Configured Cluster object
 */
@Deprecated
public Cluster getCluster();

/**
 * Static method for creating Cluster with custom JMX reporting setting
 * @param containerState Container state for connection info
 * @param enableJmxReporting Whether to enable JMX reporting
 * @return Configured Cluster object
 */
@Deprecated
public static Cluster getCluster(ContainerState containerState, boolean enableJmxReporting);

Connection Helper Methods

For manual driver configuration when needed.

// Get individual connection components
String host = cassandra.getHost();              // Container host
Integer port = cassandra.getMappedPort(9042);   // Mapped CQL port
String datacenter = cassandra.getLocalDatacenter(); // Datacenter name

// Manual session creation
CqlSession session = CqlSession.builder()
    .addContactPoint(new InetSocketAddress(host, port))
    .withLocalDatacenter(datacenter)
    .build();

Connection Testing Patterns

Basic Connection Test

@Test
public void testCassandraConnection() {
    try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")) {
        cassandra.start();
        
        CqlSession session = CqlSession.builder()
            .addContactPoint(cassandra.getContactPoint())
            .withLocalDatacenter(cassandra.getLocalDatacenter())
            .build();
        
        ResultSet result = session.execute("SELECT release_version FROM system.local");
        assertThat(result.wasApplied()).isTrue();
        assertThat(result.one().getString(0)).isNotNull();
        
        session.close();
    }
}

Connection with Schema Operations

@Test
public void testSchemaOperations() {
    try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")) {
        cassandra.start();
        
        CqlSession session = CqlSession.builder()
            .addContactPoint(cassandra.getContactPoint())
            .withLocalDatacenter(cassandra.getLocalDatacenter())
            .build();
        
        // Create keyspace
        session.execute("CREATE KEYSPACE test WITH replication = " +
                       "{'class': 'SimpleStrategy', 'replication_factor': 1}");
        
        // Create table
        session.execute("CREATE TABLE test.users (id uuid PRIMARY KEY, name text)");
        
        // Insert data
        session.execute("INSERT INTO test.users (id, name) VALUES (uuid(), 'John')");
        
        // Query data
        ResultSet result = session.execute("SELECT name FROM test.users");
        assertThat(result.one().getString("name")).isEqualTo("John");
        
        session.close();
    }
}

Error Handling

Common connection-related exceptions and handling patterns:

import com.datastax.oss.driver.api.core.AllNodesFailedException;
import com.datastax.oss.driver.api.core.DriverException;

try {
    CqlSession session = CqlSession.builder()
        .addContactPoint(cassandra.getContactPoint())
        .withLocalDatacenter(cassandra.getLocalDatacenter())
        .build();
} catch (AllNodesFailedException e) {
    // No nodes available - container may not be ready
    logger.error("Failed to connect to Cassandra", e);
} catch (DriverException e) {
    // General driver error
    logger.error("Cassandra driver error", e);
}

Install with Tessl CLI

npx tessl i tessl/maven-org-testcontainers--cassandra

docs

configuration-initialization.md

connection-access.md

container-management.md

index.md

wait-strategies-delegation.md

tile.json