// do not insert duplicated rows
permissions.grantGroupRole(project, "sonar-administrators", "admin");
- checkColumns("grantGroupRole", "group_roles", "group_id", "resource_id", "role");
+ checkTables("grantGroupRole", new String[] {"id"}, "group_roles");
}
@Test
// do not insert duplicated rows
permissions.grantUserRole(project, "marius", "admin");
- checkColumns("grantUserRole", "user_roles", "user_id", "resource_id", "role");
+ checkTables("grantUserRole", new String[] {"id"}, "user_roles");
}
@Test
// does not exist
assertThat(permissions.hasRoles(new Project("not_found"))).isFalse();
}
-}
\ No newline at end of file
+}
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
+import org.apache.commons.io.IOUtils;
import org.dbunit.Assertion;
import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.DatabaseUnitException;
import org.dbunit.IDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
+import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ReplacementDataSet;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.FlatXmlDataSet;
-import org.junit.*;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
import org.sonar.api.config.Settings;
import org.sonar.core.config.Logback;
import java.io.InputStream;
+import java.sql.Connection;
import java.sql.SQLException;
import static org.junit.Assert.fail;
public abstract class AbstractDaoTestCase {
private static Database database;
- private static MyBatis myBatis;
private static DatabaseCommands databaseCommands;
-
- private IDatabaseTester databaseTester;
- private IDatabaseConnection connection;
+ private static IDatabaseTester databaseTester;
+ private static MyBatis myBatis;
@BeforeClass
- public static void startDatabase() throws Exception {
+ public static void startDatabase() {
Settings settings = new Settings().setProperties(Maps.fromProperties(System.getProperties()));
boolean hasDialect = settings.hasKey("sonar.jdbc.dialect");
if (hasDialect) {
database = new DefaultDatabase(settings);
} else {
- database = new H2Database();
+ database = new H2Database("sonarMyBatis");
}
database.start();
+ databaseCommands = DatabaseCommands.forDialect(database.getDialect());
+ databaseTester = new DataSourceDatabaseTester(database.getDataSource());
+
myBatis = new MyBatis(database, settings, new Logback());
myBatis.start();
-
- databaseCommands = DatabaseCommands.forDialect(database.getDialect());
}
@Before
public void setupDbUnit() throws SQLException {
- databaseCommands.truncateDatabase(myBatis.openSession().getConnection());
- databaseTester = new DataSourceDatabaseTester(database.getDataSource());
- }
-
- @After
- public void stopConnection() throws Exception {
- if (databaseTester != null) {
- databaseTester.onTearDown();
- }
- if (connection != null) {
- connection.close();
- }
+ databaseCommands.truncateDatabase(database.getDataSource().getConnection());
}
@AfterClass
return myBatis;
}
- protected void setupData(String testName) {
- InputStream stream = null;
+ protected void setupData(String... testNames) {
+ InputStream[] streams = new InputStream[testNames.length];
try {
- String className = getClass().getName();
- className = String.format("/%s/%s.xml", className.replace(".", "/"), testName);
- stream = getClass().getResourceAsStream(className);
- if (stream == null) {
- throw new RuntimeException("Test not found :" + className);
+ for (int i = 0; i < testNames.length; i++) {
+ String className = getClass().getName();
+ className = String.format("/%s/%s.xml", className.replace(".", "/"), testNames[i]);
+ streams[i] = getClass().getResourceAsStream(className);
+ if (streams[i] == null) {
+ throw new RuntimeException("Test not found :" + className);
+ }
}
- setupData(stream);
+ setupData(streams);
+
} finally {
- Closeables.closeQuietly(stream);
+ for (InputStream stream : streams) {
+ IOUtils.closeQuietly(stream);
+ }
}
}
- private void setupData(InputStream dataStream) {
+ private void setupData(InputStream... dataSetStream) {
+ IDatabaseConnection connection = null;
try {
- ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(dataStream));
- dataSet.addReplacementObject("[null]", null);
- dataSet.addReplacementObject("[false]", databaseCommands.getFalse());
- dataSet.addReplacementObject("[true]", databaseCommands.getTrue());
+ IDataSet[] dataSets = new IDataSet[dataSetStream.length];
+ for (int i = 0; i < dataSetStream.length; i++) {
+ dataSets[i] = getData(dataSetStream[i]);
+ }
+ databaseTester.setDataSet(new CompositeDataSet(dataSets));
- databaseTester.setDataSet(dataSet);
- connection = databaseTester.getConnection();
+ connection = createConnection();
- connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, databaseCommands.getDbUnitFactory());
databaseCommands.getDbunitDatabaseOperation().execute(connection, databaseTester.getDataSet());
-
} catch (Exception e) {
throw translateException("Could not setup DBUnit data", e);
+ } finally {
+ closeQuietly(connection);
+ }
+ }
+
+ private void closeQuietly(IDatabaseConnection connection) {
+ try {
+ if (connection != null) {
+ connection.close();
+ }
+ } catch (SQLException e) {
}
}
protected void checkTables(String testName, String... tables) {
- checkTables(testName, new String[]{}, tables);
+ checkTables(testName, new String[0], tables);
}
protected void checkTables(String testName, String[] excludedColumnNames, String... tables) {
+ IDatabaseConnection connection = null;
try {
- IDataSet dataSet = getCurrentDataSet();
+ connection = createConnection();
+
+ IDataSet dataSet = connection.createDataSet();
IDataSet expectedDataSet = getExpectedData(testName);
for (String table : tables) {
ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(dataSet.getTable(table), excludedColumnNames);
- Assertion.assertEquals(expectedDataSet.getTable(table), filteredTable);
+ ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable(table), excludedColumnNames);
+ Assertion.assertEquals(filteredExpectedTable, filteredTable);
}
- } catch (DataSetException e) {
- throw translateException("Error while checking results", e);
} catch (DatabaseUnitException e) {
fail(e.getMessage());
+ } catch (SQLException e) {
+ throw translateException("Error while checking results", e);
+ } finally {
+ closeQuietly(connection);
}
}
- /**
- * Opposite of {@link #checkTables(String, String[], String...)}.
- */
- protected void checkColumns(String testName, String table, String... columns) {
+ protected void assertEmptyTables(String... emptyTables) {
+ IDatabaseConnection connection = null;
try {
- IDataSet dataSet = getCurrentDataSet();
- IDataSet expectedDataSet = getExpectedData(testName);
- ITable filteredTable = DefaultColumnFilter.includedColumnsTable(dataSet.getTable(table), columns);
- ITable filteredExpectedTable = DefaultColumnFilter.includedColumnsTable(expectedDataSet.getTable(table), columns);
- Assertion.assertEquals(filteredExpectedTable, filteredTable);
-
- } catch (DataSetException e) {
- throw translateException("Error while checking columns", e);
- } catch (DatabaseUnitException e) {
- fail(e.getMessage());
+ connection = createConnection();
+
+ IDataSet dataSet = connection.createDataSet();
+ for (String table : emptyTables) {
+ try {
+ Assert.assertEquals("Table " + table + " not empty.", 0, dataSet.getTable(table).getRowCount());
+ } catch (DataSetException e) {
+ throw translateException("Error while checking results", e);
+ }
+ }
+ } catch (SQLException e) {
+ throw translateException("Error while checking results", e);
+ } finally {
+ closeQuietly(connection);
}
}
- protected void assertEmptyTables(String... emptyTables) {
- for (String table : emptyTables) {
- try {
- Assert.assertEquals("Table " + table + " not empty.", 0, getCurrentDataSet().getTable(table).getRowCount());
- } catch (DataSetException e) {
- throw translateException("Error while checking results", e);
- }
+ private IDatabaseConnection createConnection() {
+ try {
+ IDatabaseConnection connection = databaseTester.getConnection();
+ connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, databaseCommands.getDbUnitFactory());
+ return connection;
+ } catch (Exception e) {
+ throw translateException("Error while getting connection", e);
}
}
private IDataSet getExpectedData(String testName) {
String className = getClass().getName();
- className = String.format("/%s/%s-result.xml", className.replace(".", "/"), testName);
+ className = String.format("/%s/%s-result.xml", className.replace('.', '/'), testName);
InputStream in = getClass().getResourceAsStream(className);
try {
}
}
- private IDataSet getCurrentDataSet() {
- try {
- return connection.createDataSet();
- } catch (SQLException e) {
- throw translateException("Could not create the current dataset", e);
- }
- }
-
private static RuntimeException translateException(String msg, Exception cause) {
RuntimeException runtimeException = new RuntimeException(String.format("%s: [%s] %s", msg, cause.getClass().getName(), cause.getMessage()));
runtimeException.setStackTrace(cause.getStackTrace());
return runtimeException;
}
- protected IDatabaseConnection getConnection() {
- return connection;
+ protected Connection getConnection() throws SQLException {
+ return database.getDataSource().getConnection();
}
}
import java.util.List;
public abstract class DatabaseCommands {
-
- private IDataTypeFactory dbUnitFactory;
+ private final IDataTypeFactory dbUnitFactory;
private DatabaseCommands(IDataTypeFactory dbUnitFactory) {
this.dbUnitFactory = dbUnitFactory;
public abstract List<String> resetPrimaryKey(String table);
- Object getTrue() {
+ public Object getTrue() {
return Boolean.TRUE;
}
- Object getFalse() {
+ public Object getFalse() {
return Boolean.FALSE;
}
- IDataTypeFactory getDbUnitFactory() {
+ public IDataTypeFactory getDbUnitFactory() {
return dbUnitFactory;
}
- DatabaseOperation getDbunitDatabaseOperation() {
- return DatabaseOperation.CLEAN_INSERT;
+ public DatabaseOperation getDbunitDatabaseOperation() {
+ return new InsertIdentityOperation(DatabaseOperation.INSERT);
}
static final DatabaseCommands H2 = new DatabaseCommands(new H2DataTypeFactory()) {
}
@Override
- DatabaseOperation getDbunitDatabaseOperation() {
+ public DatabaseOperation getDbunitDatabaseOperation() {
return new InsertIdentityOperation(DatabaseOperation.CLEAN_INSERT);
}
};
}
@Override
- Object getTrue() {
+ public Object getTrue() {
return 1;
}
@Override
- Object getFalse() {
+ public Object getFalse() {
return 0;
}
};
* @since 3.2
*/
public class H2Database implements Database {
- private static BasicDataSource datasource;
+ private final String name;
+ private BasicDataSource datasource;
+
+ /**
+ * IMPORTANT: change DB name in order to not conflict with {@link DefaultDatabaseTest}
+ */
+ public H2Database(String name) {
+ this.name = name;
+ }
public H2Database start() {
- if (datasource == null) {
- startDatabase();
- createSchema();
- }
+ startDatabase();
+ createSchema();
return this;
}
- /**
- * IMPORTANT: DB name changed from "sonar" to "sonar2" in order to not conflict with {@link DefaultDatabaseTest}
- */
private void startDatabase() {
try {
datasource = new BasicDataSource();
datasource.setDriverClassName("org.h2.Driver");
datasource.setUsername("sonar");
datasource.setPassword("sonar");
- datasource.setUrl("jdbc:h2:mem:sonar2");
- datasource.setMaxActive(2);
- datasource.setMaxIdle(2);
+ datasource.setUrl("jdbc:h2:mem:" + name);
} catch (Exception e) {
throw new IllegalStateException("Fail to start H2", e);
}
public H2Database stop() {
try {
- if (datasource != null) {
- datasource.close();
- datasource = null;
- }
+ datasource.close();
} catch (SQLException e) {
// Ignore error
}
*/
package org.sonar.core.persistence;
-import org.apache.commons.dbcp.BasicDataSource;
+import org.junit.After;
+
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class H2DatabaseTest {
- H2Database db = new H2Database();
+ H2Database db = new H2Database("sonar2");
@Before
public void startDb() {
db.start();
}
- @Before
+ @After
public void stopDb() {
db.stop();
}
assertThat(tableCount).isGreaterThan(30);
}
-
- @Test
- public void shouldLimitThePoolSize() {
- BasicDataSource dataSource = (BasicDataSource) db.getDataSource();
-
- assertThat(dataSource.getMaxActive()).isEqualTo(2);
- assertThat(dataSource.getMaxIdle()).isEqualTo(2);
- }
}
import static org.mockito.Mockito.verify;
public class MyBatisTest {
-
private static H2Database database;
+ private Logback logback = mock(Logback.class);
@BeforeClass
public static void start() {
- database = new H2Database();
+ database = new H2Database("sonar2");
database.start();
}
@Test
public void shouldConfigureMyBatis() {
- MyBatis myBatis = new MyBatis(database, new Settings(), new Logback());
+ MyBatis myBatis = new MyBatis(database, new Settings(), logback);
myBatis.start();
Configuration conf = myBatis.getSessionFactory().getConfiguration();
@Test
public void shouldOpenBatchSession() {
- MyBatis myBatis = new MyBatis(database, new Settings(), new Logback());
+ MyBatis myBatis = new MyBatis(database, new Settings(), logback);
myBatis.start();
SqlSession session = myBatis.openBatchSession();
@Test
public void log_sql_requests() {
- Logback logback = mock(Logback.class);
- Settings settings = new Settings();
- settings.setProperty("sonar.showSql", true);
+ Settings settings = new Settings()
+ .setProperty("sonar.showSql", true);
+
MyBatis myBatis = new MyBatis(database, settings, logback);
myBatis.start();
@Test
public void log_sql_requests_and_responses() {
- Logback logback = mock(Logback.class);
- Settings settings = new Settings();
- settings.setProperty("sonar.showSql", true);
- settings.setProperty("sonar.showSqlResults", true);
+ Settings settings = new Settings()
+ .setProperty("sonar.showSql", true)
+ .setProperty("sonar.showSqlResults", true);
+
MyBatis myBatis = new MyBatis(database, settings, logback);
myBatis.start();
dao.indexResource(10, "ZipUtils", "FIL", 8);
- checkTables("shouldIndexResource", new String[]{"id"}, "resource_index");
+ checkTables("shouldIndexResource", new String[] {"id"}, "resource_index");
}
@Test
dao.indexProjects();
- checkTables("shouldIndexProjects", new String[]{"id"}, "resource_index");
+ checkTables("shouldIndexProjects", new String[] {"id"}, "resource_index");
}
@Test
dao.indexProject(1);
- checkTables("shouldIndexMultiModulesProject", new String[]{"id"}, "resource_index");
+ checkTables("shouldIndexMultiModulesProject", new String[] {"id"}, "resource_index");
}
@Test
dao.indexProject(1);
- checkTables("shouldReindexProjectAfterRenaming", new String[]{"id"}, "resource_index");
+ checkTables("shouldReindexProjectAfterRenaming", new String[] {"id"}, "resource_index");
}
@Test
dao.indexProject(1);
- Connection connection = getConnection().getConnection();
+ Connection connection = getConnection();
ResultSet rs = null;
try {
// project
dao.indexResource(10, "AB", Qualifiers.FILE, 3);
- checkTables("empty", new String[]{"id"}, "resource_index");
+ checkTables("empty", new String[] {"id"}, "resource_index");
}
@Test
dao.indexResource(1, "New Struts", Qualifiers.PROJECT, 1);
- checkTables("shouldReindexResource", new String[]{"id"}, "resource_index");
+ checkTables("shouldReindexResource", new String[] {"id"}, "resource_index");
}
@Test
dao.indexResource(1, "Struts", Qualifiers.PROJECT, 1);
- checkTables("shouldNotReindexUnchangedResource", new String[]{"id"}, "resource_index");
+ checkTables("shouldNotReindexUnchangedResource", new String[] {"id"}, "resource_index");
}
}
import org.dbunit.IDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
-import org.dbunit.dataset.*;
+import org.dbunit.dataset.CompositeDataSet;
+import org.dbunit.dataset.IDataSet;
+import org.dbunit.dataset.ITable;
+import org.dbunit.dataset.ReplacementDataSet;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.FlatXmlDataSet;
-import org.dbunit.ext.h2.H2DataTypeFactory;
-import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
private static Database database;
private static DefaultDatabaseConnector dbConnector;
private static DatabaseCommands databaseCommands;
-
- private JpaDatabaseSession session;
- private IDatabaseTester databaseTester;
- private IDatabaseConnection connection;
+ private static IDatabaseTester databaseTester;
+ private static JpaDatabaseSession session;
@BeforeClass
- public static void startDatabase() throws Exception {
- database = new H2Database();
+ public static void startDatabase() {
+ database = new H2Database("sonarHibernate");
database.start();
dbConnector = new MemoryDatabaseConnector(database);
dbConnector.start();
databaseCommands = DatabaseCommands.forDialect(database.getDialect());
- }
-
- @Before
- public void startConnection() throws Exception {
- databaseCommands.truncateDatabase(database.getDataSource().getConnection());
databaseTester = new DataSourceDatabaseTester(database.getDataSource());
session = new JpaDatabaseSession(dbConnector);
session.start();
}
+ @Before
+ public void setupDbUnit() throws SQLException {
+ databaseCommands.truncateDatabase(database.getDataSource().getConnection());
+ }
+
@After
public void stopConnection() throws Exception {
- if (databaseTester != null) {
- databaseTester.onTearDown();
- }
- if (connection != null) {
- connection.close();
- }
if (session != null) {
- session.stop();
+ session.rollback();
}
}
protected DatabaseSessionFactory getSessionFactory() {
return new DatabaseSessionFactory() {
-
public DatabaseSession getSession() {
return session;
}
}
private void setupData(InputStream... dataSetStream) {
+ IDatabaseConnection connection = null;
try {
IDataSet[] dataSets = new IDataSet[dataSetStream.length];
for (int i = 0; i < dataSetStream.length; i++) {
- ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(dataSetStream[i]));
- dataSet.addReplacementObject("[null]", null);
- dataSets[i] = dataSet;
+ dataSets[i] = getData(dataSetStream[i]);
}
- CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets);
+ databaseTester.setDataSet(new CompositeDataSet(dataSets));
- databaseTester.setDataSet(compositeDataSet);
- connection = databaseTester.getConnection();
-
- connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new H2DataTypeFactory());
- DatabaseOperation.CLEAN_INSERT.execute(connection, databaseTester.getDataSet());
+ connection = createConnection();
+ databaseCommands.getDbunitDatabaseOperation().execute(connection, databaseTester.getDataSet());
} catch (Exception e) {
throw translateException("Could not setup DBUnit data", e);
+ } finally {
+ closeQuietly(connection);
+ }
+ }
+
+ private void closeQuietly(IDatabaseConnection connection) {
+ try {
+ if (connection != null) {
+ connection.close();
+ }
+ } catch (SQLException e) {
}
}
}
protected void checkTables(String testName, String[] excludedColumnNames, String... tables) {
- getSession().commit();
+ IDatabaseConnection connection = null;
try {
- IDataSet dataSet = getCurrentDataSet();
+ connection = createConnection();
+
+ IDataSet dataSet = connection.createDataSet();
IDataSet expectedDataSet = getExpectedData(testName);
for (String table : tables) {
ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(dataSet.getTable(table), excludedColumnNames);
ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable(table), excludedColumnNames);
Assertion.assertEquals(filteredExpectedTable, filteredTable);
}
- } catch (DataSetException e) {
- throw translateException("Error while checking results", e);
} catch (DatabaseUnitException e) {
fail(e.getMessage());
+ } catch (SQLException e) {
+ throw translateException("Error while checking results", e);
+ } finally {
+ closeQuietly(connection);
}
}
- /**
- * Opposite of {@link #checkTables(String, String[], String...)}.
- */
- protected void checkColumns(String testName, String table, String... columns) {
- getSession().commit();
+ private IDatabaseConnection createConnection() {
try {
- IDataSet dataSet = getCurrentDataSet();
- IDataSet expectedDataSet = getExpectedData(testName);
- ITable filteredTable = DefaultColumnFilter.includedColumnsTable(dataSet.getTable(table), columns);
- ITable filteredExpectedTable = DefaultColumnFilter.includedColumnsTable(expectedDataSet.getTable(table), columns);
- Assertion.assertEquals(filteredExpectedTable, filteredTable);
-
- } catch (DataSetException e) {
- throw translateException("Error while checking columns", e);
- } catch (DatabaseUnitException e) {
- fail(e.getMessage());
+ IDatabaseConnection connection = databaseTester.getConnection();
+ connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, databaseCommands.getDbUnitFactory());
+ return connection;
+ } catch (Exception e) {
+ throw translateException("Error while getting connection", e);
}
}
private IDataSet getExpectedData(String testName) {
String className = getClass().getName();
- className = String.format("/%s/%s-result.xml", className.replace(".", "/"), testName);
+ className = String.format("/%s/%s-result.xml", className.replace('.', '/'), testName);
InputStream in = getClass().getResourceAsStream(className);
try {
try {
ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(stream));
dataSet.addReplacementObject("[null]", null);
+ dataSet.addReplacementObject("[false]", databaseCommands.getFalse());
+ dataSet.addReplacementObject("[true]", databaseCommands.getTrue());
return dataSet;
} catch (Exception e) {
throw translateException("Could not read the dataset stream", e);
}
}
- private IDataSet getCurrentDataSet() {
- try {
- return connection.createDataSet();
- } catch (SQLException e) {
- throw translateException("Could not create the current dataset", e);
- }
- }
-
private static RuntimeException translateException(String msg, Exception cause) {
RuntimeException runtimeException = new RuntimeException(String.format("%s: [%s] %s", msg, cause.getClass().getName(), cause.getMessage()));
runtimeException.setStackTrace(cause.getStackTrace());