aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-core/src/test/java
diff options
context:
space:
mode:
authorsimonbrandhof <simon.brandhof@gmail.com>2010-09-06 14:08:06 +0000
committersimonbrandhof <simon.brandhof@gmail.com>2010-09-06 14:08:06 +0000
commitaeadc1f9129274949daaa57738c7c4550bdfbc7b (patch)
tree08dadf5ef7474fc41d1d48f74648f1ba8b55f34d /sonar-core/src/test/java
downloadsonarqube-aeadc1f9129274949daaa57738c7c4550bdfbc7b.tar.gz
sonarqube-aeadc1f9129274949daaa57738c7c4550bdfbc7b.zip
SONAR-236 remove deprecated code from checkstyle plugin + display default value of rule parameters in Q profile console
Diffstat (limited to 'sonar-core/src/test/java')
-rw-r--r--sonar-core/src/test/java/org/sonar/api/database/configuration/DatabaseConfigurationTest.java40
-rw-r--r--sonar-core/src/test/java/org/sonar/api/database/configuration/ResourceDatabaseConfigurationTest.java41
-rw-r--r--sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginDaoTest.java120
-rw-r--r--sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginTest.java42
-rw-r--r--sonar-core/src/test/java/org/sonar/core/purge/AbstractPurgeTest.java39
-rw-r--r--sonar-core/src/test/java/org/sonar/core/qualitymodel/DefaultModelProviderTest.java121
-rw-r--r--sonar-core/src/test/java/org/sonar/core/qualitymodel/ModelTest.java106
-rw-r--r--sonar-core/src/test/java/org/sonar/core/rule/DefaultRuleProviderTest.java83
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresDaoTest.java165
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresServiceTest.java153
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dao/MeasuresDaoTest.java107
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dao/ProfilesDaoTest.java68
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dao/RulesDaoTest.java131
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/DerbyTest.java32
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/DialectRepositoryTest.java70
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/HsqlDbTest.java32
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/MsSqlTest.java37
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/MySqlTest.java37
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/OracleSequenceGeneratorTest.java43
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/OracleTest.java32
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSQLSequenceGeneratorTest.java43
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSqlTest.java33
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/entity/PropertyTest.java39
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/entity/SchemaMigrationTest.java65
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/session/AbstractDatabaseConnectorTest.java114
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/session/DatabaseSessionTest.java120
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/session/DriverDatabaseConnectorTest.java92
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/session/ThreadLocalDatabaseSessionFactoryTest.java49
-rw-r--r--sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java247
29 files changed, 2301 insertions, 0 deletions
diff --git a/sonar-core/src/test/java/org/sonar/api/database/configuration/DatabaseConfigurationTest.java b/sonar-core/src/test/java/org/sonar/api/database/configuration/DatabaseConfigurationTest.java
new file mode 100644
index 00000000000..26a54faedff
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/api/database/configuration/DatabaseConfigurationTest.java
@@ -0,0 +1,40 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.database.configuration;
+
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+public class DatabaseConfigurationTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void shouldLoadPropertiesFromDatabase() {
+ setupData("some-properties");
+
+ DatabaseConfiguration configuration = new DatabaseConfiguration(getSessionFactory());
+
+ assertEquals("value1", configuration.getString("key1"));
+ assertEquals("value2", configuration.getString("key2"));
+ assertNull(configuration.getString("keyxxxx"));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/api/database/configuration/ResourceDatabaseConfigurationTest.java b/sonar-core/src/test/java/org/sonar/api/database/configuration/ResourceDatabaseConfigurationTest.java
new file mode 100644
index 00000000000..a856d0729fd
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/api/database/configuration/ResourceDatabaseConfigurationTest.java
@@ -0,0 +1,41 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.database.configuration;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+public class ResourceDatabaseConfigurationTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void shouldNotLoadGlobalProperties() {
+ setupData("shouldNotLoadGlobalProperties");
+
+ ResourceDatabaseConfiguration conf = new ResourceDatabaseConfiguration(getSessionFactory(), 100);
+ assertEquals(2, CollectionUtils.size(conf.getKeys()));
+ assertEquals("project_value1", conf.getString("key1"));
+ assertNull(conf.getString("key2"));
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginDaoTest.java b/sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginDaoTest.java
new file mode 100644
index 00000000000..ba4e26a322b
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginDaoTest.java
@@ -0,0 +1,120 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.core.plugin;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static junit.framework.Assert.assertEquals;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class JpaPluginDaoTest extends AbstractDbUnitTestCase {
+
+ private JpaPluginDao dao;
+
+ @Before
+ public void before() {
+ dao = new JpaPluginDao(getSessionFactory());
+ }
+
+ @Test
+ public void getPlugins() {
+ setupData("shared");
+
+ List<JpaPlugin> plugins = dao.getPlugins();
+
+ assertEquals(1, plugins.size());
+ assertEquals("checkstyle", plugins.get(0).getKey());
+ assertEquals(2, plugins.get(0).getFiles().size());
+ }
+
+
+ @Test
+ public void savePluginAndFiles() {
+ setupData("shared");
+ JpaPlugin pmd = JpaPlugin.create("pmd");
+ pmd.setCore(false);
+ pmd.setName("PMD");
+ pmd.setVersion("2.2");
+ pmd.setPluginClass("org.sonar.pmd.Main");
+
+ pmd.createFile("sonar-pmd-plugin-2.2.jar");
+ pmd.createFile("pmd-extension.jar");
+ pmd.createFile("pmd-extension2.jar");
+
+ getSession().saveWithoutFlush(pmd);
+ checkTables("savePluginAndFiles", "plugins", "plugin_files");
+ }
+
+ @Test
+ public void saveDeprecatedPlugin() {
+ setupData("shared");
+ JpaPlugin pmd = JpaPlugin.create("pmd");
+ pmd.setCore(false);
+ pmd.setName("PMD");
+ pmd.setPluginClass("org.sonar.pmd.Main");
+
+ pmd.createFile("sonar-pmd-plugin-2.2.jar");
+
+ getSession().saveWithoutFlush(pmd);
+ checkTables("saveDeprecatedPlugin", "plugins", "plugin_files");
+ }
+
+ @Test
+ public void removePreviousFilesWhenRegisteringPlugin() {
+ setupData("shared");
+
+ List<JpaPlugin> plugins = dao.getPlugins();
+ plugins.get(0).removeFiles();
+ plugins.get(0).createFile("newfile.jar");
+
+ dao.register(plugins);
+
+ checkTables("removePreviousFilesWhenRegisteringPlugin", "plugins", "plugin_files");
+ }
+
+ @Test
+ public void registerManyPlugins() {
+ setupData("shared");
+
+ List<JpaPlugin> plugins = createManyPlugins();
+ dao.register(plugins);
+
+ assertThat(dao.getPlugins().size(), is(150));
+ assertThat(dao.getPluginFiles().size(), is(150 * 20)); // initial plugin "checkstyle" has been deleted
+ }
+
+ private List<JpaPlugin> createManyPlugins() {
+ List<JpaPlugin> plugins = new ArrayList<JpaPlugin>();
+ for (int i=0 ; i<150 ; i++) {
+ JpaPlugin plugin = JpaPlugin.create("plugin-" + i);
+ for (int j=0 ; j<20 ; j++) {
+ plugin.createFile("file-" + i + "-" + j + ".jar");
+ }
+ plugins.add(plugin);
+ }
+ return plugins;
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginTest.java b/sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginTest.java
new file mode 100644
index 00000000000..6a6d3cad2ca
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/core/plugin/JpaPluginTest.java
@@ -0,0 +1,42 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.core.plugin;
+
+import org.junit.Test;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class JpaPluginTest {
+
+ @Test
+ public void createPlugin() {
+ JpaPlugin plugin = JpaPlugin.create("foo");
+ assertThat(plugin.getKey(), is("foo"));
+
+ assertEquals(plugin, plugin);
+ assertEquals(plugin, JpaPlugin.create("foo"));
+ assertFalse(plugin.equals(JpaPlugin.create("bar")));
+ }
+
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/core/purge/AbstractPurgeTest.java b/sonar-core/src/test/java/org/sonar/core/purge/AbstractPurgeTest.java
new file mode 100644
index 00000000000..5211d037cd3
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/core/purge/AbstractPurgeTest.java
@@ -0,0 +1,39 @@
+package org.sonar.core.purge;
+
+import org.junit.Test;
+import org.sonar.api.batch.PurgeContext;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.sql.SQLException;
+import java.util.Arrays;
+
+/**
+ * Created by IntelliJ IDEA.
+ * User: SimonBrandhof
+ * Date: Jul 20, 2010
+ * Time: 10:47:13 PM
+ * To change this template use File | Settings | File Templates.
+ */
+public class AbstractPurgeTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void purgeSnapshots() throws SQLException {
+ setupData("purgeSnapshots");
+
+ final FakePurge purge = new FakePurge(getSession());
+ purge.purge(null);
+
+ checkTables("purgeSnapshots", "snapshots", "project_measures", "measure_data", "rule_failures", "snapshot_sources", "dependencies");
+ }
+}
+
+class FakePurge extends AbstractPurge {
+ public FakePurge(DatabaseSession session) {
+ super(session);
+ }
+
+ public void purge(PurgeContext context) {
+ deleteSnapshotData(Arrays.asList(3, 4));
+ }
+} \ No newline at end of file
diff --git a/sonar-core/src/test/java/org/sonar/core/qualitymodel/DefaultModelProviderTest.java b/sonar-core/src/test/java/org/sonar/core/qualitymodel/DefaultModelProviderTest.java
new file mode 100644
index 00000000000..beb59782327
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/core/qualitymodel/DefaultModelProviderTest.java
@@ -0,0 +1,121 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.core.qualitymodel;
+
+import org.junit.Test;
+import org.sonar.api.qualitymodel.Characteristic;
+import org.sonar.api.qualitymodel.Model;
+import org.sonar.api.qualitymodel.ModelDefinition;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
+public class DefaultModelProviderTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void reset() {
+ setupData("shared");
+ DefaultModelProvider provider = new DefaultModelProvider(getSessionFactory());
+
+ Model model = Model.createByName("M1");
+ Characteristic c1 = model.createCharacteristicByName("NEWM1C1");
+ Characteristic c1a = model.createCharacteristicByName("NEWM1C1A");
+ c1.addChild(c1a);
+
+ model.createCharacteristicByName("NEWM1C2");
+ model = provider.reset(model);
+
+ model = getSession().getSingleResult(Model.class, "name", "M1");
+ assertNotNull(model);
+ assertThat(model.getCharacteristics().size(), is(3));
+ assertThat(model.getCharacteristicByName("NEWM1C1A").getParents().size(), is(1));
+ assertNotNull(model.getCharacteristicByName("NEWM1C1A").getParent("NEWM1C1"));
+ }
+
+ @Test
+ public void findByName() {
+ setupData("shared");
+ DefaultModelProvider provider = new DefaultModelProvider(getSessionFactory());
+ Model model = provider.findByName("M1");
+ assertNotNull(model);
+ assertNotNull(model.getCharacteristicByName("M1C1"));
+ }
+
+ @Test
+ public void findByNameNotFound() {
+ setupData("shared");
+ DefaultModelProvider provider = new DefaultModelProvider(getSessionFactory());
+ assertNull(provider.findByName("UNKNOWN"));
+ }
+
+ @Test
+ public void noDefinitionsToRegister() {
+ setupData("shared");
+ DefaultModelProvider provider = new DefaultModelProvider(getSessionFactory());
+ provider.registerDefinitions();
+
+ // same state
+ List<Model> models = getSession().getResults(Model.class);
+ assertThat(models.size(), is(2));
+ }
+
+ @Test
+ public void registerOnlyNewDefinitions() {
+ setupData("shared");
+
+ ModelDefinition existingDefinition = new FakeDefinition("M1");
+ ModelDefinition newDefinition = new FakeDefinition("NEWMODEL");
+
+ ModelDefinition[] definitions = new ModelDefinition[]{existingDefinition, newDefinition};
+ DefaultModelProvider provider = new DefaultModelProvider(getSessionFactory(), definitions);
+ provider.registerDefinitions();
+
+ List<Model> models = getSession().getResults(Model.class);
+ assertThat(models.size(), is(3)); // 2 existing + one new
+ }
+
+ @Test
+ public void exists() {
+ setupData("shared");
+ assertTrue(DefaultModelProvider.exists(getSession(), "M1"));
+ }
+
+ @Test
+ public void notExists() {
+ setupData("shared");
+ assertFalse(DefaultModelProvider.exists(getSession(), "UNKNOWN"));
+ }
+}
+
+class FakeDefinition extends ModelDefinition {
+
+ public FakeDefinition(String name) {
+ super(name);
+ }
+
+ @Override
+ public Model create() {
+ return Model.create();
+ }
+
+} \ No newline at end of file
diff --git a/sonar-core/src/test/java/org/sonar/core/qualitymodel/ModelTest.java b/sonar-core/src/test/java/org/sonar/core/qualitymodel/ModelTest.java
new file mode 100644
index 00000000000..a9793912a13
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/core/qualitymodel/ModelTest.java
@@ -0,0 +1,106 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.core.qualitymodel;
+
+import org.junit.Test;
+import org.sonar.api.qualitymodel.Characteristic;
+import org.sonar.api.qualitymodel.Model;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.internal.matchers.IsCollectionContaining.hasItems;
+
+public class ModelTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void saveModelAndCharacteristics() {
+ setupData("saveModelAndCharacteristics");
+ Model model = Model.createByName("fake");
+ model.createCharacteristicByName("Efficiency");
+ model.createCharacteristicByName("Usability");
+ getSession().save(model);
+ getSession().commit();
+
+ model = getSession().getSingleResult(Model.class, "name", "fake");
+ assertThat(model.getName(), is("fake"));
+ assertThat(model.getCharacteristics().size(), is(2));
+ assertThat(model.getRootCharacteristics().size(), is(2));
+ assertNotNull(model.getCharacteristicByName("Efficiency"));
+ }
+
+ /**
+ * max one parent by characteristic
+ */
+ @Test
+ public void saveTreeOfCharacteristics() {
+ setupData("testTreeOfCharacteristics");
+ Model model = Model.createByName("fake");
+
+ Characteristic efficiency = model.createCharacteristicByName("Efficiency");
+ Characteristic usability = model.createCharacteristicByName("Usability");
+ Characteristic cpuEfficiency = model.createCharacteristicByName("CPU Efficiency");
+ Characteristic ramEfficiency = model.createCharacteristicByName("RAM Efficiency");
+
+ efficiency.addChildren(cpuEfficiency, ramEfficiency);
+
+ getSession().save(model);
+ getSession().commit();
+
+ model = getSession().getSingleResult(Model.class, "name", "fake");
+ assertThat(model.getCharacteristics().size(), is(4));
+ assertThat(model.getCharacteristics(), hasItems(efficiency, usability, ramEfficiency, cpuEfficiency));
+ assertThat(efficiency.getChildren(), hasItems(ramEfficiency, cpuEfficiency));
+ assertTrue(ramEfficiency.getChildren().isEmpty());
+ assertThat(ramEfficiency.getParents(), hasItems(efficiency));
+ }
+
+ /**
+ * many-to-many relation between characteristics
+ */
+ @Test
+ public void testGraphOfCharacteristics() {
+ setupData("testGraphOfCharacteristics");
+ Model model = Model.createByName("fake");
+
+ Characteristic level1a = model.createCharacteristicByName("level1a");
+ Characteristic level1b = model.createCharacteristicByName("level1b");
+ Characteristic level2a = model.createCharacteristicByName("level2a");
+ Characteristic level2b = model.createCharacteristicByName("level2b");
+
+ level1a.addChildren(level2a, level2b);
+ level1b.addChildren(level2a, level2b);
+
+ getSession().save(model);
+ getSession().commit();
+
+ Model persistedModel = getSession().getSingleResult(Model.class, "name", "fake");
+ assertThat(persistedModel.getCharacteristics().size(), is(4));
+ assertThat(persistedModel.getRootCharacteristics().size(), is(2));
+
+ assertThat(persistedModel.getCharacteristicByName("level1a").getChildren().size(), is(2));
+ assertThat(persistedModel.getCharacteristicByName("level1b").getChildren().size(), is(2));
+
+ assertThat(persistedModel.getCharacteristicByName("level2a").getParents().size(), is(2));
+ assertThat(persistedModel.getCharacteristicByName("level2b").getParents().size(), is(2));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/core/rule/DefaultRuleProviderTest.java b/sonar-core/src/test/java/org/sonar/core/rule/DefaultRuleProviderTest.java
new file mode 100644
index 00000000000..10830c4256f
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/core/rule/DefaultRuleProviderTest.java
@@ -0,0 +1,83 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.core.rule;
+
+import org.junit.Test;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RuleQuery;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.util.Collection;
+
+import static org.hamcrest.CoreMatchers.anyOf;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+
+public class DefaultRuleProviderTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void findByKey() {
+ setupData("shared");
+ DefaultRuleProvider provider = new DefaultRuleProvider(getSessionFactory());
+ Rule rule = provider.findByKey("checkstyle", "com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck");
+ assertNotNull(rule);
+ assertThat(rule.getKey(), is("com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck"));
+ assertThat(rule.isEnabled(), is(true));
+ }
+
+ @Test
+ public void findRepositoryRules() {
+ setupData("shared");
+ DefaultRuleProvider provider = new DefaultRuleProvider(getSessionFactory());
+ Collection<Rule> rules = provider.findAll(RuleQuery.create().withRepositoryKey("checkstyle"));
+ assertNotNull(rules);
+ assertThat(rules.size(), is(2)); // only enabled checkstyle rules
+ }
+
+ @Test
+ public void findAllEnabled() {
+ setupData("shared");
+ DefaultRuleProvider provider = new DefaultRuleProvider(getSessionFactory());
+ Collection<Rule> rules = provider.findAll(RuleQuery.create());
+ assertNotNull(rules);
+ assertThat(rules.size(), is(3)); // only enabled checkstyle+pmd rules
+ for (Rule rule : rules) {
+ assertThat(rule.getId(), anyOf(is(1), is(3), is(4)));
+ }
+ }
+
+ @Test
+ public void doNotFindDisabledRules() {
+ setupData("shared");
+ DefaultRuleProvider provider = new DefaultRuleProvider(getSessionFactory());
+ Rule rule = provider.findByKey("checkstyle", "DisabledCheck");
+ assertNull(rule);
+ }
+
+ @Test
+ public void doNotFindUnknownRules() {
+ setupData("shared");
+ DefaultRuleProvider provider = new DefaultRuleProvider(getSessionFactory());
+ Collection<Rule> rules = provider.findAll(RuleQuery.create().withRepositoryKey("unknown_repository"));
+ assertThat(rules.size(), is(0));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresDaoTest.java b/sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresDaoTest.java
new file mode 100644
index 00000000000..3c70c3fd62c
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresDaoTest.java
@@ -0,0 +1,165 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dao;
+
+import org.junit.Test;
+import org.sonar.api.database.model.AsyncMeasureSnapshot;
+import org.sonar.api.database.model.MeasureModel;
+import org.sonar.api.database.model.ResourceModel;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class AsyncMeasuresDaoTest extends AbstractDbUnitTestCase {
+
+ private static final int PROJECT_ID = 1;
+ private static final int METRIC_ID = 1;
+
+ @Test
+ public void testGetNextAsyncMeasureSnapshot() {
+ setupData("sharedFixture", "testGetNextAsyncMeasureSnapshot");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ AsyncMeasureSnapshot asyncMeasure = asyncMeasuresDao.getNextAsyncMeasureSnapshot(
+ PROJECT_ID, METRIC_ID, stringToDate("2008-12-04 08:00:00.00"));
+
+ assertThat(asyncMeasure.getId(), is(3));
+ }
+
+ @Test
+ public void testGetNextSnapshotsUntilDate() {
+ setupData("sharedFixture", "testGetNextSnapshotsUntilDate");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ MeasureModel asyncMeasure = getSession().getEntityManager().find(MeasureModel.class, 1l);
+ List<Snapshot> snapshotIds = asyncMeasuresDao.getNextSnapshotsUntilDate(
+ asyncMeasure, stringToDate("2008-12-06 12:00:00.00"));
+
+ assertThat(snapshotIds.size(), is(2));
+ assertThat(snapshotIds.get(0).getId(), is(2));
+ assertThat(snapshotIds.get(1).getId(), is(4));
+ }
+
+ @Test
+ public void testGetPreviousSnapshot() {
+ setupData("sharedFixture", "testGetPreviousSnapshot");
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ Snapshot s = new Snapshot();
+ s.setCreatedAt(stringToDate("2008-12-04 08:00:00.00"));
+ s.setScope(ResourceModel.SCOPE_PROJECT);
+ ResourceModel resource1 = getSession().getEntity(ResourceModel.class, 1);
+ ResourceModel resource2 = getSession().getEntity(ResourceModel.class, 2);
+
+ s.setResource(resource1);
+ assertThat(asyncMeasuresDao.getPreviousSnapshot(s).getId(), is(1));
+
+ s.setResource(resource2);
+ assertThat(asyncMeasuresDao.getPreviousSnapshot(s).getId(), is(5));
+ }
+
+ @Test
+ public void testGetNextAsyncMeasureSnapshotsUntilDate() {
+ setupData("sharedFixture", "testGetNextAsyncMeasureSnapshotsUntilDate");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ MeasureModel asyncMeasure = getSession().getEntityManager().find(MeasureModel.class, 3l);
+ List<AsyncMeasureSnapshot> asyncMeasureSnapshots = asyncMeasuresDao.getNextAsyncMeasureSnapshotsUntilDate(
+ asyncMeasure, stringToDate("2008-12-06 08:00:00.00"));
+
+ assertThat(asyncMeasureSnapshots.size(), is(2));
+ assertThat(asyncMeasureSnapshots.get(0).getId(), is(2));
+ assertThat(asyncMeasureSnapshots.get(1).getId(), is(3));
+ }
+
+ @Test
+ public void testDeleteAsyncMeasure() {
+ setupData("sharedFixture", "testDeleteAsyncMeasure");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ MeasureModel asyncMeasure = getSession().getEntityManager().find(MeasureModel.class, 1l);
+ asyncMeasuresDao.deleteAsyncMeasure(asyncMeasure);
+
+ getSession().commit();
+ checkTables("testDeleteAsyncMeasure", "project_measures", "async_measure_snapshots");
+ }
+
+ @Test
+ public void testGetAsyncMeasureSnapshotsFromSnapshotId() {
+ setupData("sharedFixture", "testGetAsyncMeasureSnapshotsFromSnapshotId");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ Integer snapshotId = 1;
+ List<AsyncMeasureSnapshot> asyncMeasureSnapshots = asyncMeasuresDao.getAsyncMeasureSnapshotsFromSnapshotId(
+ snapshotId, Arrays.asList(1));
+ assertThat(asyncMeasureSnapshots.size(), is(1));
+ assertThat(asyncMeasureSnapshots.get(0).getId(), is(2));
+ }
+
+ @Test
+ public void testGetLastAsyncMeasureSnapshot() {
+ setupData("sharedFixture", "testGetLastAsyncMeasureSnapshot");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ AsyncMeasureSnapshot asyncMeasureSnapshot = asyncMeasuresDao.getLastAsyncMeasureSnapshot(
+ PROJECT_ID, METRIC_ID, stringToDate("2008-12-04 12:00:00.00"));
+ assertThat(asyncMeasureSnapshot.getId(), is(2));
+ }
+
+ @Test
+ public void testDeleteAsyncMeasureSnapshots() {
+ setupData("sharedFixture", "testDeleteAsyncMeasureSnapshots");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ asyncMeasuresDao.deleteAsyncMeasureSnapshots(1l);
+
+ checkTables("testDeleteAsyncMeasureSnapshots", "async_measure_snapshots");
+ }
+
+ @Test
+ public void testGetPreviousAsyncMeasureSnapshots() {
+ setupData("sharedFixture", "testGetPreviousAsyncMeasureSnapshots");
+
+ AsyncMeasuresDao asyncMeasuresDao = new AsyncMeasuresDao(getSession());
+ List<AsyncMeasureSnapshot> asyncMeasureSnapshots = asyncMeasuresDao.getPreviousAsyncMeasureSnapshots(
+ PROJECT_ID, stringToDate("2008-12-04 08:00:00.00"), stringToDate("2008-12-08 08:00:00.00"));
+ assertThat(asyncMeasureSnapshots.size(), is(2));
+ assertThat(asyncMeasureSnapshots.get(0).getId(), is(5));
+ assertThat(asyncMeasureSnapshots.get(1).getId(), is(6));
+ }
+
+
+ private static Date stringToDate(String sDate) {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
+ try {
+ return sdf.parse(sDate);
+ } catch (ParseException e) {
+ throw new RuntimeException("Bad date format.");
+ }
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresServiceTest.java b/sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresServiceTest.java
new file mode 100644
index 00000000000..9ef3ad41034
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dao/AsyncMeasuresServiceTest.java
@@ -0,0 +1,153 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dao;
+
+import org.junit.Test;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+public class AsyncMeasuresServiceTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void assignLatestMeasuresToLastSnapshot() {
+ setupData("sharedFixture", "assignLatestMeasuresToLastSnapshot");
+
+ AsyncMeasuresService asyncMeasuresService = new AsyncMeasuresService(getSession());
+ Snapshot snapshot = getSession().getEntityManager().find(Snapshot.class, 2);
+ asyncMeasuresService.refresh(snapshot);
+
+ checkTables("assignLatestMeasuresToLastSnapshot", "async_measure_snapshots");
+ }
+
+ @Test
+ public void assignNewMeasuresToLastSnapshot() {
+ setupData("sharedFixture", "assignNewMeasuresToLastSnapshot");
+
+ AsyncMeasuresService asyncMeasuresService = new AsyncMeasuresService(getSession());
+ Snapshot snapshot = getSession().getEntityManager().find(Snapshot.class, 2);
+ asyncMeasuresService.refresh(snapshot);
+
+ checkTables("assignNewMeasuresToLastSnapshot", "async_measure_snapshots");
+ }
+
+ @Test
+ public void assignMeasuresWhenNoPreviousSnapshot() {
+ setupData("sharedFixture", "assignMeasuresWhenNoPreviousSnapshot");
+
+ AsyncMeasuresService asyncMeasuresService = new AsyncMeasuresService(getSession());
+ Snapshot snapshot = getSession().getEntityManager().find(Snapshot.class, 1);
+ asyncMeasuresService.refresh(snapshot);
+
+ checkTables("assignMeasuresWhenNoPreviousSnapshot", "async_measure_snapshots");
+ }
+
+ @Test
+ public void assignLatestMeasuresWhenNoPreviousSnapshot() {
+ setupData("sharedFixture", "assignLatestMeasuresWhenNoPreviousSnapshot");
+
+ AsyncMeasuresService asyncMeasuresService = new AsyncMeasuresService(getSession());
+ Snapshot snapshot = getSession().getEntityManager().find(Snapshot.class, 1);
+ asyncMeasuresService.refresh(snapshot);
+
+ checkTables("assignLatestMeasuresWhenNoPreviousSnapshot", "async_measure_snapshots");
+ }
+
+ @Test
+ public void assignPastMeasuresToPastSnapshot() {
+ setupData("sharedFixture", "assignPastMeasuresToPastSnapshot");
+
+ AsyncMeasuresService asyncMeasuresService = new AsyncMeasuresService(getSession());
+ Snapshot snapshot = getSession().getEntityManager().find(Snapshot.class, 3);
+ asyncMeasuresService.refresh(snapshot);
+
+ checkTables("assignPastMeasuresToPastSnapshot", "async_measure_snapshots");
+ }
+
+ @Test
+ public void assignNewMeasureToFutureSnapshots() {
+ setupData("sharedFixture", "assignNewMeasureToFutureSnapshots");
+
+ AsyncMeasuresService asyncMeasuresService = new AsyncMeasuresService(getSession());
+ asyncMeasuresService.registerMeasure(2l);
+
+ checkTables("assignNewMeasureToFutureSnapshots", "async_measure_snapshots");
+ }
+
+ @Test
+ public void assignMeasureToFutureSnapshotsWithDifferentMetric() {
+ setupData("sharedFixture", "assignMeasureToFutureSnapshotsWithDifferentMetric");
+
+ AsyncMeasuresService asyncMeasureService = new AsyncMeasuresService(getSession());
+ asyncMeasureService.registerMeasure(3l);
+
+ checkTables("assignMeasureToFutureSnapshotsWithDifferentMetric", "async_measure_snapshots");
+ }
+
+ @Test
+ public void assignAPastMeasureToNextSnapshotsWithDifferentMetric() {
+ setupData("sharedFixture", "assignAPastMeasureToNextSnapshotsWithDifferentMetric");
+
+ AsyncMeasuresService asyncMeasureService = new AsyncMeasuresService(getSession());
+ asyncMeasureService.registerMeasure(2l);
+
+ checkTables("assignAPastMeasureToNextSnapshotsWithDifferentMetric", "async_measure_snapshots");
+ }
+
+ @Test
+ public void addFutureSnapshot() {
+ setupData("sharedFixture", "addFutureSnapshot");
+
+ AsyncMeasuresService asyncMeasureService = new AsyncMeasuresService(getSession());
+ asyncMeasureService.registerMeasure(2l);
+
+ checkTables("addFutureSnapshot", "async_measure_snapshots");
+ }
+
+ @Test
+ public void addInvisibleMeasure() {
+ setupData("sharedFixture", "addInvisibleMeasure");
+
+ AsyncMeasuresService asyncMeasureService = new AsyncMeasuresService(getSession());
+ asyncMeasureService.registerMeasure(2l);
+
+ checkTables("addInvisibleMeasure", "async_measure_snapshots");
+ }
+
+ @Test
+ public void deleteMeasure() {
+ setupData("sharedFixture", "deleteMeasure");
+
+ AsyncMeasuresService asyncMeasureService = new AsyncMeasuresService(getSession());
+ asyncMeasureService.deleteMeasure(2l);
+
+ checkTables("deleteMeasure", "async_measure_snapshots");
+ }
+
+ @Test
+ public void deleteLastMeasure() {
+ setupData("sharedFixture", "deleteLastMeasure");
+
+ AsyncMeasuresService asyncMeasureService = new AsyncMeasuresService(getSession());
+ asyncMeasureService.deleteMeasure(1l);
+
+ checkTables("deleteLastMeasure", "async_measure_snapshots");
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dao/MeasuresDaoTest.java b/sonar-core/src/test/java/org/sonar/jpa/dao/MeasuresDaoTest.java
new file mode 100644
index 00000000000..5502905e5e6
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dao/MeasuresDaoTest.java
@@ -0,0 +1,107 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dao;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.api.database.model.ResourceModel;
+import org.sonar.api.measures.Metric;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertThat;
+
+public class MeasuresDaoTest extends AbstractDbUnitTestCase {
+
+ private MeasuresDao service;
+ private ResourceModel project;
+
+ @Before
+ public void before() throws Exception {
+ service = new MeasuresDao(getSession());
+ project = new ResourceModel(ResourceModel.SCOPE_PROJECT, "foo:bar", ResourceModel.QUALIFIER_PROJECT_TRUNK, null, "Foo");
+ project.setName("project name");
+ getSession().save(project);
+ }
+
+ @Test
+ public void shouldReturnUserDefinedMetrics() {
+ for (Metric metric : createMetrics()) {
+ getSession().save(metric);
+ }
+
+ Collection<Metric> metrics = service.getUserDefinedMetrics();
+ assertThat(metrics.size(), is(2));
+ for (Metric metric : metrics) {
+ assertThat(metric.getOrigin(), not(Metric.Origin.JAV));
+ }
+ }
+
+ @Test
+ public void shouldRegisterMetrics() {
+ Collection<Metric> newMetrics = createMetrics();
+ service.registerMetrics(newMetrics);
+
+ Collection<Metric> metrics = service.getEnabledMetrics();
+ assertThat(metrics.size(), is(newMetrics.size()));
+ }
+
+ @Test
+ public void shouldDisabledMetrics() {
+ Collection<Metric> newMetrics = createMetrics();
+
+ service.disabledMetrics(newMetrics);
+
+ Collection<Metric> allMetrics = service.getMetrics();
+ assertThat(allMetrics.size(), is(newMetrics.size()));
+
+ Collection<Metric> disabledMetrics = service.getEnabledMetrics();
+ assertThat(disabledMetrics.size(), is(0));
+ }
+
+
+ private Collection<Metric> createMetrics() {
+ Metric m1 = new Metric("metric1");
+ m1.setEnabled(false);
+ m1.setOrigin(Metric.Origin.JAV);
+
+ Metric m2 = new Metric("metric2");
+ m2.setEnabled(true);
+ m2.setOrigin(Metric.Origin.JAV);
+
+ Metric m3 = new Metric("metric3");
+ m3.setEnabled(false);
+ m3.setOrigin(Metric.Origin.GUI);
+
+ Metric m4 = new Metric("metric4");
+ m4.setEnabled(true);
+ m4.setOrigin(Metric.Origin.GUI);
+
+ Metric m5 = new Metric("metric5");
+ m5.setEnabled(true);
+ m5.setOrigin(Metric.Origin.WS);
+
+ return Arrays.asList(m1, m2, m3, m4, m5);
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dao/ProfilesDaoTest.java b/sonar-core/src/test/java/org/sonar/jpa/dao/ProfilesDaoTest.java
new file mode 100644
index 00000000000..796435c5dab
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dao/ProfilesDaoTest.java
@@ -0,0 +1,68 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dao;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.api.database.model.ResourceModel;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
+public class ProfilesDaoTest extends AbstractDbUnitTestCase {
+
+ private ProfilesDao profilesDao;
+
+ @Before
+ public void setup() {
+ profilesDao = new ProfilesDao(getSession());
+ }
+
+ @Test
+ public void shouldGetProfiles() {
+ setupData("shouldGetProfiles");
+
+ List<RulesProfile> profiles = profilesDao.getProfiles("java");
+
+ assertThat(profiles.size(), is(2));
+ }
+
+ @Test
+ public void testGetActiveProfile() {
+ RulesProfile testDefaultProfile = new RulesProfile("default", "java", true, true);
+ RulesProfile testProfile = new RulesProfile("not default", "java", false, false);
+ getSession().save(testDefaultProfile, testProfile);
+
+ ResourceModel testResourceWithProfile = new ResourceModel(ResourceModel.SCOPE_PROJECT, "withProfile", "qual", null, "test");
+ testResourceWithProfile.setRulesProfile(testProfile);
+ ResourceModel testResourceWithNoProfile = new ResourceModel(ResourceModel.SCOPE_PROJECT, "withoutProfile", "qual", null, "test");
+ getSession().save(testResourceWithProfile, testResourceWithNoProfile);
+
+ assertNull(profilesDao.getActiveProfile("wrongLanguage", "withoutProfile"));
+ assertEquals(testDefaultProfile.getId(), profilesDao.getActiveProfile("java", "wrongKey").getId());
+ assertEquals(testDefaultProfile.getId(), profilesDao.getActiveProfile("java", "withoutProfile").getId());
+ assertEquals(testProfile.getId(), profilesDao.getActiveProfile("java", "withProfile").getId());
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dao/RulesDaoTest.java b/sonar-core/src/test/java/org/sonar/jpa/dao/RulesDaoTest.java
new file mode 100644
index 00000000000..30dc9fc0602
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dao/RulesDaoTest.java
@@ -0,0 +1,131 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dao;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rules.*;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+public class RulesDaoTest extends AbstractDbUnitTestCase {
+
+ private RulesDao rulesDao;
+
+ @Before
+ public void setup() {
+ rulesDao = new RulesDao(getSession());
+ }
+
+ @Test
+ public void shouldGetRules() {
+ setupData("shouldGetRules");
+
+ List<Rule> rules = rulesDao.getRules();
+ assertThat(rules, notNullValue());
+ assertThat(rules.size(), is(2));
+
+ assertEquals("rule_one", rules.get(0).getKey());
+ assertEquals(1, rules.get(0).getParams().size());
+ assertEquals("category one", rules.get(0).getRulesCategory().getName());
+ }
+
+ @Test
+ public void shouldGetRuleWithRuleKeyAndPluginKey() {
+ setupData("shouldGetRuleWithRuleKeyAndPluginKey");
+
+ Rule rule = rulesDao.getRuleByKey("plugin", "checkstyle.rule1");
+ assertThat(rule, notNullValue());
+ assertThat(rule.getId(), notNullValue());
+
+ Rule rule2 = rulesDao.getRuleByKey("plugin", "key not found");
+ assertThat(rule2, nullValue());
+ }
+
+ @Test
+ public void shouldCountNumberOfRulesOfACategoryForGivenPlugins() {
+ setupData("shouldCountNumberOfRulesOfACategoryForGivenPlugins");
+
+ Long result = rulesDao.countRules(Arrays.asList("plugin1", "plugin2"), "category one");
+ assertThat(result, is(3L));
+
+ result = rulesDao.countRules(Arrays.asList("plugin1", "plugin2"), "category two");
+ assertThat(result, is(1L));
+ }
+
+ @Test
+ public void shouldGetRuleParams() {
+ setupData("shouldGetRuleParams");
+
+ List<RuleParam> ruleParams = rulesDao.getRuleParams();
+
+ assertThat(ruleParams.size(), is(3));
+ }
+
+ @Test
+ public void shouldSynchronizeRuleOfActiveRule() {
+ setupData("shouldSynchronizeRuleOfActiveRule");
+ Rule rule = new Rule(null, "other key", (String) null, null, null);
+ RuleParam ruleParam = new RuleParam(null, "rule1_param1", null, null);
+ rule.setParams(Arrays.asList(ruleParam));
+ ActiveRule activeRule = new ActiveRule(null, rule, null);
+ ActiveRuleParam activeRuleParam = new ActiveRuleParam(activeRule, ruleParam, null);
+ activeRule.setActiveRuleParams(Arrays.asList(activeRuleParam));
+
+ rulesDao.synchronizeRuleOfActiveRule(activeRule, "plugin");
+
+ assertThat(activeRule.getRule().getId(), notNullValue());
+ assertThat(activeRule.getActiveRuleParams().size(), is(1));
+ }
+
+ @Test
+ public void shouldGetRulesProfileById() {
+ RulesProfile rulesProfile = new RulesProfile("profil", "java", true, true);
+ getSession().save(rulesProfile);
+
+ RulesProfile rulesProfileExpected = rulesDao.getProfileById(rulesProfile.getId());
+
+ assertThat(rulesProfileExpected, is(rulesProfile));
+ }
+
+ @Test
+ public void shouldAddActiveRulesToProfile() {
+ setupData("shouldAddActiveRulesToProfile");
+
+ Rule rule = new Rule("rule1", "key1", "config1", new RulesCategory("test"), null);
+ RuleParam ruleParam = new RuleParam(null, "param1", null, null);
+ rule.setParams(Arrays.asList(ruleParam));
+
+ ActiveRule activeRule = new ActiveRule(null, rule, RulePriority.MAJOR);
+ ActiveRuleParam activeRuleParam = new ActiveRuleParam(activeRule, ruleParam, "20");
+ activeRule.setActiveRuleParams(Arrays.asList(activeRuleParam));
+ rulesDao.addActiveRulesToProfile(Arrays.asList(activeRule), 1, "plugin");
+
+ checkTables("shouldAddActiveRulesToProfile", "rules", "active_rules", "rules_profiles");
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/DerbyTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/DerbyTest.java
new file mode 100644
index 00000000000..298f4775765
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/DerbyTest.java
@@ -0,0 +1,32 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+public class DerbyTest {
+ @Test
+ public void matchesJdbcURL() {
+ assertThat(new Derby().matchesJdbcURL("jdbc:derby:foo"), is(true));
+ assertThat(new Derby().matchesJdbcURL("jdbc:hsql:foo"), is(false));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/DialectRepositoryTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/DialectRepositoryTest.java
new file mode 100644
index 00000000000..0f7db36bd7a
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/DialectRepositoryTest.java
@@ -0,0 +1,70 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.sonar.api.database.DatabaseProperties;
+import org.sonar.api.utils.SonarException;
+
+public class DialectRepositoryTest {
+
+ @Test
+ public void testFindById() {
+ Dialect d = DialectRepository.find(DatabaseProperties.DIALECT_MYSQL, null);
+ assertEquals(MySql.class, d.getClass());
+ }
+
+ @Test
+ public void testFindByJdbcUrl() {
+ Dialect d = DialectRepository.find(null, "jdbc:mysql:foo:bar");
+ assertEquals(MySql.class, d.getClass());
+ }
+
+ @Test
+ public void testFindClassName() {
+ Dialect d = DialectRepository.find(TestDialect.class.getName(), null);
+ assertEquals(TestDialect.class, d.getClass());
+ }
+
+ @Test(expected=SonarException.class)
+ public void testFindNoMatch() {
+ DialectRepository.find("foo", "bar");
+ }
+
+ public static class TestDialect implements Dialect {
+ public boolean matchesJdbcURL(String jdbcConnectionURL) {
+ return false;
+ }
+
+ public String getId() {
+ return "testDialect";
+ }
+
+ public Class<? extends org.hibernate.dialect.Dialect> getHibernateDialectClass() {
+ return null;
+ }
+
+ public String getActiveRecordDialectCode() {
+ return null;
+ }
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/HsqlDbTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/HsqlDbTest.java
new file mode 100644
index 00000000000..20cebfd9eb7
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/HsqlDbTest.java
@@ -0,0 +1,32 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+public class HsqlDbTest {
+ @Test
+ public void matchesJdbcURL() {
+ assertThat(new HsqlDb().matchesJdbcURL("jdbc:hsqldb:hsql:foo"), is(true));
+ assertThat(new HsqlDb().matchesJdbcURL("jdbc:hsql:foo"), is(false));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/MsSqlTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/MsSqlTest.java
new file mode 100644
index 00000000000..5d2a9a53043
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/MsSqlTest.java
@@ -0,0 +1,37 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+public class MsSqlTest {
+
+ @Test
+ public void matchesJdbcURL() {
+ assertThat(new MsSql().matchesJdbcURL("jdbc:jtds:sqlserver://localhost;databaseName=SONAR;SelectMethod=Cursor"), is(true));
+ assertThat(new MsSql().matchesJdbcURL("jdbc:microsoft:sqlserver://localhost:1433;databasename=sonar"), is(true));
+
+ assertThat(new MsSql().matchesJdbcURL("jdbc:hsql:foo"), is(false));
+ assertThat(new MsSql().matchesJdbcURL("jdbc:mysql:foo"), is(false));
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/MySqlTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/MySqlTest.java
new file mode 100644
index 00000000000..ad60fa7e0a1
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/MySqlTest.java
@@ -0,0 +1,37 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+public class MySqlTest {
+
+ @Test
+ public void matchesJdbcURL() {
+ assertThat(new MySql().matchesJdbcURL("jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8"), is(true));
+ assertThat(new MySql().matchesJdbcURL("JDBC:MYSQL://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8"), is(true));
+
+ assertThat(new MySql().matchesJdbcURL("jdbc:hsql:foo"), is(false));
+ assertThat(new MySql().matchesJdbcURL("jdbc:oracle:foo"), is(false));
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/OracleSequenceGeneratorTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/OracleSequenceGeneratorTest.java
new file mode 100644
index 00000000000..ba15aa47854
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/OracleSequenceGeneratorTest.java
@@ -0,0 +1,43 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import org.hibernate.id.PersistentIdentifierGenerator;
+import org.junit.Test;
+
+import java.util.Properties;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class OracleSequenceGeneratorTest {
+
+ @Test
+ public void sequenceNameShouldFollowRailsConventions() {
+ Properties props = new Properties();
+ props.setProperty(PersistentIdentifierGenerator.TABLE, "my_table");
+ props.setProperty(PersistentIdentifierGenerator.PK, "id");
+
+ OracleSequenceGenerator generator = new OracleSequenceGenerator();
+ generator.configure(null, props, new Oracle.Oracle10gWithDecimalDialect());
+ assertThat(generator.getSequenceName(), is("MY_TABLE_SEQ"));
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/OracleTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/OracleTest.java
new file mode 100644
index 00000000000..89145bf7305
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/OracleTest.java
@@ -0,0 +1,32 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+public class OracleTest {
+ @Test
+ public void matchesJdbcURL() {
+ assertThat(new Oracle().matchesJdbcURL("jdbc:oracle:thin:@localhost/XE"), is(true));
+ assertThat(new Oracle().matchesJdbcURL("jdbc:hsql:foo"), is(false));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSQLSequenceGeneratorTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSQLSequenceGeneratorTest.java
new file mode 100644
index 00000000000..3738d30f56c
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSQLSequenceGeneratorTest.java
@@ -0,0 +1,43 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import org.hibernate.id.PersistentIdentifierGenerator;
+import org.junit.Test;
+
+import java.util.Properties;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class PostgreSQLSequenceGeneratorTest {
+
+ @Test
+ public void sequenceNameShouldFollowRailsConventions() {
+ Properties props = new Properties();
+ props.setProperty(PersistentIdentifierGenerator.TABLE, "my_table");
+ props.setProperty(PersistentIdentifierGenerator.PK, "id");
+
+ PostgreSQLSequenceGenerator generator = new PostgreSQLSequenceGenerator();
+ generator.configure(null, props, new PostgreSql.PostgreSQLWithDecimalDialect());
+ assertThat(generator.getSequenceName(), is("my_table_id_seq"));
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSqlTest.java b/sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSqlTest.java
new file mode 100644
index 00000000000..b16d92c5e4d
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/dialect/PostgreSqlTest.java
@@ -0,0 +1,33 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.dialect;
+
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class PostgreSqlTest {
+ @Test
+ public void matchesJdbcURL() {
+ assertThat(new PostgreSql().matchesJdbcURL("jdbc:postgresql://localhost/sonar"), is(true));
+ assertThat(new PostgreSql().matchesJdbcURL("jdbc:hsql:foo"), is(false));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/entity/PropertyTest.java b/sonar-core/src/test/java/org/sonar/jpa/entity/PropertyTest.java
new file mode 100644
index 00000000000..c948023d82a
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/entity/PropertyTest.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.entity;
+
+import org.junit.Test;
+import org.sonar.api.database.configuration.Property;
+
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+public class PropertyTest {
+
+ @Test
+ public void encodeBlob() {
+ Property prop = new Property("key1", "value1");
+ assertThat(prop.getValue(), is("value1"));
+
+ prop.setValue(null);
+ assertThat(prop.getValue(), nullValue());
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/entity/SchemaMigrationTest.java b/sonar-core/src/test/java/org/sonar/jpa/entity/SchemaMigrationTest.java
new file mode 100644
index 00000000000..8be589fb5b2
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/entity/SchemaMigrationTest.java
@@ -0,0 +1,65 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.entity;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.sonar.jpa.session.MemoryDatabaseConnector;
+
+import java.sql.Connection;
+
+import static org.junit.Assert.assertEquals;
+
+
+public class SchemaMigrationTest {
+
+ @Test
+ public void currentVersionShouldBeUnknownWhenSchemaIsEmpty() throws Exception {
+ MemoryDatabaseConnector connector = new MemoryDatabaseConnector(SchemaMigration.VERSION_UNKNOWN);
+ connector.start();
+
+ Connection connection = Mockito.mock(Connection.class);
+ try {
+ connection = connector.getConnection();
+ assertEquals(SchemaMigration.VERSION_UNKNOWN, SchemaMigration.getCurrentVersion(connection));
+ } finally {
+ if (connection != null) {
+ connection.close();
+ }
+ }
+ }
+
+ @Test
+ public void versionShouldBeLoadedFromSchemaMigrationsTable() throws Exception {
+ MemoryDatabaseConnector connector = new MemoryDatabaseConnector(30);
+ connector.start();
+
+ Connection connection = null;
+ try {
+ connection = connector.getConnection();
+ assertEquals(30, SchemaMigration.getCurrentVersion(connection));
+
+ } finally {
+ if (connection != null) {
+ connection.close();
+ }
+ }
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/session/AbstractDatabaseConnectorTest.java b/sonar-core/src/test/java/org/sonar/jpa/session/AbstractDatabaseConnectorTest.java
new file mode 100644
index 00000000000..5d5cc9cfc83
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/session/AbstractDatabaseConnectorTest.java
@@ -0,0 +1,114 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.session;
+
+import org.apache.commons.configuration.Configuration;
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.hamcrest.Matchers;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.sonar.api.database.DatabaseProperties;
+import org.sonar.jpa.dialect.HsqlDb;
+import org.sonar.jpa.dialect.Oracle;
+
+import javax.persistence.EntityManagerFactory;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.SQLException;
+import java.util.Properties;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+public class AbstractDatabaseConnectorTest {
+
+ @Test
+ public void autodetectDialectWhenNotExcplicitlyDefined() {
+ MemoryDatabaseConnector connector = new MemoryDatabaseConnector();
+ connector.start();
+ assertEquals(HsqlDb.class, connector.getDialect().getClass());
+ connector.stop();
+ }
+
+ @Test
+ public void useConfiguredDialectByDefault() {
+ Configuration conf = MemoryDatabaseConnector.getInMemoryConfiguration(false);
+ conf.setProperty(DatabaseProperties.PROP_DIALECT, DatabaseProperties.DIALECT_ORACLE);
+
+ TestDatabaseConnector connector = new TestDatabaseConnector(conf);
+ connector.start();
+ assertEquals(Oracle.class, connector.getDialect().getClass());
+ connector.stop();
+ }
+
+ @Test
+ public void getHibernateProperties() {
+ PropertiesConfiguration conf = new PropertiesConfiguration();
+ conf.setProperty("sonar.foo", "foo value");
+
+ // all properties prefixed by sonar.hibernate are propagated to hibernate configuration (the prefix "sonar." is removed)
+ conf.setProperty("sonar.hibernate.foo", "hibernate.foo value");
+
+ // hardcoded property. Should be replaced by sonar.hibernate.hbm2ddl.auto
+ conf.setProperty("sonar.jdbc.hibernate.hbm2ddl", "hibernate.hbm2ddl value");
+
+ // the dialect is mandatory if the JDBC url is not set
+ conf.setProperty("sonar.jdbc.dialect", DatabaseProperties.DIALECT_ORACLE);
+
+ AbstractDatabaseConnector connector = new TestDatabaseConnector(conf);
+ connector.start();
+
+ Properties hibernateProps = connector.getHibernateProperties();
+ assertThat(hibernateProps.getProperty("sonar.foo"), Matchers.nullValue()); // not an hibernate property
+ assertThat(hibernateProps.getProperty("hibernate.foo"), Matchers.is("hibernate.foo value"));
+ assertThat(hibernateProps.getProperty("hibernate.hbm2ddl.auto"), Matchers.is("hibernate.hbm2ddl value"));
+ assertThat(hibernateProps.getProperty("hibernate.dialect"), Matchers.is(Oracle.Oracle10gWithDecimalDialect.class.getName()));
+ }
+
+ private class TestDatabaseConnector extends AbstractDatabaseConnector {
+
+ public TestDatabaseConnector(Configuration configuration) {
+ super(configuration, false);
+ }
+
+ @Override
+ public void setupEntityManagerFactory(Properties factoryProps) {
+ }
+
+ @Override
+ protected boolean upToDateSchemaVersion() {
+ return true;
+ }
+
+ @Override
+ public EntityManagerFactory createEntityManagerFactory() {
+ return null;
+ }
+
+ public Connection getConnection() throws SQLException {
+ Connection c = Mockito.mock(Connection.class);
+ DatabaseMetaData m = Mockito.mock(DatabaseMetaData.class);
+ Mockito.when(c.getMetaData()).thenReturn(m);
+ return c;
+ }
+ }
+
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/session/DatabaseSessionTest.java b/sonar-core/src/test/java/org/sonar/jpa/session/DatabaseSessionTest.java
new file mode 100644
index 00000000000..6cc891f6cf8
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/session/DatabaseSessionTest.java
@@ -0,0 +1,120 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.session;
+
+import org.hamcrest.Matchers;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.internal.matchers.IsCollectionContaining;
+import org.sonar.api.database.model.MeasureModel;
+import org.sonar.api.database.model.ResourceModel;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.measures.Metric;
+import org.sonar.jpa.dao.MeasuresDao;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import javax.persistence.NonUniqueResultException;
+import java.sql.Date;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+public class DatabaseSessionTest extends AbstractDbUnitTestCase {
+ private static final Long NB_INSERTS = 20000l;
+
+ private ResourceModel project1;
+ private ResourceModel project2;
+
+ @Before
+ public void setup() {
+ project1 = new ResourceModel(ResourceModel.SCOPE_PROJECT, "mygroup:myartifact", "JAV", null, "my name");
+ project2 = new ResourceModel(ResourceModel.SCOPE_PROJECT, "mygroup:myartifact1", "JAV", null, "my name 2");
+ }
+
+ @Test
+ public void performaceTestOnBatchInserts() throws Exception {
+
+ Snapshot snapshot = new Snapshot(project1, true, "", new Date(1));
+ getSession().save(project1, snapshot);
+ getSession().commit();
+
+ Metric metric = new MeasuresDao(getSession()).getMetric("classes_count");
+ for (int i = 0; i < NB_INSERTS; i++) {
+ MeasureModel pm = new MeasureModel(metric, 1.0).setSnapshotId(snapshot.getId());
+ getSession().save(pm);
+ }
+
+ getSession().commit();
+ assertEquals(NB_INSERTS, getHQLCount(MeasureModel.class));
+
+ }
+
+ @Test
+ public void testGetSingleResultWithNoResults() {
+ assertNull(getSession().getSingleResult(ResourceModel.class, "name", "test"));
+ }
+
+ @Test
+ public void testGetSingleResultWithNoCriterias() {
+ try {
+ assertNull(getSession().getSingleResult(ResourceModel.class, (Object[]) null));
+ fail("No IllegalStateException raised");
+ } catch (IllegalStateException ex) {
+ // error raised correctly
+ }
+ }
+
+ @Test
+ public void testGetSingleResultWithOneResult() {
+ getSession().save(project1);
+ ResourceModel hit = getSession().getSingleResult(ResourceModel.class, "name", "my name");
+ assertNotNull(hit);
+ assertEquals(project1, hit);
+ }
+
+ @Test
+ public void testGetSingleResultWithTwoResults() {
+ getSession().save(project1, project2);
+ try {
+ getSession().getSingleResult(ResourceModel.class, "qualifier", "JAV");
+ fail("No NonUniqueResultException raised");
+ } catch (NonUniqueResultException ex) {
+ // error raised correctly
+ }
+ }
+
+ @Test
+ public void testGetResultsWithNoResults() {
+ List<ResourceModel> hits = getSession().getResults(ResourceModel.class, "name", "foo");
+ assertTrue(hits.isEmpty());
+ }
+
+ @Test
+ public void testGetResultsWithMultipleResults() {
+ ResourceModel project3 = new ResourceModel(ResourceModel.SCOPE_PROJECT, "mygroup:myartifact3", "TEST", null, "my name 3");
+ getSession().save(project1, project2, project3);
+
+ List<ResourceModel> hits = getSession().getResults(ResourceModel.class, "qualifier", "JAV");
+ assertFalse(hits.isEmpty());
+ assertThat(hits, IsCollectionContaining.hasItems(project1, project2));
+ assertThat(hits, Matchers.not(IsCollectionContaining.hasItem(project3)));
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/session/DriverDatabaseConnectorTest.java b/sonar-core/src/test/java/org/sonar/jpa/session/DriverDatabaseConnectorTest.java
new file mode 100644
index 00000000000..f133296d10f
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/session/DriverDatabaseConnectorTest.java
@@ -0,0 +1,92 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.session;
+
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.hamcrest.Matchers;
+import org.junit.After;
+import org.junit.Test;
+import org.sonar.api.database.DatabaseProperties;
+
+import java.sql.SQLException;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.*;
+
+public class DriverDatabaseConnectorTest {
+
+ private DriverDatabaseConnector connector = null;
+
+ @After
+ public void stop() {
+ if (connector != null) {
+ connector.stop();
+ }
+ }
+
+ @Test(expected = DatabaseException.class)
+ public void failsIfUnvalidConfiguration() throws SQLException {
+ PropertiesConfiguration conf = new PropertiesConfiguration();
+ conf.setProperty(DatabaseProperties.PROP_URL, "jdbc:foo:bar//xxx");
+ conf.setProperty(DatabaseProperties.PROP_DRIVER, MemoryDatabaseConnector.DRIVER);
+ conf.setProperty(DatabaseProperties.PROP_USER, "sa");
+ conf.setProperty(DatabaseProperties.PROP_PASSWORD, null);
+ connector = new DriverDatabaseConnector(conf);
+ try {
+ connector.start();
+ } finally {
+ assertFalse(connector.isStarted());
+ assertFalse(connector.isOperational());
+ }
+ }
+
+ @Test(expected = DatabaseException.class)
+ public void failsIfSchemaIsNotCreated() {
+ connector = new DriverDatabaseConnector(MemoryDatabaseConnector.getInMemoryConfiguration(false));
+ try {
+ connector.start();
+ } finally {
+ assertTrue(connector.isStarted());
+ assertFalse(connector.isOperational());
+ }
+ }
+
+ @Test(expected = DatabaseException.class)
+ public void failsIfUpToDateSchema() {
+ connector = new DriverDatabaseConnector(MemoryDatabaseConnector.getInMemoryConfiguration(true));
+ try {
+ connector.start();
+ } finally {
+ assertTrue(connector.isStarted());
+ assertFalse(connector.isOperational());
+ }
+ }
+
+ @Test
+ public void deprecatedParametersAreStillValid() {
+ PropertiesConfiguration conf = new PropertiesConfiguration();
+ conf.setProperty(DatabaseProperties.PROP_DRIVER_DEPRECATED, MemoryDatabaseConnector.DRIVER);
+ conf.setProperty(DatabaseProperties.PROP_USER_DEPRECATED, "freddy");
+ connector = new DriverDatabaseConnector(conf);
+
+ assertThat(connector.getDriver(), is(MemoryDatabaseConnector.DRIVER));
+ assertThat(connector.getUsername(), Matchers.is("freddy"));
+ }
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/session/ThreadLocalDatabaseSessionFactoryTest.java b/sonar-core/src/test/java/org/sonar/jpa/session/ThreadLocalDatabaseSessionFactoryTest.java
new file mode 100644
index 00000000000..7f1c2eb5c3b
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/session/ThreadLocalDatabaseSessionFactoryTest.java
@@ -0,0 +1,49 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.session;
+
+import org.junit.Test;
+import org.sonar.api.database.DatabaseSession;
+
+import static org.junit.Assert.assertTrue;
+
+public class ThreadLocalDatabaseSessionFactoryTest {
+
+
+ @Test
+ public void shouldCreateOneSessionPerThread() {
+ final MemoryDatabaseConnector connector = new MemoryDatabaseConnector();
+ connector.start();
+ final DatabaseSessionFactory factory = new ThreadLocalDatabaseSessionFactory(connector);
+
+ final DatabaseSession junitThreadSession = factory.getSession();
+ assertTrue(junitThreadSession == factory.getSession());
+
+ new Thread() {
+ @Override
+ public void run() {
+ DatabaseSession threadSession = factory.getSession();
+ assertTrue(threadSession != junitThreadSession);
+ }
+
+ }.start();
+ }
+
+}
diff --git a/sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java b/sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java
new file mode 100644
index 00000000000..0f4eb82793d
--- /dev/null
+++ b/sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java
@@ -0,0 +1,247 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.jpa.test;
+
+import org.apache.commons.io.IOUtils;
+import org.dbunit.Assertion;
+import org.dbunit.DatabaseUnitException;
+import org.dbunit.IDatabaseTester;
+import org.dbunit.JdbcDatabaseTester;
+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.ReplacementDataSet;
+import org.dbunit.dataset.xml.FlatXmlDataSet;
+import org.dbunit.ext.hsqldb.HsqldbDataTypeFactory;
+import org.dbunit.operation.DatabaseOperation;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.jpa.session.DatabaseSessionFactory;
+import org.sonar.jpa.dao.*;
+import org.sonar.jpa.session.JpaDatabaseSession;
+import org.sonar.jpa.session.MemoryDatabaseConnector;
+
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.sql.SQLException;
+
+import static org.junit.Assert.fail;
+
+public abstract class AbstractDbUnitTestCase {
+
+ private MemoryDatabaseConnector dbConnector;
+ private JpaDatabaseSession session;
+ private DaoFacade dao;
+ protected IDatabaseTester databaseTester;
+ protected IDatabaseConnection connection;
+
+ @Before
+ public final void startDatabase() throws Exception {
+ if (dbConnector == null) {
+ dbConnector = new MemoryDatabaseConnector();
+ dbConnector.start();
+ session = new JpaDatabaseSession(dbConnector);
+ session.start();
+ }
+
+ databaseTester = new JdbcDatabaseTester(MemoryDatabaseConnector.DRIVER, MemoryDatabaseConnector.URL, MemoryDatabaseConnector.USER,
+ MemoryDatabaseConnector.PASSWORD);
+ databaseTester.onTearDown();
+ }
+
+ @After
+ public final void stopDatabase() {
+ if (dbConnector != null) {
+ dbConnector.stop();
+ session.stop();
+ }
+ }
+
+ public DaoFacade getDao() {
+ if (dao == null) {
+ dao = new DaoFacade(new ProfilesDao(session), new RulesDao(session), new MeasuresDao(session), new AsyncMeasuresDao(session));
+ }
+ return dao;
+ }
+
+ public DatabaseSession getSession() {
+ return session;
+ }
+
+ public DatabaseSessionFactory getSessionFactory() {
+ return new DatabaseSessionFactory() {
+
+ public DatabaseSession getSession() {
+ return session;
+ }
+
+ public void clear() {
+ }
+ };
+ }
+
+ protected final void setupData(String... testNames) {
+ InputStream[] streams = new InputStream[testNames.length];
+ try {
+ 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(streams);
+
+ } finally {
+ for (InputStream stream : streams) {
+ IOUtils.closeQuietly(stream);
+ }
+ }
+ }
+
+ protected final void setupData(InputStream... dataSetStream) {
+ 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;
+ }
+ CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets);
+
+ databaseTester.setDataSet(compositeDataSet);
+ connection = databaseTester.getConnection();
+ connection.getConnection().prepareStatement("set referential_integrity FALSE").execute(); // HSQL DB
+ DatabaseConfig config = connection.getConfig();
+ config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());
+
+ DatabaseOperation.CLEAN_INSERT.execute(connection, databaseTester.getDataSet());
+
+ connection.getConnection().prepareStatement("set referential_integrity TRUE").execute(); // HSQL DB
+ } catch (Exception e) {
+ throw translateException("Could not setup DBUnit data", e);
+ }
+ }
+
+ protected final void checkTables(String testName, String... tables) {
+ getSession().commit();
+ try {
+ IDataSet dataSet = getCurrentDataSet();
+ IDataSet expectedDataSet = getExpectedData(testName);
+ for (String table : tables) {
+ Assertion.assertEquals(expectedDataSet.getTable(table), dataSet.getTable(table));
+ }
+ } catch (DataSetException e) {
+ throw translateException("Error while checking results", e);
+ } catch (DatabaseUnitException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ protected final void assertEmptyTables(String... emptyTables) {
+ for (String table : emptyTables) {
+ try {
+ Assert.assertEquals(0, getCurrentDataSet().getTable(table).getRowCount());
+ } catch (DataSetException e) {
+ throw translateException("Error while checking results", e);
+ }
+ }
+ }
+
+ protected final IDataSet getExpectedData(String testName) {
+ String className = getClass().getName();
+ className = String.format("/%s/%s-result.xml", className.replace(".", "/"), testName);
+
+ InputStream in = getClass().getResourceAsStream(className);
+ try {
+ return getData(in);
+ } finally {
+ IOUtils.closeQuietly(in);
+ }
+ }
+
+ protected final IDataSet getData(InputStream stream) {
+ try {
+ ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(stream));
+ dataSet.addReplacementObject("[null]", null);
+ return dataSet;
+ } catch (Exception e) {
+ throw translateException("Could not read the dataset stream", e);
+ }
+ }
+
+ protected final IDataSet getCurrentDataSet() {
+ try {
+ return connection.createDataSet();
+ } catch (SQLException e) {
+ throw translateException("Could not create the current dataset", e);
+ }
+ }
+
+ protected String getCurrentDataSetAsXML() {
+ return getDataSetAsXML(getCurrentDataSet());
+ }
+
+ protected String getDataSetAsXML(IDataSet dataset) {
+ try {
+ StringWriter writer = new StringWriter();
+ FlatXmlDataSet.write(dataset, writer);
+ return writer.getBuffer().toString();
+ } catch (Exception e) {
+ throw translateException("Could not build XML from 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;
+ }
+
+ /*public static class HsqlDataTypeFactory extends DefaultDataTypeFactory {
+
+ public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException {
+ if (sqlType == Types.BOOLEAN) {
+ return DataType.BOOLEAN;
+ }
+ return super.createDataType(sqlType, sqlTypeName);
+ }
+ }*/
+
+ protected Long getHQLCount(final Class<?> hqlClass) {
+ String hqlCount = "SELECT count(o) from " + hqlClass.getSimpleName() + " o";
+ return (Long) getSession().createQuery(hqlCount).getSingleResult();
+ }
+
+ protected IDatabaseConnection getConnection() {
+ return connection;
+ }
+
+ protected IDatabaseTester getDatabaseTester() {
+ return databaseTester;
+ }
+
+}