getTestPreparers();
29 |
30 | EmbeddedDatabase getDatabase();
31 |
32 | ContextState getState();
33 |
34 | void apply(DatabasePreparer preparer);
35 |
36 | void reset();
37 |
38 | enum ContextState {
39 |
40 | INITIALIZING,
41 | FRESH,
42 | AHEAD,
43 | DIRTY
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/flyway/preparer/CleanFlywayDatabasePreparer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.flyway.preparer;
18 |
19 | import io.zonky.test.db.flyway.FlywayDescriptor;
20 | import io.zonky.test.db.flyway.FlywayWrapper;
21 |
22 | public class CleanFlywayDatabasePreparer extends FlywayDatabasePreparer {
23 |
24 | public CleanFlywayDatabasePreparer(FlywayDescriptor descriptor) {
25 | super(descriptor);
26 | }
27 |
28 | @Override
29 | public long estimatedDuration() {
30 | return 100;
31 | }
32 |
33 | @Override
34 | protected Object doOperation(FlywayWrapper wrapper) {
35 | wrapper.setCleanDisabled(false);
36 | return wrapper.clean();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/config/Provider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.config;
18 |
19 | import org.springframework.beans.factory.annotation.Qualifier;
20 | import org.springframework.context.annotation.Lazy;
21 |
22 | import java.lang.annotation.Documented;
23 | import java.lang.annotation.ElementType;
24 | import java.lang.annotation.Retention;
25 | import java.lang.annotation.RetentionPolicy;
26 | import java.lang.annotation.Target;
27 |
28 | @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
29 | @Retention(RetentionPolicy.RUNTIME)
30 | @Documented
31 | @Lazy
32 | @Qualifier
33 | public @interface Provider {
34 |
35 | String type();
36 |
37 | String database();
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/ProviderException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import org.springframework.core.NestedRuntimeException;
20 |
21 | public class ProviderException extends NestedRuntimeException {
22 |
23 | /**
24 | * Construct a new provider exception.
25 | *
26 | * @param message the exception message
27 | */
28 | public ProviderException(String message) {
29 | super(message);
30 | }
31 |
32 | /**
33 | * Construct a new provider exception.
34 | *
35 | * @param message the exception message
36 | * @param cause the cause
37 | */
38 | public ProviderException(String message, Throwable cause) {
39 | super(message, cause);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/support/SimpleDatabaseTemplate.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider.support;
18 |
19 | import io.zonky.test.db.provider.DatabaseTemplate;
20 |
21 | public class SimpleDatabaseTemplate implements DatabaseTemplate {
22 |
23 | private final String templateName;
24 | private final Runnable closeCallback;
25 |
26 | public SimpleDatabaseTemplate(String templateName, Runnable closeCallback) {
27 | this.templateName = templateName;
28 | this.closeCallback = closeCallback;
29 | }
30 |
31 | @Override
32 | public String getTemplateName() {
33 | return templateName;
34 | }
35 |
36 | @Override
37 | public synchronized void close() {
38 | closeCallback.run();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/util/AopProxyUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.util;
18 |
19 | import io.zonky.test.db.context.DatabaseTargetSource;
20 | import io.zonky.test.db.context.DatabaseContext;
21 | import org.springframework.aop.TargetSource;
22 | import org.springframework.aop.framework.Advised;
23 |
24 | import javax.sql.DataSource;
25 |
26 | public class AopProxyUtils {
27 |
28 | private AopProxyUtils() {}
29 |
30 | public static DatabaseContext getDatabaseContext(DataSource dataSource) {
31 | if (dataSource instanceof Advised) {
32 | TargetSource targetSource = ((Advised) dataSource).getTargetSource();
33 | if (targetSource instanceof DatabaseTargetSource) {
34 | return ((DatabaseTargetSource) targetSource).getContext();
35 | }
36 | }
37 | return null;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/DatabaseReplacePropertyIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package io.zonky.test.db;
2 |
3 | import io.zonky.test.db.context.DatabaseContext;
4 | import io.zonky.test.db.provider.DatabaseProvider;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.context.ApplicationContext;
9 | import org.springframework.test.context.ContextConfiguration;
10 | import org.springframework.test.context.TestPropertySource;
11 | import org.springframework.test.context.junit4.SpringRunner;
12 |
13 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
14 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.RefreshMode.AFTER_EACH_TEST_METHOD;
15 | import static org.assertj.core.api.Assertions.assertThat;
16 |
17 | @RunWith(SpringRunner.class)
18 | @TestPropertySource(properties = "zonky.test.database.replace=none")
19 | @AutoConfigureEmbeddedDatabase(type = POSTGRES, refresh = AFTER_EACH_TEST_METHOD)
20 | @ContextConfiguration
21 | public class DatabaseReplacePropertyIntegrationTest {
22 |
23 | @Autowired
24 | private ApplicationContext applicationContext;
25 | @Autowired
26 | private DatabaseProvider dockerPostgresDatabaseProvider;
27 |
28 | @Test
29 | public void noDatabaseContextShouldExist() {
30 | assertThat(dockerPostgresDatabaseProvider).isNotNull();
31 | assertThat(applicationContext.getBeanNamesForType(DatabaseContext.class)).isEmpty();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/preparer/RecordingDataSource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.preparer;
18 |
19 | import org.springframework.aop.framework.ProxyFactory;
20 |
21 | import javax.sql.DataSource;
22 | import java.lang.reflect.Modifier;
23 |
24 | public interface RecordingDataSource extends DataSource {
25 |
26 | ReplayableDatabasePreparer getPreparer();
27 |
28 | static RecordingDataSource wrap(DataSource dataSource) {
29 | ProxyFactory proxyFactory = new ProxyFactory(dataSource);
30 | proxyFactory.addAdvice(new RecordingMethodInterceptor());
31 | proxyFactory.addInterface(RecordingDataSource.class);
32 |
33 | if (!Modifier.isFinal(dataSource.getClass().getModifiers())) {
34 | proxyFactory.setProxyTargetClass(true);
35 | }
36 |
37 | return (RecordingDataSource) proxyFactory.getProxy();
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/DockerMSSQLProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package io.zonky.test.db.provider;
2 |
3 | import io.zonky.test.category.MSSQLTestSuite;
4 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
5 | import io.zonky.test.db.provider.mssql.MsSQLEmbeddedDatabase;
6 | import io.zonky.test.support.ConditionalTestRule;
7 | import io.zonky.test.support.TestAssumptions;
8 | import org.junit.ClassRule;
9 | import org.junit.Test;
10 | import org.junit.experimental.categories.Category;
11 | import org.junit.runner.RunWith;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.test.context.ContextConfiguration;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | import javax.sql.DataSource;
17 | import java.sql.SQLException;
18 |
19 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.MSSQL;
20 | import static org.assertj.core.api.Assertions.assertThat;
21 |
22 | @RunWith(SpringRunner.class)
23 | @Category(MSSQLTestSuite.class)
24 | @AutoConfigureEmbeddedDatabase(type = MSSQL)
25 | @ContextConfiguration
26 | public class DockerMSSQLProviderIntegrationTest {
27 |
28 | @ClassRule
29 | public static ConditionalTestRule conditionalTestRule = new ConditionalTestRule(TestAssumptions::assumeLicenceAcceptance);
30 |
31 | @Autowired
32 | private DataSource dataSource;
33 |
34 | @Test
35 | public void testDataSource() throws SQLException {
36 | assertThat(dataSource.unwrap(MsSQLEmbeddedDatabase.class).getJdbcUrl()).contains("password=A_Str0ng_Required_Password");
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/derby/DerbyEmbeddedDatabase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider.derby;
18 |
19 | import io.zonky.test.db.provider.support.AbstractEmbeddedDatabase;
20 |
21 | import javax.sql.DataSource;
22 |
23 | public class DerbyEmbeddedDatabase extends AbstractEmbeddedDatabase {
24 |
25 | private final DataSource dataSource;
26 | private final String dbName;
27 |
28 | public DerbyEmbeddedDatabase(DataSource dataSource, String dbName, Runnable closeCallback) {
29 | super(closeCallback);
30 | this.dataSource = dataSource;
31 | this.dbName = dbName;
32 | }
33 |
34 | @Override
35 | protected DataSource getDataSource() {
36 | return dataSource;
37 | }
38 |
39 | @Override
40 | public String getJdbcUrl() {
41 | return String.format("jdbc:derby:memory:%s;user=sa", dbName);
42 | }
43 |
44 | public String getDatabaseName() {
45 | return dbName;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/hsqldb/HSQLEmbeddedDatabase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider.hsqldb;
18 |
19 | import io.zonky.test.db.provider.support.AbstractEmbeddedDatabase;
20 |
21 | import javax.sql.DataSource;
22 |
23 | public class HSQLEmbeddedDatabase extends AbstractEmbeddedDatabase {
24 |
25 | private final DataSource dataSource;
26 | private final String dbName;
27 |
28 | public HSQLEmbeddedDatabase(DataSource dataSource, String dbName, Runnable closeCallback) {
29 | super(closeCallback);
30 | this.dataSource = dataSource;
31 | this.dbName = dbName;
32 | }
33 |
34 | @Override
35 | protected DataSource getDataSource() {
36 | return dataSource;
37 | }
38 |
39 | @Override
40 | public String getJdbcUrl() {
41 | return String.format("jdbc:hsqldb:mem:%s;user=sa", dbName);
42 | }
43 |
44 | public String getDatabaseName() {
45 | return dbName;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/DatabaseRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.db.preparer.DatabasePreparer;
20 |
21 | public class DatabaseRequest {
22 |
23 | private final DatabasePreparer preparer;
24 | private final DatabaseTemplate template;
25 |
26 | public static DatabaseRequest of(DatabasePreparer preparer) {
27 | return new DatabaseRequest(preparer, null);
28 | }
29 |
30 | public static DatabaseRequest of(DatabasePreparer preparer, DatabaseTemplate template) {
31 | return new DatabaseRequest(preparer, template);
32 | }
33 |
34 | private DatabaseRequest(DatabasePreparer preparer, DatabaseTemplate template) {
35 | this.template = template;
36 | this.preparer = preparer;
37 | }
38 |
39 | public DatabasePreparer getPreparer() {
40 | return preparer;
41 | }
42 |
43 | public DatabaseTemplate getTemplate() {
44 | return template;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/support/DatabaseDefinition.java:
--------------------------------------------------------------------------------
1 | package io.zonky.test.db.support;
2 |
3 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
4 |
5 | import java.util.Objects;
6 |
7 | public class DatabaseDefinition {
8 |
9 | private final String beanName;
10 | private final AutoConfigureEmbeddedDatabase.DatabaseType databaseType;
11 | private final AutoConfigureEmbeddedDatabase.DatabaseProvider providerType;
12 |
13 | public DatabaseDefinition(String beanName, AutoConfigureEmbeddedDatabase.DatabaseType databaseType, AutoConfigureEmbeddedDatabase.DatabaseProvider providerType) {
14 | this.beanName = beanName;
15 | this.databaseType = databaseType;
16 | this.providerType = providerType;
17 | }
18 |
19 | public String getBeanName() {
20 | return beanName;
21 | }
22 |
23 | public AutoConfigureEmbeddedDatabase.DatabaseType getDatabaseType() {
24 | return databaseType;
25 | }
26 |
27 | public AutoConfigureEmbeddedDatabase.DatabaseProvider getProviderType() {
28 | return providerType;
29 | }
30 |
31 | @Override
32 | public boolean equals(Object o) {
33 | if (this == o) return true;
34 | if (o == null || getClass() != o.getClass()) return false;
35 | DatabaseDefinition that = (DatabaseDefinition) o;
36 | return Objects.equals(beanName, that.beanName) &&
37 | databaseType == that.databaseType &&
38 | providerType == that.providerType;
39 | }
40 |
41 | @Override
42 | public int hashCode() {
43 | return Objects.hash(beanName, databaseType, providerType);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/resources/db/changelog/db.changelog-master.yaml:
--------------------------------------------------------------------------------
1 | databaseChangeLog:
2 | - changeSet:
3 | id: 1
4 | author: tomix26
5 | changes:
6 | - sql:
7 | sql: create schema test
8 | - changeSet:
9 | id: 2
10 | author: tomix26
11 | changes:
12 | - createTable:
13 | schemaName: test
14 | tableName: person
15 | columns:
16 | - column:
17 | name: id
18 | type: bigint
19 | constraints:
20 | primaryKey: true
21 | nullable: false
22 | - column:
23 | name: first_name
24 | type: varchar(255)
25 | constraints:
26 | nullable: false
27 | - column:
28 | name: surname
29 | type: varchar(255)
30 | constraints:
31 | nullable: false
32 | - changeSet:
33 | id: 3
34 | author: tomix26
35 | changes:
36 | - insert:
37 | schemaName: test
38 | tableName: person
39 | columns:
40 | - column:
41 | name: id
42 | value: 1
43 | - column:
44 | name: first_name
45 | value: Dave
46 | - column:
47 | name: surname
48 | value: Syer
49 | - changeSet:
50 | id: 4
51 | author: tomix26
52 | changes:
53 | - renameColumn:
54 | schemaName: test
55 | tableName: person
56 | oldColumnName: surname
57 | newColumnName: last_name
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/mysql/MySQLEmbeddedDatabase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider.mysql;
18 |
19 | import com.mysql.cj.jdbc.MysqlDataSource;
20 | import io.zonky.test.db.provider.support.AbstractEmbeddedDatabase;
21 | import org.springframework.util.StringUtils;
22 |
23 | import javax.sql.DataSource;
24 |
25 | public class MySQLEmbeddedDatabase extends AbstractEmbeddedDatabase {
26 |
27 | private final MysqlDataSource dataSource;
28 |
29 | public MySQLEmbeddedDatabase(MysqlDataSource dataSource, Runnable closeCallback) {
30 | super(closeCallback);
31 | this.dataSource = dataSource;
32 | }
33 |
34 | @Override
35 | protected DataSource getDataSource() {
36 | return dataSource;
37 | }
38 |
39 | @Override
40 | public String getJdbcUrl() {
41 | String url = dataSource.getUrl() + String.format("?user=%s", dataSource.getUser());
42 | if (StringUtils.hasText(dataSource.getPassword())) {
43 | url += String.format("&password=%s", dataSource.getPassword());
44 | }
45 | return url;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/DefaultProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
20 | import org.junit.Test;
21 | import org.junit.runner.RunWith;
22 | import org.postgresql.ds.PGSimpleDataSource;
23 | import org.springframework.beans.factory.annotation.Autowired;
24 | import org.springframework.test.context.ContextConfiguration;
25 | import org.springframework.test.context.junit4.SpringRunner;
26 |
27 | import javax.sql.DataSource;
28 | import java.sql.SQLException;
29 |
30 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
31 | import static org.assertj.core.api.Assertions.assertThat;
32 |
33 | @RunWith(SpringRunner.class)
34 | @AutoConfigureEmbeddedDatabase(type = POSTGRES)
35 | @ContextConfiguration
36 | public class DefaultProviderIntegrationTest {
37 |
38 | @Autowired
39 | private DataSource dataSource;
40 |
41 | @Test
42 | public void testDataSource() throws SQLException {
43 | assertThat(dataSource.unwrap(PGSimpleDataSource.class)).isNotNull();
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/util/StringUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.util;
18 |
19 | import org.springframework.util.ObjectUtils;
20 |
21 | public class StringUtils {
22 |
23 | private StringUtils() {}
24 |
25 | public static boolean startsWithAny(String input, String... searchStrings) {
26 | if (org.springframework.util.StringUtils.isEmpty(input) || ObjectUtils.isEmpty(searchStrings)) {
27 | return false;
28 | }
29 | for (String searchString : searchStrings) {
30 | if (input.startsWith(searchString)) {
31 | return true;
32 | }
33 | }
34 | return false;
35 | }
36 |
37 | public static boolean endsWithAny(String input, String... searchStrings) {
38 | if (org.springframework.util.StringUtils.isEmpty(input) || ObjectUtils.isEmpty(searchStrings)) {
39 | return false;
40 | }
41 | for (String searchString : searchStrings) {
42 | if (input.endsWith(searchString)) {
43 | return true;
44 | }
45 | }
46 | return false;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/postgres/PostgresEmbeddedDatabase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider.postgres;
18 |
19 | import io.zonky.test.db.provider.support.AbstractEmbeddedDatabase;
20 | import org.postgresql.ds.PGSimpleDataSource;
21 | import org.springframework.util.StringUtils;
22 |
23 | import javax.sql.DataSource;
24 |
25 | public class PostgresEmbeddedDatabase extends AbstractEmbeddedDatabase {
26 |
27 | private final PGSimpleDataSource dataSource;
28 |
29 | public PostgresEmbeddedDatabase(PGSimpleDataSource dataSource, Runnable closeCallback) {
30 | super(closeCallback);
31 | this.dataSource = dataSource;
32 | }
33 |
34 | @Override
35 | protected DataSource getDataSource() {
36 | return dataSource;
37 | }
38 |
39 | @Override
40 | public String getJdbcUrl() {
41 | String url = dataSource.getUrl() + String.format("?user=%s", dataSource.getUser());
42 | if (StringUtils.hasText(dataSource.getPassword())) {
43 | url += String.format("&password=%s", dataSource.getPassword());
44 | }
45 | return url;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/liquibase/LiquibasePropertiesPostProcessor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.liquibase;
18 |
19 | import org.springframework.beans.BeansException;
20 | import org.springframework.beans.factory.config.BeanPostProcessor;
21 | import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
22 | import org.springframework.core.Ordered;
23 |
24 | public class LiquibasePropertiesPostProcessor implements BeanPostProcessor, Ordered {
25 |
26 | @Override
27 | public int getOrder() {
28 | return Ordered.LOWEST_PRECEDENCE - 1;
29 | }
30 |
31 | @Override
32 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
33 | return bean;
34 | }
35 |
36 | @Override
37 | public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
38 | if (bean instanceof LiquibaseProperties) {
39 | LiquibaseProperties properties = (LiquibaseProperties) bean;
40 | properties.setUrl(null);
41 | properties.setUser(null);
42 | properties.setPassword(null);
43 | }
44 | return bean;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/H2ProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.H2TestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import org.junit.Test;
22 | import org.junit.experimental.categories.Category;
23 | import org.junit.runner.RunWith;
24 | import org.springframework.beans.factory.annotation.Autowired;
25 | import org.springframework.test.context.ContextConfiguration;
26 | import org.springframework.test.context.junit4.SpringRunner;
27 |
28 | import javax.sql.DataSource;
29 | import java.sql.SQLException;
30 |
31 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.H2;
32 | import static org.assertj.core.api.Assertions.assertThat;
33 |
34 | @RunWith(SpringRunner.class)
35 | @Category(H2TestSuite.class)
36 | @AutoConfigureEmbeddedDatabase(type = H2)
37 | @ContextConfiguration
38 | public class H2ProviderIntegrationTest {
39 |
40 | @Autowired
41 | private DataSource dataSource;
42 |
43 | @Test
44 | public void testDataSource() throws SQLException {
45 | assertThat(dataSource.unwrap(EmbeddedDatabase.class).getJdbcUrl()).startsWith("jdbc:h2:");
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/logging/EmbeddedDatabaseReporter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.logging;
18 |
19 | import io.zonky.test.db.provider.EmbeddedDatabase;
20 | import org.slf4j.Logger;
21 | import org.slf4j.LoggerFactory;
22 |
23 | import java.lang.reflect.AnnotatedElement;
24 | import java.lang.reflect.Method;
25 |
26 | public class EmbeddedDatabaseReporter {
27 |
28 | private static final Logger logger = LoggerFactory.getLogger(EmbeddedDatabaseReporter.class);
29 |
30 | public static void reportDataSource(String beanName, EmbeddedDatabase database, AnnotatedElement element) {
31 | logger.info("JDBC URL to connect to '{}': url='{}', scope='{}'", beanName, database.getJdbcUrl(), getElementName(element));
32 | }
33 |
34 | private static String getElementName(AnnotatedElement element) {
35 | if (element instanceof Class>) {
36 | return ((Class>) element).getSimpleName();
37 | } else if (element instanceof Method) {
38 | Method method = (Method) element;
39 | return getElementName(method.getDeclaringClass()) + "#" + method.getName();
40 | } else {
41 | return element.toString();
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/liquibase/LiquibaseDatabasePreparerTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.liquibase;
18 |
19 | import io.zonky.test.category.LiquibaseTestSuite;
20 | import liquibase.integration.spring.SpringLiquibase;
21 | import org.junit.Before;
22 | import org.junit.Test;
23 | import org.junit.experimental.categories.Category;
24 | import org.springframework.core.io.DefaultResourceLoader;
25 |
26 | import static org.assertj.core.api.Assertions.assertThat;
27 |
28 | @Category(LiquibaseTestSuite.class)
29 | public class LiquibaseDatabasePreparerTest {
30 |
31 | private LiquibaseDatabasePreparer preparer;
32 |
33 | @Before
34 | public void setUp() throws Exception {
35 | SpringLiquibase liquibase = new SpringLiquibase();
36 | liquibase.setChangeLog("classpath:/db/changelog/db.changelog-master.yaml");
37 | liquibase.setResourceLoader(new DefaultResourceLoader());
38 | LiquibaseDescriptor descriptor = LiquibaseDescriptor.from(liquibase);
39 |
40 | preparer = new LiquibaseDatabasePreparer(descriptor);
41 | }
42 |
43 | @Test
44 | public void estimatedDuration() {
45 | assertThat(preparer.estimatedDuration()).isEqualTo(214);
46 | }
47 | }
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/HSQLProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.HSQLTestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import org.junit.Test;
22 | import org.junit.experimental.categories.Category;
23 | import org.junit.runner.RunWith;
24 | import org.springframework.beans.factory.annotation.Autowired;
25 | import org.springframework.test.context.ContextConfiguration;
26 | import org.springframework.test.context.junit4.SpringRunner;
27 |
28 | import javax.sql.DataSource;
29 | import java.sql.SQLException;
30 |
31 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.HSQL;
32 | import static org.assertj.core.api.Assertions.assertThat;
33 |
34 | @RunWith(SpringRunner.class)
35 | @Category(HSQLTestSuite.class)
36 | @AutoConfigureEmbeddedDatabase(type = HSQL)
37 | @ContextConfiguration
38 | public class HSQLProviderIntegrationTest {
39 |
40 | @Autowired
41 | private DataSource dataSource;
42 |
43 | @Test
44 | public void testDataSource() throws SQLException {
45 | assertThat(dataSource.unwrap(EmbeddedDatabase.class).getJdbcUrl()).startsWith("jdbc:hsqldb:");
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/DerbyProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.DerbyTestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import org.junit.Test;
22 | import org.junit.experimental.categories.Category;
23 | import org.junit.runner.RunWith;
24 | import org.springframework.beans.factory.annotation.Autowired;
25 | import org.springframework.test.context.ContextConfiguration;
26 | import org.springframework.test.context.junit4.SpringRunner;
27 |
28 | import javax.sql.DataSource;
29 | import java.sql.SQLException;
30 |
31 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.DERBY;
32 | import static org.assertj.core.api.Assertions.assertThat;
33 |
34 | @RunWith(SpringRunner.class)
35 | @Category(DerbyTestSuite.class)
36 | @AutoConfigureEmbeddedDatabase(type = DERBY)
37 | @ContextConfiguration
38 | public class DerbyProviderIntegrationTest {
39 |
40 | @Autowired
41 | private DataSource dataSource;
42 |
43 | @Test
44 | public void testDataSource() throws SQLException {
45 | assertThat(dataSource.unwrap(EmbeddedDatabase.class).getJdbcUrl()).startsWith("jdbc:derby:");
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/DockerMariaDBProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.MariaDBTestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import org.junit.Test;
22 | import org.junit.experimental.categories.Category;
23 | import org.junit.runner.RunWith;
24 | import org.springframework.beans.factory.annotation.Autowired;
25 | import org.springframework.test.context.ContextConfiguration;
26 | import org.springframework.test.context.junit4.SpringRunner;
27 |
28 | import javax.sql.DataSource;
29 | import java.sql.SQLException;
30 |
31 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.MARIADB;
32 | import static org.assertj.core.api.Assertions.assertThat;
33 |
34 | @RunWith(SpringRunner.class)
35 | @Category(MariaDBTestSuite.class)
36 | @AutoConfigureEmbeddedDatabase(type = MARIADB)
37 | @ContextConfiguration
38 | public class DockerMariaDBProviderIntegrationTest {
39 |
40 | @Autowired
41 | private DataSource dataSource;
42 |
43 | @Test
44 | public void testDataSource() throws SQLException {
45 | assertThat(dataSource.unwrap(EmbeddedDatabase.class).getJdbcUrl()).contains("password=docker");
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/config/ProviderTypePropertyIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.config;
18 |
19 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
20 | import org.junit.Test;
21 | import org.junit.runner.RunWith;
22 | import org.postgresql.ds.PGSimpleDataSource;
23 | import org.springframework.beans.factory.annotation.Autowired;
24 | import org.springframework.test.context.ContextConfiguration;
25 | import org.springframework.test.context.TestPropertySource;
26 | import org.springframework.test.context.junit4.SpringRunner;
27 |
28 | import javax.sql.DataSource;
29 |
30 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
31 | import static org.assertj.core.api.Assertions.assertThat;
32 |
33 | @RunWith(SpringRunner.class)
34 | @AutoConfigureEmbeddedDatabase(type = POSTGRES)
35 | @TestPropertySource(properties = "zonky.test.database.provider=docker")
36 | @ContextConfiguration
37 | public class ProviderTypePropertyIntegrationTest {
38 |
39 | @Autowired
40 | private DataSource dataSource;
41 |
42 | @Test
43 | public void dockerProviderShouldBeUsed() throws Exception {
44 | assertThat(dataSource.unwrap(PGSimpleDataSource.class).getPassword()).isEqualTo("docker");
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/DockerMySQLProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import com.mysql.cj.jdbc.MysqlDataSource;
20 | import io.zonky.test.category.MySQLTestSuite;
21 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
22 | import org.junit.Test;
23 | import org.junit.experimental.categories.Category;
24 | import org.junit.runner.RunWith;
25 | import org.springframework.beans.factory.annotation.Autowired;
26 | import org.springframework.test.context.ContextConfiguration;
27 | import org.springframework.test.context.junit4.SpringRunner;
28 |
29 | import javax.sql.DataSource;
30 | import java.sql.SQLException;
31 |
32 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.MYSQL;
33 | import static org.assertj.core.api.Assertions.assertThat;
34 |
35 | @RunWith(SpringRunner.class)
36 | @Category(MySQLTestSuite.class)
37 | @AutoConfigureEmbeddedDatabase(type = MYSQL)
38 | @ContextConfiguration
39 | public class DockerMySQLProviderIntegrationTest {
40 |
41 | @Autowired
42 | private DataSource dataSource;
43 |
44 | @Test
45 | public void testDataSource() throws SQLException {
46 | assertThat(dataSource.unwrap(MysqlDataSource.class).getPassword()).isEqualTo("docker");
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/AutoConfigureEmbeddedDatabases.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db;
18 |
19 | import java.lang.annotation.Documented;
20 | import java.lang.annotation.ElementType;
21 | import java.lang.annotation.Inherited;
22 | import java.lang.annotation.Retention;
23 | import java.lang.annotation.RetentionPolicy;
24 | import java.lang.annotation.Target;
25 |
26 | /**
27 | * Container annotation that aggregates several {@link AutoConfigureEmbeddedDatabase} annotations.
28 | *
29 | * Can be used natively, declaring several nested {@link AutoConfigureEmbeddedDatabase} annotations.
30 | * Can also be used in conjunction with Java 8's support for repeatable annotations,
31 | * where {@link AutoConfigureEmbeddedDatabase} can simply be declared several times on the same
32 | * {@linkplain ElementType#TYPE type}, implicitly generating this container annotation.
33 | *
34 | * This annotation may be used as a meta-annotation to create custom composed annotations.
35 | *
36 | * @see AutoConfigureEmbeddedDatabase
37 | */
38 | @Documented
39 | @Inherited
40 | @Target(ElementType.TYPE)
41 | @Retention(RetentionPolicy.RUNTIME)
42 | public @interface AutoConfigureEmbeddedDatabases {
43 |
44 | AutoConfigureEmbeddedDatabase[] value();
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/init/EmbeddedDatabaseInitializer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.init;
18 |
19 | import io.zonky.test.db.context.DatabaseContext;
20 | import org.springframework.beans.BeansException;
21 | import org.springframework.beans.factory.config.BeanPostProcessor;
22 | import org.springframework.core.Ordered;
23 |
24 | public class EmbeddedDatabaseInitializer implements BeanPostProcessor, Ordered {
25 |
26 | private final ScriptDatabasePreparer scriptPreparer;
27 |
28 | public EmbeddedDatabaseInitializer(ScriptDatabasePreparer scriptPreparer) {
29 | this.scriptPreparer = scriptPreparer;
30 | }
31 |
32 | @Override
33 | public int getOrder() {
34 | return Ordered.HIGHEST_PRECEDENCE + 10;
35 | }
36 |
37 | @Override
38 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
39 | if (bean instanceof DatabaseContext && scriptPreparer != null) {
40 | DatabaseContext databaseContext = (DatabaseContext) bean;
41 | databaseContext.apply(scriptPreparer);
42 | }
43 | return bean;
44 | }
45 |
46 | @Override
47 | public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
48 | return bean;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/config/ProviderTypePriorityIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.config;
18 |
19 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
20 | import org.junit.Test;
21 | import org.junit.runner.RunWith;
22 | import org.postgresql.ds.PGSimpleDataSource;
23 | import org.springframework.beans.factory.annotation.Autowired;
24 | import org.springframework.test.context.ContextConfiguration;
25 | import org.springframework.test.context.TestPropertySource;
26 | import org.springframework.test.context.junit4.SpringRunner;
27 |
28 | import javax.sql.DataSource;
29 |
30 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseProvider.DOCKER;
31 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
32 | import static org.assertj.core.api.Assertions.assertThat;
33 |
34 | @RunWith(SpringRunner.class)
35 | @AutoConfigureEmbeddedDatabase(type = POSTGRES, provider = DOCKER)
36 | @TestPropertySource(properties = "zonky.test.database.provider=zonky")
37 | @ContextConfiguration
38 | public class ProviderTypePriorityIntegrationTest {
39 |
40 | @Autowired
41 | private DataSource dataSource;
42 |
43 | @Test
44 | public void dockerProviderShouldBeUsed() throws Exception {
45 | assertThat(dataSource.unwrap(PGSimpleDataSource.class).getPassword()).isEqualTo("docker");
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/ZonkyProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.PostgresTestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import org.junit.Test;
22 | import org.junit.experimental.categories.Category;
23 | import org.junit.runner.RunWith;
24 | import org.postgresql.ds.PGSimpleDataSource;
25 | import org.springframework.beans.factory.annotation.Autowired;
26 | import org.springframework.test.context.ContextConfiguration;
27 | import org.springframework.test.context.junit4.SpringRunner;
28 |
29 | import javax.sql.DataSource;
30 | import java.sql.SQLException;
31 |
32 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseProvider.EMBEDDED;
33 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
34 | import static org.assertj.core.api.Assertions.assertThat;
35 |
36 | @RunWith(SpringRunner.class)
37 | @Category(PostgresTestSuite.class)
38 | @AutoConfigureEmbeddedDatabase(type = POSTGRES, provider = EMBEDDED)
39 | @ContextConfiguration
40 | public class ZonkyProviderIntegrationTest {
41 |
42 | @Autowired
43 | private DataSource dataSource;
44 |
45 | @Test
46 | public void testDataSource() throws SQLException {
47 | assertThat(dataSource.unwrap(PGSimpleDataSource.class)).isNotNull();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/OpenTableProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.PostgresTestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import org.junit.Test;
22 | import org.junit.experimental.categories.Category;
23 | import org.junit.runner.RunWith;
24 | import org.postgresql.ds.PGSimpleDataSource;
25 | import org.springframework.beans.factory.annotation.Autowired;
26 | import org.springframework.test.context.ContextConfiguration;
27 | import org.springframework.test.context.junit4.SpringRunner;
28 |
29 | import javax.sql.DataSource;
30 | import java.sql.SQLException;
31 |
32 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseProvider.OPENTABLE;
33 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
34 | import static org.assertj.core.api.Assertions.assertThat;
35 |
36 | @RunWith(SpringRunner.class)
37 | @Category(PostgresTestSuite.class)
38 | @AutoConfigureEmbeddedDatabase(type = POSTGRES, provider = OPENTABLE)
39 | @ContextConfiguration
40 | public class OpenTableProviderIntegrationTest {
41 |
42 | @Autowired
43 | private DataSource dataSource;
44 |
45 | @Test
46 | public void testDataSource() throws SQLException {
47 | assertThat(dataSource.unwrap(PGSimpleDataSource.class)).isNotNull();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/DockerPostgresProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.PostgresTestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import org.junit.Test;
22 | import org.junit.experimental.categories.Category;
23 | import org.junit.runner.RunWith;
24 | import org.postgresql.ds.PGSimpleDataSource;
25 | import org.springframework.beans.factory.annotation.Autowired;
26 | import org.springframework.test.context.ContextConfiguration;
27 | import org.springframework.test.context.junit4.SpringRunner;
28 |
29 | import javax.sql.DataSource;
30 | import java.sql.SQLException;
31 |
32 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseProvider.DOCKER;
33 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
34 | import static org.assertj.core.api.Assertions.assertThat;
35 |
36 | @RunWith(SpringRunner.class)
37 | @Category(PostgresTestSuite.class)
38 | @AutoConfigureEmbeddedDatabase(type = POSTGRES, provider = DOCKER)
39 | @ContextConfiguration
40 | public class DockerPostgresProviderIntegrationTest {
41 |
42 | @Autowired
43 | private DataSource dataSource;
44 |
45 | @Test
46 | public void testDataSource() throws SQLException {
47 | assertThat(dataSource.unwrap(PGSimpleDataSource.class).getPassword()).isEqualTo("docker");
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/mssql/MsSQLEmbeddedDatabase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider.mssql;
18 |
19 | import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
20 | import io.zonky.test.db.provider.support.AbstractEmbeddedDatabase;
21 | import org.springframework.util.StringUtils;
22 |
23 | import javax.sql.DataSource;
24 |
25 | import static io.zonky.test.db.util.ReflectionUtils.invokeMethod;
26 |
27 | public class MsSQLEmbeddedDatabase extends AbstractEmbeddedDatabase {
28 |
29 | private final SQLServerDataSource dataSource;
30 |
31 | public MsSQLEmbeddedDatabase(SQLServerDataSource dataSource, Runnable closeCallback) {
32 | super(closeCallback);
33 | this.dataSource = dataSource;
34 | }
35 |
36 | @Override
37 | protected DataSource getDataSource() {
38 | return dataSource;
39 | }
40 |
41 | @Override
42 | public String getJdbcUrl() {
43 | String url = String.format("jdbc:sqlserver://%s:%s;databaseName=%s;user=%s",
44 | dataSource.getServerName(), dataSource.getPortNumber(), dataSource.getDatabaseName(), dataSource.getUser());
45 | if (StringUtils.hasText(getPassword())) {
46 | url += String.format(";password=%s", getPassword());
47 | }
48 | return url;
49 | }
50 |
51 | private String getPassword() {
52 | return invokeMethod(dataSource, "getPassword");
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/provider/h2/H2EmbeddedDatabase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider.h2;
18 |
19 | import io.zonky.test.db.provider.support.AbstractEmbeddedDatabase;
20 | import org.h2.tools.Server;
21 |
22 | import javax.sql.DataSource;
23 |
24 | public class H2EmbeddedDatabase extends AbstractEmbeddedDatabase {
25 |
26 | private final Server server;
27 | private final DataSource dataSource;
28 | private final String dbName;
29 |
30 | public H2EmbeddedDatabase(Server server, DataSource dataSource, String dbName, Runnable closeCallback) {
31 | super(closeCallback);
32 | this.server = server;
33 | this.dataSource = dataSource;
34 | this.dbName = dbName;
35 | }
36 |
37 | @Override
38 | protected DataSource getDataSource() {
39 | return dataSource;
40 | }
41 |
42 | @Override
43 | public String getJdbcUrl() {
44 | if (server != null) {
45 | return String.format("jdbc:h2:tcp://localhost:%s/mem:%s;USER=sa", server.getPort(), dbName);
46 | } else {
47 | return String.format("jdbc:h2:mem:%s;USER=sa", dbName);
48 | }
49 | }
50 |
51 | public String getDatabaseName() {
52 | return dbName;
53 | }
54 |
55 | public int getPortNumber() {
56 | if (server != null) {
57 | return server.getPort();
58 | } else {
59 | return 0;
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/ReplacingDefaultDataSourceIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db;
18 |
19 | import org.junit.Test;
20 | import org.junit.runner.RunWith;
21 | import org.postgresql.ds.PGSimpleDataSource;
22 | import org.springframework.beans.factory.annotation.Autowired;
23 | import org.springframework.context.annotation.Bean;
24 | import org.springframework.context.annotation.Configuration;
25 | import org.springframework.context.annotation.Primary;
26 | import org.springframework.test.context.ContextConfiguration;
27 | import org.springframework.test.context.junit4.SpringRunner;
28 |
29 | import javax.sql.DataSource;
30 |
31 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
32 | import static org.assertj.core.api.Assertions.assertThat;
33 | import static org.mockito.Mockito.mock;
34 |
35 | @RunWith(SpringRunner.class)
36 | @AutoConfigureEmbeddedDatabase(type = POSTGRES)
37 | @ContextConfiguration
38 | public class ReplacingDefaultDataSourceIntegrationTest {
39 |
40 | @Configuration
41 | static class Config {
42 |
43 | @Bean
44 | @Primary
45 | public DataSource dataSource() {
46 | return mock(DataSource.class, "mockDataSource");
47 | }
48 | }
49 |
50 | @Autowired
51 | private DataSource dataSource;
52 |
53 | @Test
54 | public void primaryDataSourceShouldBeReplaced() throws Exception {
55 | assertThat(dataSource.unwrap(PGSimpleDataSource.class)).isExactlyInstanceOf(PGSimpleDataSource.class);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/event/EventPublishingTestExecutionListener.java:
--------------------------------------------------------------------------------
1 | package io.zonky.test.db.event;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.context.ApplicationContext;
6 | import org.springframework.test.context.TestContext;
7 | import org.springframework.test.context.TestExecutionListener;
8 | import org.springframework.test.context.support.AbstractTestExecutionListener;
9 | import org.springframework.util.ClassUtils;
10 |
11 | public class EventPublishingTestExecutionListener extends AbstractTestExecutionListener {
12 |
13 | private static final Logger logger = LoggerFactory.getLogger(EventPublishingTestExecutionListener.class);
14 |
15 | private static final boolean TEST_EXECUTION_METHODS_SUPPORTED = ClassUtils.getMethodIfAvailable(
16 | TestExecutionListener.class, "beforeTestExecution", null) != null;
17 |
18 | @Override
19 | public void beforeTestMethod(TestContext testContext) {
20 | if (!TEST_EXECUTION_METHODS_SUPPORTED) {
21 | beforeTestExecution(testContext);
22 | }
23 | }
24 |
25 | @Override
26 | public void afterTestMethod(TestContext testContext) {
27 | if (!TEST_EXECUTION_METHODS_SUPPORTED) {
28 | afterTestExecution(testContext);
29 | }
30 | }
31 |
32 | @Override
33 | public void beforeTestExecution(TestContext testContext) {
34 | ApplicationContext applicationContext = testContext.getApplicationContext();
35 | applicationContext.publishEvent(new TestExecutionStartedEvent(applicationContext, testContext.getTestMethod()));
36 | logger.trace("Test execution started - '{}#{}'", testContext.getTestClass().getSimpleName(), testContext.getTestMethod().getName());
37 | }
38 |
39 | @Override
40 | public void afterTestExecution(TestContext testContext) {
41 | ApplicationContext applicationContext = testContext.getApplicationContext();
42 | applicationContext.publishEvent(new TestExecutionFinishedEvent(applicationContext, testContext.getTestMethod()));
43 | logger.trace("Test execution finished - '{}#{}'", testContext.getTestClass().getSimpleName(), testContext.getTestMethod().getName());
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/context/EmbeddedDatabaseFactoryBean.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.context;
18 |
19 | import org.springframework.aop.framework.ProxyFactory;
20 | import org.springframework.beans.factory.FactoryBean;
21 | import org.springframework.beans.factory.ObjectFactory;
22 | import org.springframework.core.Ordered;
23 |
24 | import javax.sql.DataSource;
25 |
26 | /**
27 | * Implementation of the {@link org.springframework.beans.factory.FactoryBean} interface
28 | * that provides fully cacheable instances of the embedded postgres database.
29 | */
30 | public class EmbeddedDatabaseFactoryBean implements FactoryBean, Ordered {
31 |
32 | private final ObjectFactory databaseContextProvider;
33 |
34 | private DataSource dataSource;
35 |
36 | public EmbeddedDatabaseFactoryBean(ObjectFactory databaseContextProvider) {
37 | this.databaseContextProvider = databaseContextProvider;
38 | }
39 |
40 | @Override
41 | public int getOrder() {
42 | return Ordered.HIGHEST_PRECEDENCE;
43 | }
44 |
45 | @Override
46 | public boolean isSingleton() {
47 | return true;
48 | }
49 |
50 | @Override
51 | public Class> getObjectType() {
52 | return DataSource.class;
53 | }
54 |
55 | @Override
56 | public synchronized DataSource getObject() {
57 | if (dataSource == null) {
58 | DatabaseContext databaseContext = databaseContextProvider.getObject();
59 | dataSource = ProxyFactory.getProxy(DataSource.class, new DatabaseTargetSource(databaseContext));
60 | }
61 | return dataSource;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/YandexProviderIntegrationTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.provider;
18 |
19 | import io.zonky.test.category.PostgresTestSuite;
20 | import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
21 | import io.zonky.test.support.ConditionalTestRule;
22 | import io.zonky.test.support.TestAssumptions;
23 | import org.junit.ClassRule;
24 | import org.junit.Test;
25 | import org.junit.experimental.categories.Category;
26 | import org.junit.runner.RunWith;
27 | import org.postgresql.ds.PGSimpleDataSource;
28 | import org.springframework.beans.factory.annotation.Autowired;
29 | import org.springframework.test.context.ContextConfiguration;
30 | import org.springframework.test.context.junit4.SpringRunner;
31 |
32 | import javax.sql.DataSource;
33 | import java.sql.SQLException;
34 |
35 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseProvider.YANDEX;
36 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
37 | import static org.assertj.core.api.Assertions.assertThat;
38 |
39 | @RunWith(SpringRunner.class)
40 | @Category(PostgresTestSuite.class)
41 | @AutoConfigureEmbeddedDatabase(type = POSTGRES, provider = YANDEX)
42 | @ContextConfiguration
43 | public class YandexProviderIntegrationTest {
44 |
45 | @ClassRule
46 | public static ConditionalTestRule conditionalTestRule = new ConditionalTestRule(TestAssumptions::assumeYandexSupportsCurrentPostgresVersion);
47 |
48 | @Autowired
49 | private DataSource dataSource;
50 |
51 | @Test
52 | public void testDataSource() throws SQLException {
53 | assertThat(dataSource.unwrap(PGSimpleDataSource.class).getPassword()).isEqualTo("yandex");
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/config/OnClassCondition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.config;
18 |
19 | import org.springframework.context.annotation.Condition;
20 | import org.springframework.context.annotation.ConditionContext;
21 | import org.springframework.core.Ordered;
22 | import org.springframework.core.annotation.Order;
23 | import org.springframework.core.type.AnnotatedTypeMetadata;
24 | import org.springframework.util.ClassUtils;
25 | import org.springframework.util.MultiValueMap;
26 |
27 | import java.util.Arrays;
28 | import java.util.List;
29 | import java.util.stream.Collectors;
30 |
31 | @Order(Ordered.HIGHEST_PRECEDENCE)
32 | class OnClassCondition implements Condition {
33 |
34 | @Override
35 | public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
36 | ClassLoader classLoader = context.getClassLoader();
37 | List candidates = getCandidates(metadata, ConditionalOnClass.class);
38 |
39 | for (String className : candidates) {
40 | if (!ClassUtils.isPresent(className, classLoader)) {
41 | return false;
42 | }
43 | }
44 |
45 | return true;
46 | }
47 |
48 | private List getCandidates(AnnotatedTypeMetadata metadata, Class> annotationType) {
49 | MultiValueMap attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), true);
50 | if (attributes == null || attributes.get("name") == null) {
51 | throw new IllegalStateException("@ConditionalOnClass did not specify a class name");
52 | }
53 | return attributes.get("name").stream().flatMap(o -> Arrays.stream((String[]) o)).collect(Collectors.toList());
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/support/TestSocketUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2024 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.support;
18 |
19 | import org.springframework.util.Assert;
20 |
21 | import javax.net.ServerSocketFactory;
22 | import java.net.InetAddress;
23 | import java.net.ServerSocket;
24 | import java.util.Random;
25 |
26 | public class TestSocketUtils {
27 |
28 | private static final int PORT_RANGE_MIN = 1024;
29 | private static final int PORT_RANGE_MAX = 65535;
30 | private static final int PORT_RANGE_PLUS_ONE = PORT_RANGE_MAX - PORT_RANGE_MIN + 1;
31 | private static final int MAX_ATTEMPTS = 1_000;
32 |
33 | private static final Random random = new Random(System.nanoTime());
34 |
35 | private TestSocketUtils() {}
36 |
37 | public static int findAvailableTcpPort() {
38 | int candidatePort;
39 | int searchCounter = 0;
40 | do {
41 | Assert.state(++searchCounter <= MAX_ATTEMPTS, () -> String.format(
42 | "Could not find an available TCP port in the range [%d, %d] after %d attempts",
43 | PORT_RANGE_MIN, PORT_RANGE_MAX, MAX_ATTEMPTS));
44 | candidatePort = PORT_RANGE_MIN + random.nextInt(PORT_RANGE_PLUS_ONE);
45 | }
46 | while (!isPortAvailable(candidatePort));
47 |
48 | return candidatePort;
49 | }
50 |
51 | private static boolean isPortAvailable(int port) {
52 | try {
53 | ServerSocket serverSocket = ServerSocketFactory.getDefault()
54 | .createServerSocket(port, 1, InetAddress.getByName("localhost"));
55 | serverSocket.close();
56 | return true;
57 | }
58 | catch (Exception ex) {
59 | return false;
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/support/MockitoAssertions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.support;
18 |
19 | import org.assertj.core.api.Condition;
20 | import org.mockito.internal.util.MockUtil;
21 |
22 | import static io.zonky.test.db.util.ReflectionUtils.invokeConstructor;
23 | import static io.zonky.test.db.util.ReflectionUtils.invokeMethod;
24 | import static io.zonky.test.db.util.ReflectionUtils.invokeStaticMethod;
25 | import static org.assertj.core.api.Assertions.allOf;
26 |
27 | public class MockitoAssertions {
28 |
29 | private MockitoAssertions() {}
30 |
31 | public static Condition mock() {
32 | return new Condition("target object should be a mock") {
33 | @Override
34 | public boolean matches(T object) {
35 | try {
36 | return invokeMethod(invokeConstructor(MockUtil.class), "isMock", object);
37 | } catch (Exception e) {
38 | return invokeStaticMethod(MockUtil.class, "isMock", object);
39 | }
40 | }
41 | };
42 | }
43 |
44 | public static Condition mockWithName(String name) {
45 | Condition hasName = new Condition("mock should have a specified name") {
46 | @Override
47 | public boolean matches(T object) {
48 | try {
49 | return name.equals(invokeMethod(invokeConstructor(MockUtil.class), "getMockName", object).toString());
50 | } catch (Exception e) {
51 | return name.equals(invokeStaticMethod(MockUtil.class, "getMockName", object).toString());
52 | }
53 | }
54 | };
55 |
56 | return allOf(mock(), hasName);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/flyway/FlywayClassUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.flyway;
18 |
19 | import org.flywaydb.core.Flyway;
20 | import org.slf4j.LoggerFactory;
21 | import org.springframework.core.io.ClassPathResource;
22 | import org.springframework.util.ClassUtils;
23 | import org.springframework.util.StreamUtils;
24 |
25 | import static java.nio.charset.StandardCharsets.UTF_8;
26 |
27 | public class FlywayClassUtils {
28 |
29 | private static final FlywayVersion flywayVersion = loadFlywayVersion();
30 |
31 | private FlywayClassUtils() {}
32 |
33 | private static FlywayVersion loadFlywayVersion() {
34 | try {
35 | ClassPathResource versionResource = new ClassPathResource("org/flywaydb/core/internal/version.txt", FlywayClassUtils.class.getClassLoader());
36 | if (versionResource.exists()) {
37 | String version = StreamUtils.copyToString(versionResource.getInputStream(), UTF_8);
38 | return FlywayVersion.parseVersion(version);
39 | } else if (ClassUtils.hasMethod(Flyway.class, "isPlaceholderReplacement")) {
40 | return FlywayVersion.parseVersion("3.2");
41 | } else if (ClassUtils.hasMethod(Flyway.class, "getBaselineVersion")) {
42 | return FlywayVersion.parseVersion("3.1");
43 | } else {
44 | return FlywayVersion.parseVersion("3.0");
45 | }
46 | } catch (Exception e) {
47 | LoggerFactory.getLogger(FlywayClassUtils.class).error("Unexpected error when resolving flyway version", e);
48 | return FlywayVersion.parseVersion("0");
49 | }
50 | }
51 |
52 | public static FlywayVersion getFlywayVersion() {
53 | return flywayVersion;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/preparer/CompositeDatabasePreparer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.preparer;
18 |
19 | import com.google.common.base.MoreObjects;
20 | import com.google.common.collect.ImmutableList;
21 |
22 | import javax.sql.DataSource;
23 | import java.sql.SQLException;
24 | import java.util.List;
25 | import java.util.Objects;
26 |
27 | public class CompositeDatabasePreparer implements DatabasePreparer {
28 |
29 | private final List preparers;
30 |
31 | public CompositeDatabasePreparer(List preparers) {
32 | this.preparers = ImmutableList.copyOf(preparers);
33 | }
34 |
35 | public List getPreparers() {
36 | return preparers;
37 | }
38 |
39 | @Override
40 | public long estimatedDuration() {
41 | return preparers.stream()
42 | .mapToLong(DatabasePreparer::estimatedDuration)
43 | .sum();
44 | }
45 |
46 | @Override
47 | public void prepare(DataSource dataSource) throws SQLException {
48 | for (DatabasePreparer preparer : preparers) {
49 | preparer.prepare(dataSource);
50 | }
51 | }
52 |
53 | @Override
54 | public boolean equals(Object o) {
55 | if (this == o) return true;
56 | if (o == null || getClass() != o.getClass()) return false;
57 | CompositeDatabasePreparer that = (CompositeDatabasePreparer) o;
58 | return Objects.equals(preparers, that.preparers);
59 | }
60 |
61 | @Override
62 | public int hashCode() {
63 | return Objects.hash(preparers);
64 | }
65 |
66 | @Override
67 | public String toString() {
68 | return MoreObjects.toStringHelper(this)
69 | .add("preparers", preparers)
70 | .toString();
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/support/TestDatabasePreparer.java:
--------------------------------------------------------------------------------
1 | package io.zonky.test.db.support;
2 |
3 | import io.zonky.test.db.preparer.DatabasePreparer;
4 |
5 | import javax.sql.DataSource;
6 | import java.util.Objects;
7 | import java.util.function.Consumer;
8 |
9 | public class TestDatabasePreparer implements DatabasePreparer {
10 |
11 | public static TestDatabasePreparer empty() {
12 | return new TestDatabasePreparer(null, dataSource -> {});
13 | }
14 |
15 | public static TestDatabasePreparer empty(String identifier) {
16 | return new TestDatabasePreparer(identifier, dataSource -> {});
17 | }
18 |
19 | public static TestDatabasePreparer of(Consumer action) {
20 | return new TestDatabasePreparer(null, action);
21 | }
22 |
23 | public static TestDatabasePreparer of(String identifier, Consumer action) {
24 | return new TestDatabasePreparer(identifier, action);
25 | }
26 |
27 | public static TestDatabasePreparer of(String identifier, long duration, Consumer action) {
28 | return new TestDatabasePreparer(identifier, action, duration);
29 | }
30 |
31 | private final String identifier;
32 | private final Consumer action;
33 | private final long estimatedDuration;
34 |
35 | private TestDatabasePreparer(String identifier, Consumer action) {
36 | this.identifier = identifier;
37 | this.action = action;
38 | this.estimatedDuration = 0;
39 | }
40 |
41 | private TestDatabasePreparer(String identifier, Consumer action, long estimatedDuration) {
42 | this.identifier = identifier;
43 | this.action = action;
44 | this.estimatedDuration = estimatedDuration;
45 | }
46 |
47 | @Override
48 | public long estimatedDuration() {
49 | return estimatedDuration;
50 | }
51 |
52 | @Override
53 | public void prepare(DataSource dataSource) {
54 | action.accept(dataSource);
55 | }
56 |
57 | @Override
58 | public boolean equals(Object o) {
59 | if (this == o) return true;
60 | if (o == null || getClass() != o.getClass()) return false;
61 | TestDatabasePreparer that = (TestDatabasePreparer) o;
62 | if (identifier == null || that.identifier == null) return false;
63 | return Objects.equals(identifier, that.identifier);
64 | }
65 |
66 | @Override
67 | public int hashCode() {
68 | return Objects.hash(identifier);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/support/ProviderDescriptor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.support;
18 |
19 | import com.google.common.base.MoreObjects;
20 | import org.springframework.util.Assert;
21 |
22 | import java.util.Objects;
23 |
24 | public final class ProviderDescriptor {
25 |
26 | private final String providerName;
27 | private final String databaseName;
28 |
29 | public static ProviderDescriptor of(String providerName, String databaseName) {
30 | return new ProviderDescriptor(providerName, databaseName);
31 | }
32 |
33 | private ProviderDescriptor(String providerName, String databaseName) {
34 | Assert.notNull(databaseName, "Database name must not be null");
35 | Assert.notNull(providerName, "Provider name must not be null");
36 | this.databaseName = databaseName.toLowerCase();
37 | this.providerName = providerName.toLowerCase();
38 | }
39 |
40 | public String getProviderName() {
41 | return providerName;
42 | }
43 |
44 | public String getDatabaseName() {
45 | return databaseName;
46 | }
47 |
48 | @Override
49 | public boolean equals(Object o) {
50 | if (this == o) return true;
51 | if (o == null || getClass() != o.getClass()) return false;
52 | ProviderDescriptor that = (ProviderDescriptor) o;
53 | return Objects.equals(providerName, that.providerName) &&
54 | Objects.equals(databaseName, that.databaseName);
55 | }
56 |
57 | @Override
58 | public int hashCode() {
59 | return Objects.hash(providerName, databaseName);
60 | }
61 |
62 | @Override
63 | public String toString() {
64 | return MoreObjects.toStringHelper(this)
65 | .add("providerName", providerName)
66 | .add("databaseName", databaseName)
67 | .toString();
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/EarlyInitializationIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package io.zonky.test.db;
2 |
3 | import com.google.common.collect.ImmutableList;
4 | import io.zonky.test.category.FlywayTestSuite;
5 | import io.zonky.test.db.flyway.FlywayWrapper;
6 | import org.flywaydb.core.Flyway;
7 | import org.junit.Test;
8 | import org.junit.experimental.categories.Category;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
12 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
13 | import org.springframework.context.annotation.Bean;
14 | import org.springframework.context.annotation.Configuration;
15 | import org.springframework.core.Ordered;
16 | import org.springframework.test.context.ContextConfiguration;
17 | import org.springframework.test.context.junit4.SpringRunner;
18 |
19 | import javax.sql.DataSource;
20 |
21 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
22 | import static org.assertj.core.api.Assertions.assertThat;
23 |
24 | @RunWith(SpringRunner.class)
25 | @Category(FlywayTestSuite.class)
26 | @AutoConfigureEmbeddedDatabase(type = POSTGRES)
27 | @ContextConfiguration
28 | public class EarlyInitializationIntegrationTest {
29 |
30 | @Configuration
31 | static class Config {
32 |
33 | @Bean
34 | public BeanFactoryPostProcessor beanFactoryPostProcessor() {
35 | return new TestBeanFactoryPostProcessor();
36 | }
37 |
38 | @Bean(initMethod = "migrate")
39 | public Flyway flyway(DataSource dataSource) {
40 | FlywayWrapper wrapper = FlywayWrapper.newInstance();
41 | wrapper.setDataSource(dataSource);
42 | wrapper.setSchemas(ImmutableList.of("test"));
43 | return wrapper.getFlyway();
44 | }
45 | }
46 |
47 | @Autowired
48 | private DataSource dataSource;
49 |
50 | @Test
51 | public void testDataSource() {
52 | assertThat(dataSource).isNotNull();
53 | }
54 |
55 | private static class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {
56 |
57 | @Override
58 | public int getOrder() {
59 | return Ordered.HIGHEST_PRECEDENCE;
60 | }
61 |
62 | @Override
63 | public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
64 | beanFactory.getBeanNamesForType(DataSource.class, true, true);
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/main/java/io/zonky/test/db/config/OnBeanCondition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.zonky.test.db.config;
18 |
19 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
20 | import org.springframework.context.annotation.ConditionContext;
21 | import org.springframework.context.annotation.ConfigurationCondition;
22 | import org.springframework.core.Ordered;
23 | import org.springframework.core.annotation.Order;
24 | import org.springframework.core.type.AnnotatedTypeMetadata;
25 | import org.springframework.util.MultiValueMap;
26 |
27 | import java.util.Arrays;
28 | import java.util.List;
29 | import java.util.stream.Collectors;
30 |
31 | @Order(Ordered.LOWEST_PRECEDENCE)
32 | class OnBeanCondition implements ConfigurationCondition {
33 |
34 | @Override
35 | public ConfigurationPhase getConfigurationPhase() {
36 | return ConfigurationPhase.REGISTER_BEAN;
37 | }
38 |
39 | @Override
40 | public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
41 | ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
42 | List candidates = getCandidates(metadata, ConditionalOnMissingBean.class);
43 |
44 | for (String beanName : candidates) {
45 | if (beanFactory.containsBean(beanName)) {
46 | return false;
47 | }
48 | }
49 |
50 | return true;
51 | }
52 |
53 | private List getCandidates(AnnotatedTypeMetadata metadata, Class> annotationType) {
54 | MultiValueMap attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), true);
55 | if (attributes == null || attributes.get("name") == null) {
56 | throw new IllegalStateException("@ConditionalOnMissingBean did not specify a bean name");
57 | }
58 | return attributes.get("name").stream().flatMap(o -> Arrays.stream((String[]) o)).collect(Collectors.toList());
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/embedded-database-spring-test/src/test/java/io/zonky/test/db/ConnectionLeakIntegrationTest.java:
--------------------------------------------------------------------------------
1 | package io.zonky.test.db;
2 |
3 | import com.google.common.collect.ImmutableList;
4 | import io.zonky.test.category.FlywayTestSuite;
5 | import io.zonky.test.db.flyway.FlywayWrapper;
6 | import org.flywaydb.core.Flyway;
7 | import org.flywaydb.test.annotation.FlywayTest;
8 | import org.junit.Test;
9 | import org.junit.experimental.categories.Category;
10 | import org.junit.runner.RunWith;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.context.annotation.Bean;
13 | import org.springframework.context.annotation.Configuration;
14 | import org.springframework.jdbc.core.JdbcTemplate;
15 | import org.springframework.test.annotation.Repeat;
16 | import org.springframework.test.annotation.Timed;
17 | import org.springframework.test.context.ContextConfiguration;
18 | import org.springframework.test.context.TestPropertySource;
19 | import org.springframework.test.context.junit4.SpringRunner;
20 |
21 | import javax.sql.DataSource;
22 | import java.util.List;
23 | import java.util.Map;
24 |
25 | import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseType.POSTGRES;
26 | import static org.assertj.core.api.Assertions.assertThat;
27 |
28 | @RunWith(SpringRunner.class)
29 | @Category(FlywayTestSuite.class)
30 | @AutoConfigureEmbeddedDatabase(type = POSTGRES)
31 | @TestPropertySource(properties = "zonky.test.database.postgres.server.properties.max_connections=15")
32 | @ContextConfiguration
33 | public class ConnectionLeakIntegrationTest {
34 |
35 | private static final String SQL_SELECT_PERSONS = "select * from test.person";
36 |
37 | @Configuration
38 | static class Config {
39 |
40 | @Bean(initMethod = "migrate")
41 | public Flyway flyway(DataSource dataSource) {
42 | FlywayWrapper wrapper = FlywayWrapper.newInstance();
43 | wrapper.setDataSource(dataSource);
44 | wrapper.setSchemas(ImmutableList.of("test"));
45 | return wrapper.getFlyway();
46 | }
47 |
48 | @Bean
49 | public JdbcTemplate jdbcTemplate(DataSource dataSource) {
50 | return new JdbcTemplate(dataSource);
51 | }
52 | }
53 |
54 | @Autowired
55 | private JdbcTemplate jdbcTemplate;
56 |
57 | @Test
58 | @Repeat(50)
59 | @Timed(millis = 30000)
60 | @FlywayTest(locationsForMigrate = "db/test_migration/appendable")
61 | public void testEmbeddedDatabase() {
62 | List