View Javadoc
1   package com.atlassian.refapp.test.plugin.api;
2   
3   import com.atlassian.functest.junit.SpringAwareTestCase;
4   import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
5   import com.atlassian.refapp.api.ConnectionProvider;
6   import org.junit.Test;
7   
8   import java.sql.ResultSet;
9   import java.sql.SQLException;
10  
11  import static org.hamcrest.MatcherAssert.assertThat;
12  import static org.hamcrest.core.Is.is;
13  import static org.junit.Assert.fail;
14  
15  /**
16   * Ensures that the {@link ConnectionProvider#connection()} and its schema provide a valid database connection that may
17   * be used for DDL and DML.
18   *
19   * An attempt is made to drop existing database objects, to prevent spurious faliures.
20   */
21  public class ConnectionProviderTest extends SpringAwareTestCase {
22  
23      @ComponentImport
24      private ConnectionProvider connectionProvider;
25  
26      public void setConnectionProvider(ConnectionProvider connectionProvider) {
27          this.connectionProvider = connectionProvider;
28      }
29  
30      /**
31       * Database vendor agnostic DML/DDL test
32       */
33      @Test
34      public void pokeDatabase() {
35  
36          // not all databases need a schema
37          final String schemaPrefix = connectionProvider.schema().map(s -> s + '.').orElse("");
38  
39          try {
40              // drop a table if it's there
41              connectionProvider.connection()
42                      .prepareStatement("drop table " + schemaPrefix + "refapptest")
43                      .execute();
44          } catch (SQLException e) {
45              // all good - no existing tables in the database
46          }
47  
48          try {
49              // create a table
50              connectionProvider.connection()
51                      .prepareStatement("create table " + schemaPrefix + "refapptest (refappcol varchar(255))")
52                      .execute();
53  
54              // insert a row
55              connectionProvider.connection()
56                      .prepareStatement("insert into " + schemaPrefix + "refapptest (refappcol) values ('something')")
57                      .execute();
58  
59              // select the above row
60              final String select = "select refappcol from " + schemaPrefix + "refapptest";
61              final ResultSet rs = connectionProvider.connection()
62                      .prepareStatement(select)
63                      .executeQuery();
64  
65              // ensure that a value is correctly returned
66              assertThat("no results returned for '" + select + "'", rs.next(), is(true));
67              assertThat(rs.getString("refappcol"), is("something"));
68  
69          } catch (SQLException e) {
70              // functest-plugin 0.8.2 doesn't consider an exception from a test as a failure
71              fail(e.toString());
72          }
73      }
74  }