Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testcontainers for Java: Add examples for init scripts and function #59

Merged
merged 3 commits into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions testing/testcontainers/java/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ of examples you can explore here:
Testcontainer instance honoring the ``CRATEDB_VERSION`` environment variable, suitable
for running a test matrix on different versions of CrateDB, shared across multiple test
classes.
- ``TestSqlInitialization``: Demonstrate different ways how Testcontainers can run an init script after
the database container is started, but before your code is given a connection to it.
matriv marked this conversation as resolved.
Show resolved Hide resolved
amotl marked this conversation as resolved.
Show resolved Hide resolved

[1]: Sometimes, it might be useful to define a container that is only started once for
several test classes. There is no special support for this use case provided by
Expand All @@ -64,6 +66,9 @@ Usage
# Run individual tests.
./gradlew test --tests TestFunctionScope

# Inspect tracebacks on failures.
./gradlew test --tests TestFunctionScope --info

# Run test case showing how to select CrateDB version per environment variable.
export CRATEDB_VERSION=5.2.3
export CRATEDB_VERSION=nightly
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ public Results querySummitsTable() throws IOException, SQLException {
return this.query("SELECT * FROM sys.summits ORDER BY height DESC LIMIT 3");
}

public Results showCreateTable(String tablename) throws IOException, SQLException {
return this.query("SHOW CREATE TABLE " + tablename);
}

public Results query(String sql) throws IOException, SQLException {
Properties connectionProps = new Properties();
connectionProps.put("user", user);
Expand Down
15 changes: 15 additions & 0 deletions testing/testcontainers/java/src/main/resources/init.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE alltypes (
name STRING PRIMARY KEY,
date TIMESTAMP,
datetime_tz TIMESTAMP WITH TIME ZONE,
datetime_notz TIMESTAMP WITHOUT TIME ZONE,
nullable_datetime TIMESTAMP,
nullable_date TIMESTAMP,
kind STRING,
flag BOOLEAN,
position INTEGER,
description STRING,
details ARRAY(OBJECT),
attributes OBJECT(DYNAMIC),
coordinates GEO_POINT
) WITH (number_of_replicas=0);
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package io.crate.example.testing;

import org.junit.Test;

import java.io.IOException;
import java.sql.SQLException;

import static org.assertj.core.api.Assertions.assertThat;


/**
* Database containers launched with SQL initialization/provisioning script/routine.
* <p>
* <a href="https://www.testcontainers.org/modules/databases/jdbc/#database-containers-launched-via-jdbc-url-scheme"/>
* <a href="https://www.testcontainers.org/features/reuse/"/>
* </p>
*/
public class TestSqlInitialization {

/**
* Launch container with CrateDB 5.2, using `TC_INITSCRIPT` to address a file in Java's CLASSPATH.
* <a href="https://www.testcontainers.org/modules/databases/jdbc/#using-a-classpath-init-script"/>
*/
@Test
public void testTcInitClasspathFile() throws SQLException, IOException {
String connectionUrl = "jdbc:tc:cratedb:5.2://localhost/doc?user=crate&TC_REUSABLE=true&TC_INITSCRIPT=init.sql";
System.out.printf("Connecting to %s%n", connectionUrl);

// Invoke `SHOW CREATE TABLE ...` query.
Application app = new Application(connectionUrl);
var results= app.showCreateTable("alltypes");
assertThat(results.metaData().getColumnCount()).isEqualTo(1);
assertThat(results.rows()).hasSize(1);
}

/**
* Launch container with CrateDB 5.2, using `TC_INITSCRIPT` to address an arbitrary file on the filesystem.
* <a href="https://www.testcontainers.org/modules/databases/jdbc/#using-an-init-script-from-a-file"/>
*/
@Test
public void testTcInitArbitraryFile() throws SQLException, IOException {
String connectionUrl = "jdbc:tc:cratedb:5.2://localhost/doc?user=crate&TC_REUSABLE=true&TC_INITSCRIPT=file:src/main/resources/init.sql";
System.out.printf("Connecting to %s%n", connectionUrl);

// Invoke `SHOW CREATE TABLE ...` query.
Application app = new Application(connectionUrl);
var results= app.showCreateTable("alltypes");
assertThat(results.metaData().getColumnCount()).isEqualTo(1);
assertThat(results.rows()).hasSize(1);
}

/**
* Launch container with CrateDB 5.2, using an init function.
* <a href="https://www.testcontainers.org/modules/databases/jdbc/#using-an-init-script-from-a-file"/>
*/
@Test
public void testTcInitFunction() throws SQLException, IOException {
String connectionUrl = "jdbc:tc:cratedb:5.2://localhost/doc?user=crate&TC_INITFUNCTION=io.crate.example.testing.utils.TestingHelpers::sqlInitFunction";
System.out.printf("Connecting to %s%n", connectionUrl);

// Invoke `SHOW CREATE TABLE ...` query.
Application app = new Application(connectionUrl);
var results= app.showCreateTable("foobar_init");
assertThat(results.metaData().getColumnCount()).isEqualTo(1);
assertThat(results.rows()).hasSize(1);
}
amotl marked this conversation as resolved.
Show resolved Hide resolved

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import io.crate.example.testing.Application;
import org.testcontainers.utility.DockerImageName;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import static org.assertj.core.api.Assertions.assertThat;

Expand Down Expand Up @@ -36,4 +39,21 @@ public static void assertResults(Application.Results results) throws SQLExceptio
"Monte Rosa",
"Dom");
}

/**
* Support function for initializing CrateDB with SQL using an init function.
* You can run a simple schema setup or Flyway/liquibase DB migrations here, at your disposal.
* <a href="https://www.testcontainers.org/modules/databases/jdbc/#using-an-init-function"/>
*/
public static void sqlInitFunction(Connection connection) throws SQLException, IOException, InterruptedException {
try (Statement stmt = connection.createStatement()) {
boolean checkResults = stmt.execute("CREATE TABLE IF NOT EXISTS foobar_init (id INTEGER)");
if (checkResults) {
System.out.println("Success.");
matriv marked this conversation as resolved.
Show resolved Hide resolved
} else {
throw new SQLException("ERROR: SQL initialization failed");
}
}
}

}