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.junit5; 016 017import static java.lang.String.format; 018import static org.junit.jupiter.api.Assertions.assertEquals; 019import static org.junit.jupiter.api.Assertions.assertFalse; 020import static org.junit.jupiter.api.Assertions.assertNotNull; 021import static org.junit.jupiter.api.Assertions.assertTrue; 022 023import de.softwareforge.testing.postgres.embedded.DatabaseInfo; 024import de.softwareforge.testing.postgres.embedded.EmbeddedPostgres; 025 026import java.sql.Connection; 027import java.sql.ResultSet; 028import java.sql.SQLException; 029import java.sql.Statement; 030import javax.sql.DataSource; 031 032import org.junit.jupiter.api.Test; 033import org.junit.jupiter.api.extension.ExtendWith; 034 035@ExtendWith(EmbeddedPgExtension.class) 036public class ExtendWithTest { 037 038 @Test 039 public void testEmbeddedPostgres(EmbeddedPostgres pg) throws SQLException { 040 assertNotNull(pg); 041 testDataSource(pg.createDefaultDataSource()); 042 } 043 044 @Test 045 public void testDatabaseInfo(DatabaseInfo databaseInfo) throws SQLException { 046 assertNotNull(databaseInfo); 047 048 testDataSource(databaseInfo.asDataSource()); 049 } 050 051 @Test 052 public void testDataSource(DataSource dataSource) throws SQLException { 053 assertFalse(existsTable(dataSource, "table1")); 054 assertFalse(existsTable(dataSource, "table2")); 055 056 assertEquals(0, createTable(dataSource, "table1")); 057 assertEquals(0, createTable(dataSource, "table2")); 058 059 assertTrue(existsTable(dataSource, "table1")); 060 assertTrue(existsTable(dataSource, "table2")); 061 } 062 063 static int createTable(DataSource ds, String table) throws SQLException { 064 try (Connection connection = ds.getConnection(); 065 Statement statement = connection.createStatement()) { 066 return statement.executeUpdate(format("CREATE TABLE public.%s (a INTEGER)", table)); 067 } 068 } 069 070 static boolean existsTable(DataSource ds, String table) throws SQLException { 071 try (Connection connection = ds.getConnection(); 072 Statement statement = connection.createStatement()) { 073 String query = format("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '%s')", table); 074 try (ResultSet resultSet = statement.executeQuery(query)) { 075 resultSet.next(); 076 return resultSet.getBoolean(1); 077 } 078 } 079 } 080}