001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 * http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014
015package de.softwareforge.testing.postgres.embedded;
016
017import static com.google.common.base.Preconditions.checkState;
018import static org.junit.jupiter.api.Assertions.assertEquals;
019
020import de.softwareforge.testing.postgres.junit5.EmbeddedPgExtension;
021import de.softwareforge.testing.postgres.junit5.SingleDatabaseBuilder;
022
023import jakarta.annotation.Nonnull;
024import java.sql.SQLException;
025import java.util.Map;
026import javax.sql.DataSource;
027
028import org.junit.jupiter.api.Test;
029import org.junit.jupiter.api.extension.RegisterExtension;
030import org.postgresql.ds.common.BaseDataSource;
031
032public class ConnectConfigTest {
033
034    private final CapturingDatabasePreparer preparer = new CapturingDatabasePreparer();
035
036    @RegisterExtension
037    public EmbeddedPgExtension db = SingleDatabaseBuilder.preparedInstanceWithDefaults(preparer)
038            .withInstancePreparer(builder -> builder.addConnectionProperty("connectTimeout", "20"))
039            .build();
040
041    @Test
042    public void test() throws SQLException {
043        DatabaseInfo databaseInfo = db.createDatabaseInfo();
044
045        Map<String, String> properties = databaseInfo.connectionProperties();
046        assertEquals(1, properties.size());
047        assertEquals("20", properties.get("connectTimeout"));
048
049        BaseDataSource testDatabase = (BaseDataSource) db.createDataSource();
050        assertEquals("20", testDatabase.getProperty("connectTimeout"));
051
052        BaseDataSource preparerDataSource = (BaseDataSource) preparer.getDataSource();
053        assertEquals("20", preparerDataSource.getProperty("connectTimeout"));
054    }
055
056    private static class CapturingDatabasePreparer implements EmbeddedPostgresPreparer<DataSource> {
057
058        private DataSource dataSource;
059
060        @Override
061        public void prepare(@Nonnull DataSource dataSource) {
062            checkState(this.dataSource == null, "database preparer has been called multiple times");
063            this.dataSource = dataSource;
064        }
065
066        public DataSource getDataSource() {
067            return dataSource;
068        }
069    }
070}