org.testcontainers.containers.JdbcDatabaseContainer Java Examples

The following examples show how to use org.testcontainers.containers.JdbcDatabaseContainer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DatabaseDriverTmpfsTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void testDatabaseHasTmpFsViaConnectionString() throws Exception {
    final String jdbcUrl = "jdbc:tc:postgresql:9.6.8://hostname/databasename?TC_TMPFS=/testtmpfs:rw";
    try (Connection ignored = DriverManager.getConnection(jdbcUrl)) {

        JdbcDatabaseContainer<?> container = ContainerDatabaseDriver.getContainer(jdbcUrl);
        // check file doesn't exist
        String path = "/testtmpfs/test.file";
        Container.ExecResult execResult = container.execInContainer("ls", path);
        assertNotEquals("tmpfs inside container doesn't have file that doesn't exist", 0, execResult.getExitCode());
        // touch && check file does exist
        container.execInContainer("touch", path);
        execResult = container.execInContainer("ls", path);
        assertEquals("tmpfs inside container has file that does exist", 0, execResult.getExitCode());
    }
}
 
Example #2
Source File: ContainerDatabaseDriver.java    From testcontainers-java with MIT License 6 votes vote down vote up
/**
 * Wrap the connection, setting up a callback to be called when the connection is closed.
 * <p>
 * When there are no more open connections, the container itself will be stopped.
 *
 * @param connection    the new connection to be wrapped
 * @param container     the container which the connection is associated with
 * @param connectionUrl {@link ConnectionUrl} instance representing JDBC Url for this connection
 * @return the connection, wrapped
 */
private Connection wrapConnection(final Connection connection, final JdbcDatabaseContainer container, final ConnectionUrl connectionUrl) {

    final boolean isDaemon = connectionUrl.isInDaemonMode() || connectionUrl.isReusable();

    Set<Connection> connections = containerConnections.computeIfAbsent(container.getContainerId(), k -> new HashSet<>());

    connections.add(connection);

    final Set<Connection> finalConnections = connections;

    return new ConnectionWrapper(connection, () -> {
        finalConnections.remove(connection);
        if (!isDaemon && finalConnections.isEmpty()) {
            container.stop();
            jdbcUrlContainerCache.remove(connectionUrl.getUrl());
        }
    });
}
 
Example #3
Source File: AbstractMigratorIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
protected void migrate(JdbcDatabaseContainer container, String listTableQuery, String username, String password) throws SQLException {
    Source source = new Source(container.getJdbcUrl(), username, password);
    assertThat(new Request(source, listTableQuery))
            .hasNumberOfRows(0);

    try (Connection connection = container.createConnection("")) {
        new DatabaseMigrator().migrate(connection);
    }

    assertThat(new Request(source, listTableQuery))
            .hasNumberOfRowsGreaterThan(10);
}
 
Example #4
Source File: DatabaseDriverShutdownTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void shouldNotStopDaemonContainerWhenAllConnectionsClosed() throws SQLException {
    final String jdbcUrl = "jdbc:tc:postgresql:9.6.8://hostname/databasename?TC_DAEMON=true";

    getConnectionAndClose(jdbcUrl);

    JdbcDatabaseContainer<?> container = ContainerDatabaseDriver.getContainer(jdbcUrl);
    assertNotNull("Database container instance is not null as expected", container);
    assertTrue("Database container is running as expected", container.isRunning());
}
 
Example #5
Source File: IntegrationTestConfig.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private JdbcDatabaseContainer<?> initContainer()
{
    DhisPostgreSQLContainer<?> postgisContainer = ((DhisPostgreSQLContainer<?>) new DhisPostgisContainerProvider().newInstance())
        .appendCustomPostgresConfig( "max_locks_per_transaction=100" )
        .withDatabaseName( POSTGRES_DATABASE_NAME )
        .withUsername( POSTGRES_CREDENTIALS )
        .withPassword( POSTGRES_CREDENTIALS );

    postgisContainer.start();

    log.info( String.format( "PostGIS container initialized: %s", postgisContainer.getJdbcUrl() ) );

    return postgisContainer;
}
 
Example #6
Source File: JpaTransactionManagerRule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static JdbcDatabaseContainer create() {
  PostgreSQLContainer container =
      new PostgreSQLContainer(NomulusPostgreSql.getDockerTag())
          .withDatabaseName(POSTGRES_DB_NAME);
  container.start();
  return container;
}
 
Example #7
Source File: AbstractContainerDatabaseTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
protected ResultSet performQuery(JdbcDatabaseContainer<?> container, String sql) throws SQLException {
    DataSource ds = getDataSource(container);
    Statement statement = ds.getConnection().createStatement();
    statement.execute(sql);
    ResultSet resultSet = statement.getResultSet();

    resultSet.next();
    return resultSet;
}
 
Example #8
Source File: AbstractContainerDatabaseTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
protected DataSource getDataSource(JdbcDatabaseContainer<?> container) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(container.getJdbcUrl());
    hikariConfig.setUsername(container.getUsername());
    hikariConfig.setPassword(container.getPassword());
    hikariConfig.setDriverClassName(container.getDriverClassName());

    return new HikariDataSource(hikariConfig);
}
 
Example #9
Source File: DatabaseDriverShutdownTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void shouldStopContainerWhenAllConnectionsClosed() throws SQLException {
    final String jdbcUrl = "jdbc:tc:postgresql:9.6.8://hostname/databasename";

    getConnectionAndClose(jdbcUrl);

    JdbcDatabaseContainer<?> container = ContainerDatabaseDriver.getContainer(jdbcUrl);
    assertNull("Database container instance is null as expected", container);
}
 
