org.testcontainers.containers.PostgreSQLContainer Java Examples
The following examples show how to use
org.testcontainers.containers.PostgreSQLContainer.
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: DITestingConfiguration.java From waltz with Apache License 2.0 | 6 votes |
@Bean public DataSource dataSource() { HikariConfig dsConfig = new HikariConfig(); postgreSQLContainer.start(); dsConfig.setJdbcUrl(format("jdbc:postgresql://%s:%s/%s", postgreSQLContainer.getContainerIpAddress(), postgreSQLContainer.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT), postgreSQLContainer.getDatabaseName())); dsConfig.setUsername(postgreSQLContainer.getUsername()); dsConfig.setPassword(postgreSQLContainer.getPassword()); dsConfig.setSchema("test"); dsConfig.setDriverClassName("org.postgresql.Driver"); dsConfig.setMaximumPoolSize(5); dsConfig.setMinimumIdle(2); return new HikariDataSource(dsConfig); }
Example #2
Source File: PgTemplateTestBase.java From vertx-sql-client with Apache License 2.0 | 5 votes |
@BeforeClass public static void startDatabase() { server = new PostgreSQLContainer("postgres:" + "10.10") .withDatabaseName("postgres") .withUsername("postgres") .withPassword("postgres"); server.start(); }
Example #3
Source File: PostgreSqlContainerLiveTest.java From tutorials with MIT License | 5 votes |
private ResultSet performQuery(PostgreSQLContainer postgres, String query) throws SQLException { String jdbcUrl = postgres.getJdbcUrl(); String username = postgres.getUsername(); String password = postgres.getPassword(); Connection conn = DriverManager.getConnection(jdbcUrl, username, password); return conn.createStatement() .executeQuery(query); }
Example #4
Source File: SimplePostgreSQLTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void testWithAdditionalUrlParamInJdbcUrl() { try (PostgreSQLContainer postgres = new PostgreSQLContainer<>() .withUrlParam("charSet", "UNICODE")) { postgres.start(); String jdbcUrl = postgres.getJdbcUrl(); assertThat(jdbcUrl, containsString("?")); assertThat(jdbcUrl, containsString("&")); assertThat(jdbcUrl, containsString("charSet=UNICODE")); } }
Example #5
Source File: SimplePostgreSQLTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void testExplicitInitScript() throws SQLException { try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>().withInitScript("somepath/init_postgresql.sql")) { postgres.start(); ResultSet resultSet = performQuery(postgres, "SELECT foo FROM bar"); String firstColumnValue = resultSet.getString(1); assertEquals("Value from init script should equal real value", "hello world", firstColumnValue); } }
Example #6
Source File: SimplePostgreSQLTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void testUnsetCommand() throws SQLException { try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>().withCommand("postgres -c max_connections=42").withCommand()) { postgres.start(); ResultSet resultSet = performQuery(postgres, "SELECT current_setting('max_connections')"); String result = resultSet.getString(1); assertNotEquals("max_connections should not be overriden", "42", result); } }
Example #7
Source File: SimplePostgreSQLTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void testCommandOverride() throws SQLException { try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>().withCommand("postgres -c max_connections=42")) { postgres.start(); ResultSet resultSet = performQuery(postgres, "SELECT current_setting('max_connections')"); String result = resultSet.getString(1); assertEquals("max_connections should be overriden", "42", result); } }
Example #8
Source File: SimplePostgreSQLTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void testSimple() throws SQLException { try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>()) { postgres.start(); ResultSet resultSet = performQuery(postgres, "SELECT 1"); int resultSetInt = resultSet.getInt(1); assertEquals("A basic SELECT query succeeds", 1, resultSetInt); } }
Example #9
Source File: CustomizablePostgreSQLTest.java From testcontainers-java with MIT License | 5 votes |
@Test public void testSimple() throws SQLException { try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:9.6.8") .withDatabaseName(DB_NAME) .withUsername(USER) .withPassword(PWD)) { postgres.start(); ResultSet resultSet = performQuery(postgres, "SELECT 1"); int resultSetInt = resultSet.getInt(1); assertEquals("A basic SELECT query succeeds", 1, resultSetInt); } }
Example #10
Source File: JpaTransactionManagerRule.java From nomulus with Apache License 2.0 | 5 votes |
private static JdbcDatabaseContainer create() { PostgreSQLContainer container = new PostgreSQLContainer(NomulusPostgreSql.getDockerTag()) .withDatabaseName(POSTGRES_DB_NAME); container.start(); return container; }
Example #11
Source File: PgTemplateTestBase.java From vertx-sql-client with Apache License 2.0 | 5 votes |
public static PgConnectOptions connectOptions() { Integer port = server.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT); String ip = server.getContainerIpAddress(); return new PgConnectOptions() .setPort(port) .setHost(ip) .setDatabase("postgres") .setUser("postgres") .setPassword("postgres"); }
Example #12
Source File: ContainerPgRule.java From vertx-sql-client with Apache License 2.0 | 5 votes |
public synchronized PgConnectOptions startServer(String databaseVersion) throws Exception { initServer(databaseVersion); server.start(); return new PgConnectOptions() .setPort(server.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT)) .setHost(server.getContainerIpAddress()) .setDatabase("postgres") .setUser("postgres") .setPassword("postgres"); }
Example #13
Source File: ContainerPgRule.java From vertx-sql-client with Apache License 2.0 | 5 votes |
private void initServer(String version) throws Exception { File setupFile = getTestResource("resources" + File.separator + "create-postgres.sql"); server = (PostgreSQLContainer) new PostgreSQLContainer("postgres:" + version) .withDatabaseName("postgres") .withUsername("postgres") .withPassword("postgres") .withCopyFileToContainer(MountableFile.forHostPath(setupFile.toPath()), "/docker-entrypoint-initdb.d/create-postgres.sql"); if(ssl) { server.withCopyFileToContainer(MountableFile.forHostPath(getTestResource("resources" +File.separator + "server.crt").toPath()), "/server.crt") .withCopyFileToContainer(MountableFile.forHostPath(getTestResource("resources" +File.separator + "server.key").toPath()), "/server.key") .withCopyFileToContainer(MountableFile.forHostPath(getTestResource("ssl.sh").toPath()), "/docker-entrypoint-initdb.d/ssl.sh"); } }
Example #14
Source File: DockerPostgresDatabaseProvider.java From embedded-database-spring-test with Apache License 2.0 | 5 votes |
private DatabaseInstance(DatabaseConfig config) { String initdbArgs = config.initdbProperties.entrySet().stream() .map(e -> String.format("--%s=%s", e.getKey(), e.getValue())) .collect(Collectors.joining(" ")); Map<String, String> serverProperties = new HashMap<>(config.configProperties); serverProperties.putIfAbsent("fsync", "off"); serverProperties.putIfAbsent("full_page_writes", "off"); serverProperties.putIfAbsent("max_connections", "300"); String postgresArgs = serverProperties.entrySet().stream() .map(e -> String.format("-c %s=%s", e.getKey(), e.getValue())) .collect(Collectors.joining(" ")); container = new PostgreSQLContainer(config.dockerImage) { @Override protected void configure() { super.configure(); addEnv("POSTGRES_INITDB_ARGS", "--nosync " + initdbArgs); setCommand("postgres " + postgresArgs); } }; if (config.tmpfsEnabled) { Consumer<CreateContainerCmd> consumer = cmd -> cmd.getHostConfig() .withTmpFs(ImmutableMap.of("/var/lib/postgresql/data", config.tmpfsOptions)); container.withCreateContainerCmdModifier(consumer); } container.withUsername(DEFAULT_POSTGRES_USERNAME); container.withPassword(DEFAULT_POSTGRES_PASSWORD); config.customizers.forEach(c -> c.customize(container)); container.start(); container.followOutput(new Slf4jLogConsumer(LoggerFactory.getLogger(DockerPostgresDatabaseProvider.class))); semaphore = new Semaphore(Integer.parseInt(serverProperties.get("max_connections"))); }
Example #15
Source File: TestingPostgreSqlServer.java From presto with Apache License 2.0 | 5 votes |
public TestingPostgreSqlServer() { dockerContainer = new PostgreSQLContainer("postgres:10.3") .withDatabaseName(DATABASE) .withUsername(USER) .withPassword(PASSWORD); dockerContainer.start(); }
Example #16
Source File: DebeziumPostgresTestResource.java From camel-quarkus with Apache License 2.0 | 5 votes |
@Override protected PostgreSQLContainer createContainer() { return new PostgreSQLContainer<>(POSTGRES_IMAGE) .withUsername(DB_USERNAME) .withPassword(DB_PASSWORD) .withDatabaseName(DebeziumPostgresResource.DB_NAME) .withInitScript("initPostgres.sql"); }
Example #17
Source File: ConnectUtil.java From pgadba with BSD 2-Clause "Simplified" License | 5 votes |
/** * Opens a DataSource to the supplied database. * @param postgres the docker database * @return a datasource */ public static DataSource openDb(PostgreSQLContainer postgres) { return DataSourceFactory.newFactory("org.postgresql.adba.PgDataSourceFactory") .builder() .url("jdbc:postgresql://" + postgres.getContainerIpAddress() + ":" + postgres.getMappedPort(5432) + "/" + postgres.getDatabaseName()) .username(postgres.getUsername()) .password(postgres.getPassword()) .sessionProperty(AdbaSessionProperty.TRANSACTION_ISOLATION, AdbaSessionProperty.TransactionIsolation.REPEATABLE_READ) .build(); }
Example #18
Source File: ConnectUtil.java From pgadba with BSD 2-Clause "Simplified" License | 5 votes |
/** * Opens a DataSource to the supplied database that sends all traffic over tls. * @param postgres the docker database * @return a datasource */ public static DataSource openDbWithTls(PostgreSQLContainer postgres) { return DataSourceFactory.newFactory("org.postgresql.adba.PgDataSourceFactory") .builder() .url("jdbc:postgresql://" + postgres.getContainerIpAddress() + ":" + postgres.getMappedPort(5432) + "/" + postgres.getDatabaseName()) .username(postgres.getUsername()) .password(postgres.getPassword()) .sessionProperty(AdbaSessionProperty.TRANSACTION_ISOLATION, AdbaSessionProperty.TransactionIsolation.REPEATABLE_READ) .sessionProperty(PgSessionProperty.SSL, true) .build(); }
Example #19
Source File: DatabaseHolder.java From pgadba with BSD 2-Clause "Simplified" License | 5 votes |
/** * returns a new database, instead of the cached one. * @return a docker instance running a postgresql database */ public static PostgreSQLContainer getNew() { PostgreSQLContainer container = new PostgreSQLContainer(); container.withTmpFs(singletonMap("/var/lib/postgresql/data", "rw")); container.start(); return container; }
Example #20
Source File: DatabaseHolder.java From pgadba with BSD 2-Clause "Simplified" License | 5 votes |
/** * returns a new database that requires TLS, instead of the cached one. * @return a docker instance running a postgresql database */ public static PostgreSQLContainer getNewWithTls() { PostgreSQLContainer container = new PostgreSQLContainer("capitol/postgresql-tls:debian-stretch-postgresql10"); container.withTmpFs(singletonMap("/var/lib/postgresql/data", "rw")); container.start(); return container; }
Example #21
Source File: DatabaseHolder.java From pgadba with BSD 2-Clause "Simplified" License | 5 votes |
/** * returns a new database that that runs postgresql 11. * @return a docker instance running a postgresql 11 database */ public static PostgreSQLContainer getNew11() { PostgreSQLContainer container = new PostgreSQLContainer("capitol/debian-buster-postgresql11-tls:latest"); container.withTmpFs(singletonMap("/var/lib/postgresql/data", "rw")); container.start(); return container; }
Example #22
Source File: SqlMetaDataITCase.java From syndesis with Apache License 2.0 | 5 votes |
@SuppressWarnings("resource") @Parameters public static Collection<Object> databaseContainerImages() { return Arrays.asList( //new DerbyContainer(), // new PostgreSQLContainer<>(), new MariaDBContainer<>() ); }
Example #23
Source File: GenerateSqlSchemaCommand.java From nomulus with Apache License 2.0 | 4 votes |
@Override public void run() { // Start PostgreSQL if requested. if (startPostgresql) { // Complain if the user has also specified either --db_host or --db_port. if (databaseHost != null || databasePort != null) { System.err.println(DB_OPTIONS_CLASH); // TODO: it would be nice to exit(1) here, but this breaks testability. return; } // Start the container and store the address information. postgresContainer = new PostgreSQLContainer(NomulusPostgreSql.getDockerTag()) .withDatabaseName(DB_NAME) .withUsername(DB_USERNAME) .withPassword(DB_PASSWORD); postgresContainer.start(); databaseHost = postgresContainer.getContainerIpAddress(); databasePort = postgresContainer.getMappedPort(POSTGRESQL_PORT); } else if (databaseHost == null) { System.err.println( "You must specify either --start_postgresql to start a PostgreSQL database in a\n" + "docker instance, or specify --db_host (and, optionally, --db_port) to identify\n" + "the location of a running instance. To start a long-lived instance (suitable\n" + "for running this command multiple times) run this:\n\n" + " docker run --rm --name some-postgres -e POSTGRES_PASSWORD=domain-registry \\\n" + " -d postgres:9.6.12\n\n" + "Copy the container id output from the command, then run:\n\n" + " docker inspect <container-id> | grep IPAddress\n\n" + "To obtain the value for --db-host.\n"); // TODO(mmuller): need exit(1), see above. return; } // use the default port if non has been defined. if (databasePort == null) { databasePort = POSTGRESQL_PORT; } try { File outputFile = new File(outFile); // Generate the copyright header (this file gets checked for copyright). The schema exporter // appends to the existing file, so this has the additional desired effect of clearing any // existing data in the file. String copyright = "-- Copyright 2019 The Nomulus Authors. All Rights Reserved.\n" + "--\n" + "-- Licensed under the Apache License, Version 2.0 (the \"License\");\n" + "-- you may not use this file except in compliance with the License.\n" + "-- You may obtain a copy of the License at\n" + "--\n" + "-- http://www.apache.org/licenses/LICENSE-2.0\n" + "--\n" + "-- Unless required by applicable law or agreed to in writing, software\n" + "-- distributed under the License is distributed on an \"AS IS\" BASIS,\n" + "-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + "-- See the License for the specific language governing permissions and\n" + "-- limitations under the License.\n"; try { Files.write(outputFile.toPath(), copyright.getBytes(UTF_8)); } catch (IOException e) { System.err.println("Error writing sql file: " + e); e.printStackTrace(); System.exit(1); } HibernateSchemaExporter exporter = HibernateSchemaExporter.create( "jdbc:postgresql://" + databaseHost + ":" + databasePort + "/" + DB_NAME + "?useSSL=false", DB_USERNAME, DB_PASSWORD); exporter.export(PersistenceXmlUtility.getManagedClasses(), outputFile); } finally { if (postgresContainer != null) { postgresContainer.stop(); } } }
Example #24
Source File: PostgresqlCommand.java From nomulus with Apache License 2.0 | 4 votes |
/** * Starts the database if appropriate. * * <p>Returns true if the database was successfully initialized, false if not. */ private boolean initializeDatabase() { // Start PostgreSQL if requested. if (startPostgresql) { // Complain if the user has also specified either --db_host or --db_port. if (databaseHost != null || databasePort != null) { System.err.println(DB_OPTIONS_CLASH); // TODO: it would be nice to exit(1) here, but this breaks testability. return false; } // Start the container and store the address information. postgresContainer = new PostgreSQLContainer(NomulusPostgreSql.getDockerTag()) .withDatabaseName(DB_NAME) .withUsername(DB_USERNAME) .withPassword(DB_PASSWORD); try { onContainerCreate(); } catch (Exception e) { logger.atSevere().withCause(e).log("Error in container callback hook."); return false; } postgresContainer.start(); databaseHost = postgresContainer.getContainerIpAddress(); databasePort = postgresContainer.getMappedPort(POSTGRESQL_PORT); } else if (databaseHost == null) { System.err.println( "You must specify either --start_postgresql to start a PostgreSQL database in a\n" + "docker instance, or specify --db_host (and, optionally, --db_port) to identify\n" + "the location of a running instance. To start a long-lived instance (suitable\n" + "for running this command multiple times) run this:\n\n" + " docker run --rm --name some-postgres -e POSTGRES_PASSWORD=domain-registry \\\n" + " -d " + NomulusPostgreSql.getDockerTag() + "\n\nCopy the container id output from the command, then run:\n\n" + " docker inspect <container-id> | grep IPAddress\n\n" + "To obtain the value for --db-host.\n"); // TODO(mmuller): need exit(1), see above. return false; } // use the default port if non has been defined. if (databasePort == null) { databasePort = POSTGRESQL_PORT; } return true; }
Example #25
Source File: JdbcPostgresSinkTester.java From pulsar with Apache License 2.0 | 4 votes |
@Override protected PostgreSQLContainer createSinkService(PulsarCluster cluster) { return (PostgreSQLContainer) new PostgreSQLContainer() .withNetworkAliases(POSTGRES); }
Example #26
Source File: DatabaseHolder.java From pgadba with BSD 2-Clause "Simplified" License | 4 votes |
public static PostgreSQLContainer getCached() { return postgres; }
Example #27
Source File: VaultTestExtension.java From quarkus with Apache License 2.0 | 4 votes |
public void start() throws InterruptedException, IOException { log.info("start containers on " + System.getProperty("os.name")); new File(HOST_POSTGRES_TMP_CMD).mkdirs(); Network network = Network.newNetwork(); postgresContainer = new PostgreSQLContainer<>() .withDatabaseName(DB_NAME) .withUsername(DB_USERNAME) .withPassword(DB_PASSWORD) .withNetwork(network) .withFileSystemBind(HOST_POSTGRES_TMP_CMD, CONTAINER_TMP_CMD) .withNetworkAliases(POSTGRESQL_HOST) .withExposedPorts(POSTGRESQL_PORT) .withClasspathResourceMapping("postgres-init.sql", TMP_POSTGRES_INIT_SQL_FILE, READ_ONLY); postgresContainer.setPortBindings(Arrays.asList(MAPPED_POSTGRESQL_PORT + ":" + POSTGRESQL_PORT)); String configFile = useTls() ? "vault-config-tls.json" : "vault-config.json"; log.info("starting vault with url=" + VAULT_URL + " and config file=" + configFile); new File(HOST_VAULT_TMP_CMD).mkdirs(); vaultContainer = new GenericContainer<>("vault:" + getVaultVersion()) .withExposedPorts(VAULT_PORT) .withEnv("SKIP_SETCAP", "true") .withEnv("VAULT_SKIP_VERIFY", "true") // this is internal to the container .withEnv("VAULT_ADDR", VAULT_URL) .withNetwork(network) .withFileSystemBind(HOST_VAULT_TMP_CMD, CONTAINER_TMP_CMD) .withClasspathResourceMapping(configFile, TMP_VAULT_CONFIG_JSON_FILE, READ_ONLY) .withClasspathResourceMapping("vault-tls.key", "/tmp/vault-tls.key", READ_ONLY) .withClasspathResourceMapping("vault-tls.crt", "/tmp/vault-tls.crt", READ_ONLY) .withClasspathResourceMapping("vault.policy", TMP_VAULT_POLICY_FILE, READ_ONLY) .withClasspathResourceMapping("vault-postgres-creation.sql", TMP_VAULT_POSTGRES_CREATION_SQL_FILE, READ_ONLY) .withCommand("server", "-log-level=debug", "-config=" + TMP_VAULT_CONFIG_JSON_FILE); vaultContainer.setPortBindings(Arrays.asList(VAULT_PORT + ":" + VAULT_PORT)); postgresContainer.start(); execPostgres(format("psql -U %s -d %s -f %s", DB_USERNAME, DB_NAME, TMP_POSTGRES_INIT_SQL_FILE)); Consumer<OutputFrame> consumer = outputFrame -> System.out.print("VAULT >> " + outputFrame.getUtf8String()); vaultContainer.setLogConsumers(Arrays.asList(consumer)); vaultContainer.start(); initVault(); log.info("vault has started with root token: " + rootToken); }
Example #28
Source File: KafkaConnectConverterIT.java From apicurio-registry with Apache License 2.0 | 4 votes |
private Connection getConnection(PostgreSQLContainer<?> postgresContainer) throws SQLException { return DriverManager.getConnection(postgresContainer.getJdbcUrl(), postgresContainer.getUsername(), postgresContainer.getPassword()); }
Example #29
Source File: DatabaseContainers.java From spring-session with Apache License 2.0 | 4 votes |
static PostgreSQLContainer postgreSql9() { return new PostgreSql9Container(); }
Example #30
Source File: DatabaseContainers.java From spring-session with Apache License 2.0 | 4 votes |
static PostgreSQLContainer postgreSql10() { return new PostgreSql10Container(); }