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.assertFalse; 019import static org.junit.jupiter.api.Assertions.assertTrue; 020 021import java.sql.Connection; 022import java.sql.ResultSet; 023import java.sql.SQLException; 024import java.sql.Statement; 025 026import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; 027import org.junit.jupiter.api.Order; 028import org.junit.jupiter.api.Test; 029import org.junit.jupiter.api.TestMethodOrder; 030import org.junit.jupiter.api.extension.RegisterExtension; 031 032@TestMethodOrder(OrderAnnotation.class) 033public class Junit5ClassMemberTest { 034 035 @RegisterExtension 036 public static EmbeddedPgExtension singleDatabase = SingleDatabaseBuilder.instanceWithDefaults().build(); 037 038 @RegisterExtension 039 public static EmbeddedPgExtension multiDatabase = MultiDatabaseBuilder.instanceWithDefaults().build(); 040 041 @Test 042 @Order(1) 043 public void testTableCreation() throws Exception { 044 // create tables in a single and a multi database 045 // the static extension is the same database across all tests. 046 createTable(singleDatabase, "table1"); 047 createTable(multiDatabase, "table2"); 048 } 049 050 @Test 051 @Order(2) 052 public void testTableExists() throws Exception { 053 // single database is shared between tests 054 // multi database is not. 055 assertTrue(existsTable(singleDatabase, "table1")); 056 assertFalse(existsTable(multiDatabase, "table2")); 057 } 058 059 060 static int createTable(EmbeddedPgExtension extension, String table) throws SQLException { 061 try (Connection connection = extension.createDataSource().getConnection(); 062 Statement statement = connection.createStatement()) { 063 return statement.executeUpdate(format("CREATE TABLE public.%s (a INTEGER)", table)); 064 } 065 } 066 067 static boolean existsTable(EmbeddedPgExtension extension, String table) throws SQLException { 068 try (Connection connection = extension.createDataSource().getConnection(); 069 Statement statement = connection.createStatement()) { 070 String query = format("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '%s')", table); 071 try (ResultSet resultSet = statement.executeQuery(query)) { 072 resultSet.next(); 073 return resultSet.getBoolean(1); 074 } 075 } 076 } 077}