Example #10
Source File: DatabaseConfigurations.java    From elepy with Apache License 2.0 5 votes vote down vote up
public static Configuration createTestContainerConfiguration(JdbcDatabaseContainer container, String dialect) {
    return new WithSetupConfiguration(
            container::start,
            createInMemoryHibernateConfig(
                    container.getDriverClassName(),
                    container.getJdbcUrl(),
                    dialect,
                    container.getUsername(),
                    container.getPassword()
            ),
            container::stop);
}
 
Example #11
Source File: ContainerDatabaseDriver.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * Utility method to kill ALL database containers directly from test support code. It shouldn't be necessary to use this,
 * but it is provided for convenience - e.g. for situations where many different database containers are being
 * tested and cleanup is needed to limit resource usage.
 */
public static void killContainers() {
    synchronized (jdbcUrlContainerCache) {
        jdbcUrlContainerCache.values().forEach(JdbcDatabaseContainer::stop);
        jdbcUrlContainerCache.clear();
        containerConnections.clear();
        initializedContainers.clear();
    }

}
 
Example #12
Source File: ContainerDatabaseDriver.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * Utility method to kill a database container directly from test support code. It shouldn't be necessary to use this,
 * but it is provided for convenience - e.g. for situations where many different database containers are being
 * tested and cleanup is needed to limit resource usage.
 *
 * @param jdbcUrl the JDBC URL of the container which should be killed
 */
public static void killContainer(String jdbcUrl) {
    synchronized (jdbcUrlContainerCache) {
        JdbcDatabaseContainer container = jdbcUrlContainerCache.get(jdbcUrl);
        if (container != null) {
            container.stop();
            jdbcUrlContainerCache.remove(jdbcUrl);
            containerConnections.remove(container.getContainerId());
            initializedContainers.remove(container.getContainerId());
        }
    }
}
 
Example #13
Source File: ContainerDatabaseDriver.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
public synchronized Connection connect(String url, final Properties info) throws SQLException {

    /*
      The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL.
     */
    if (!acceptsURL(url)) {
        return null;
    }

    ConnectionUrl connectionUrl = ConnectionUrl.newInstance(url);

    synchronized (jdbcUrlContainerCache) {

        String queryString = connectionUrl.getQueryString().orElse("");
        /*
          If we already have a running container for this exact connection string, we want to connect
          to that rather than create a new container
         */
        JdbcDatabaseContainer container = jdbcUrlContainerCache.get(connectionUrl.getUrl());
        if (container == null) {

            LOGGER.debug("Container not found in cache, creating new instance");

            Map<String, String> parameters = connectionUrl.getContainerParameters();

            /*
              Find a matching container type using ServiceLoader.
             */
            ServiceLoader<JdbcDatabaseContainerProvider> databaseContainers = ServiceLoader.load(JdbcDatabaseContainerProvider.class);
            for (JdbcDatabaseContainerProvider candidateContainerType : databaseContainers) {
                if (candidateContainerType.supports(connectionUrl.getDatabaseType())) {
                    container = candidateContainerType.newInstance(connectionUrl);
                    container.withTmpFs(connectionUrl.getTmpfsOptions());
                    delegate = container.getJdbcDriverInstance();
                }
            }
            if (container == null) {
                throw new UnsupportedOperationException("Database name " + connectionUrl.getDatabaseType() + " not supported");
            }

            /*
              Cache the container before starting to prevent race conditions when a connection
              pool is started up
             */
            jdbcUrlContainerCache.put(url, container);

            /*
              Pass possible container-specific parameters
             */
            container.setParameters(parameters);

            /*
              Start the container
             */
            container.start();
        }

        /*
          Create a connection using the delegated driver. The container must be ready to accept connections.
         */
        Connection connection = container.createConnection(queryString);

        /*
          If this container has not been initialized, AND
          an init script or function has been specified, use it
         */
        if (!initializedContainers.contains(container.getContainerId())) {
            DatabaseDelegate databaseDelegate = new JdbcDatabaseDelegate(container, queryString);
            runInitScriptIfRequired(connectionUrl, databaseDelegate);
            runInitFunctionIfRequired(connectionUrl, connection);
            initializedContainers.add(container.getContainerId());
        }

        return wrapConnection(connection, container, connectionUrl);
    }
}
 
Example #14
Source File: JdbcDatabaseDelegate.java    From testcontainers-java with MIT License 4 votes vote down vote up
public JdbcDatabaseDelegate(JdbcDatabaseContainer container, String queryString) {
    this.container = container;
    this.queryString = queryString;
}
 
Example #15
Source File: DhisPostgisContainerProvider.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public JdbcDatabaseContainer newInstance( String tag )
{
    return new DhisPostgreSQLContainer( DEFAULT_IMAGE + ":" + tag );
}
 
Example #16
Source File: DhisPostgisContainerProvider.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public JdbcDatabaseContainer newInstance()
{
    return newInstance( DEFAULT_TAG );
}
 
Example #17
Source File: SqlMetaDataITCase.java    From syndesis with Apache License 2.0 4 votes vote down vote up
public SqlMetaDataITCase(final JdbcDatabaseContainer<?> database) {
    this.database = database;
}
 
Example #18
Source File: ContainerDatabaseDriver.java    From testcontainers-java with MIT License 2 votes vote down vote up
/**
 * Utility method to get an instance of a database container given its JDBC URL.
 *
 * @param jdbcUrl the JDBC URL of the container instance to get
 * @return an instance of database container or <code>null</code> if no container associated with JDBC URL
 */
static JdbcDatabaseContainer getContainer(String jdbcUrl) {
    synchronized (jdbcUrlContainerCache) {
        return jdbcUrlContainerCache.get(jdbcUrl);
    }
}