aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-batch/src/test/java/org/sonar/batch
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-batch/src/test/java/org/sonar/batch
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-batch/src/test/java/org/sonar/batch')
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/CoreJobsTest.java29
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/DecoratorsSelectorTest.java114
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/DefaultSensorContextTest.java244
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/DefaultTimeMachineTest.java108
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/FinalizeSnapshotsJobTest.java78
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/MavenPhaseExecutorTest.java58
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/MavenPluginsConfiguratorTest.java77
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/PostJobsExecutorTest.java66
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/ProfileProviderTest.java95
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/ProjectBuilderTest.java210
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/ProjectConfigurationTest.java117
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/ProjectTreeTest.java209
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/RemoteClassLoaderTest.java43
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/ServerMetadataTest.java61
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/ViolationFiltersTest.java68
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultPersisterTest.java61
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultSonarIndexTest.java56
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/indexer/LibraryPersisterTest.java94
-rw-r--r--sonar-batch/src/test/java/org/sonar/batch/indexer/ResourcePersistersTest.java67
19 files changed, 1855 insertions, 0 deletions
diff --git a/sonar-batch/src/test/java/org/sonar/batch/CoreJobsTest.java b/sonar-batch/src/test/java/org/sonar/batch/CoreJobsTest.java
new file mode 100644
index 00000000000..25c2e046e47
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/CoreJobsTest.java
@@ -0,0 +1,29 @@
+package org.sonar.batch;
+
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+import java.util.List;
+
+public class CoreJobsTest {
+
+ @Test
+ public void mavenPluginsAreExecutedAfterBeingConfigured() {
+ List<Class<? extends CoreJob>> jobs = CoreJobs.allJobs();
+ assertThat(jobs.indexOf(FinalizeSnapshotsJob.class),
+ greaterThan(jobs.indexOf(DecoratorsExecutor.class)));
+ }
+
+ @Test
+ public void finalizeJobIsExecutedAfterDecorators() {
+ List<Class<? extends CoreJob>> jobs = CoreJobs.allJobs();
+ assertThat(jobs.indexOf(FinalizeSnapshotsJob.class),
+ greaterThan(jobs.indexOf(DecoratorsExecutor.class)));
+ }
+
+ @Test
+ public void allJobs() {
+ assertThat(CoreJobs.allJobs().size(), greaterThan(3));
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/DecoratorsSelectorTest.java b/sonar-batch/src/test/java/org/sonar/batch/DecoratorsSelectorTest.java
new file mode 100644
index 00000000000..90edc924f10
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/DecoratorsSelectorTest.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.batch;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+import static org.junit.internal.matchers.IsCollectionContaining.hasItem;
+import static org.mockito.Mockito.mock;
+import org.picocontainer.containers.TransientPicoContainer;
+import org.sonar.api.batch.*;
+import org.sonar.api.measures.*;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.Resource;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+public class DecoratorsSelectorTest {
+
+ private Metric withFormula1 = new Metric("metric1").setFormula(new FakeFormula());
+ private Metric withFormula2 = new Metric("metric2").setFormula(new FakeFormula());
+ private Metric withoutFormula = new Metric("metric3");
+
+ @Test
+ public void selectAndSortFormulas() {
+ Project project = new Project("key");
+ BatchExtensionDictionnary dictionnary = newDictionnary(withFormula1, withoutFormula, withFormula2);
+
+ Collection<Decorator> decorators = new DecoratorsSelector(dictionnary).select(project);
+ assertThat(decorators.size(), is(2));
+ assertThat(decorators, hasItem((Decorator) new FormulaDecorator(withFormula1)));
+ assertThat(decorators, hasItem((Decorator) new FormulaDecorator(withFormula2)));
+ }
+
+ @Test
+ public void pluginDecoratorsCanOverrideFormulas() {
+ Project project = new Project("key");
+ Decorator fakeDecorator = new FakeDecorator();
+ Decorator metric1Decorator = new Metric1Decorator();
+ BatchExtensionDictionnary dictionnary = newDictionnary(fakeDecorator, metric1Decorator, withFormula1, withoutFormula, withFormula2);
+
+ Collection<Decorator> decorators = new DecoratorsSelector(dictionnary).select(project);
+
+ assertThat(decorators.size(), is(3));
+ assertThat(decorators, hasItem(fakeDecorator));
+ assertThat(decorators, hasItem(metric1Decorator));
+ assertThat(decorators, hasItem((Decorator) new FormulaDecorator(withFormula2)));
+ }
+
+ private BatchExtensionDictionnary newDictionnary(Object... extensions) {
+ TransientPicoContainer ioc = new TransientPicoContainer();
+ int index = 0;
+ for (Object extension : extensions) {
+ ioc.addComponent("" + index, extension);
+ index++;
+ }
+ return new BatchExtensionDictionnary(ioc);
+ }
+
+
+ class FakeFormula implements Formula {
+ public List<Metric> dependsUponMetrics() {
+ return Arrays.asList();
+ }
+
+ public Measure calculate(FormulaData data, FormulaContext context) {
+ return null;
+ }
+ }
+
+ public class Metric1Decorator implements Decorator {
+ @DependedUpon
+ public Metric generatesMetric1Measure() {
+ return withFormula1;
+ }
+
+ public void decorate(Resource resource, DecoratorContext context) {
+
+ }
+
+ public boolean shouldExecuteOnProject(Project project) {
+ return true;
+ }
+ }
+
+ public class FakeDecorator implements Decorator {
+ public void decorate(Resource resource, DecoratorContext context) {
+
+ }
+
+ public boolean shouldExecuteOnProject(Project project) {
+ return true;
+ }
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/DefaultSensorContextTest.java b/sonar-batch/src/test/java/org/sonar/batch/DefaultSensorContextTest.java
new file mode 100644
index 00000000000..dba2db3e375
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/DefaultSensorContextTest.java
@@ -0,0 +1,244 @@
+/*
+ * 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.batch;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.design.Dependency;
+import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.measures.PersistenceMode;
+import org.sonar.api.measures.RuleMeasure;
+import org.sonar.api.resources.JavaFile;
+import org.sonar.api.resources.JavaPackage;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.Resource;
+import org.sonar.api.rules.RulePriority;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import javax.persistence.Query;
+import java.text.ParseException;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.assertThat;
+
+@Ignore
+public class DefaultSensorContextTest extends AbstractDbUnitTestCase {
+ private DefaultSensorContext context;
+ private Project project;
+
+ @Before
+ public void before() {
+ project = null;
+ context = null;
+ }
+
+ @Test
+ public void saveProjectMeasure() throws ParseException {
+ setup("saveProjectMeasure");
+ context.saveMeasure(CoreMetrics.NCLOC, 500.0);
+ check("saveProjectMeasure", "projects", "snapshots", "project_measures");
+ }
+
+ @Test
+ public void saveMeasureOnExistingResource() throws ParseException {
+ setup("saveMeasureOnExistingResource");
+ context.saveMeasure(new JavaPackage("org.sonar"), CoreMetrics.NCLOC, 200.0);
+ check("saveMeasureOnExistingResource", "projects", "snapshots", "project_measures");
+ }
+
+ @Test
+ public void avoidConflictWithResourceFromOtherProject() throws ParseException {
+ setup("avoidConflictWithResourceFromOtherProject");
+ context.saveMeasure(new JavaPackage("org.sonar"), CoreMetrics.NCLOC, 200.0);
+ context.saveMeasure(new JavaPackage("org.sonar"), CoreMetrics.COVERAGE, 80.0);
+ check("avoidConflictWithResourceFromOtherProject", "projects", "snapshots", "project_measures");
+ }
+
+ @Test
+ public void doNotPersistInMemoryMeasures() throws ParseException {
+ setup("doNotPersistInMemoryMeasures");
+ Measure measure = new Measure(CoreMetrics.NCLOC, 30.0).setPersistenceMode(PersistenceMode.MEMORY);
+ context.saveMeasure(measure);
+
+ check("doNotPersistInMemoryMeasures", "projects", "snapshots", "project_measures");
+ assertThat(context.getMeasure(CoreMetrics.NCLOC).getValue(), is(30.0));
+ }
+
+ @Test
+ public void doNotCacheDatabaseMeasures() throws ParseException {
+ setup("doNotCacheDatabaseMeasures");
+ Measure measure = new Measure(CoreMetrics.NCLOC, 500.0).setPersistenceMode(PersistenceMode.DATABASE);
+ context.saveMeasure(measure);
+
+ check("doNotCacheDatabaseMeasures", "projects", "snapshots", "project_measures");
+ assertThat(context.getMeasure(CoreMetrics.NCLOC), nullValue());
+ }
+
+ @Test
+ public void saveRuleMeasures() throws ParseException {
+ setup("saveRuleMeasures");
+ context.saveMeasure(RuleMeasure.createForPriority(CoreMetrics.VIOLATIONS, RulePriority.CRITICAL, 500.0));
+ context.saveMeasure(RuleMeasure.createForCategory(CoreMetrics.VIOLATIONS, 3, 200.0));
+ //FIXME context.saveMeasure(RuleMeasure.createForRule(CoreMetrics.VIOLATIONS, 3).setIntValue(50.0));
+ check("saveRuleMeasures", "projects", "snapshots", "project_measures");
+ }
+
+ @Test
+ public void saveResourceTree() throws ParseException {
+// setup("saveResourceTree");
+//
+// assertThat(context.getResource("org.foo.Bar"), nullValue());
+// context.saveResource(new JavaFile("org.foo.Bar"));
+// assertThat(context.getResource("org.foo.Bar"), is((Resource) new JavaFile("org.foo.Bar")));
+//
+// check("saveResourceTree", "projects", "snapshots");
+ }
+//
+// @Test
+// public void doNotSaveExcludedResources() throws ParseException {
+// setup("doNotSaveExcludedResources");
+//
+// JavaFile javaFile = new JavaFile("org.excluded.Bar");
+// ResourceFilters resourceFilters = mock(ResourceFilters.class);
+// when(resourceFilters.isExcluded(javaFile)).thenReturn(true);
+// context.setResourceFilters(resourceFilters);
+//
+// assertThat(context.getResource("org.excluded.Bar"), nullValue());
+// assertThat(context.saveResource(javaFile), nullValue());
+// assertThat(context.getResource("org.excluded.Bar"), nullValue());
+//
+// check("doNotSaveExcludedResources", "projects", "snapshots");
+// }
+
+ @Test
+ public void updateExistingResourceFields() throws ParseException {
+ setup("updateExistingResourceFields");
+
+ context.saveResource(new JavaPackage("org.foo"));
+
+ check("updateExistingResourceFields", "projects", "snapshots");
+ }
+
+ @Test
+ public void doNotSaveOptimizedBestValues() throws ParseException {
+ setup("doNotSaveOptimizedBestValues");
+
+ // best values of the metrics violations and blocker_violations are set as optimized
+ assertThat(CoreMetrics.VIOLATIONS.getBestValue(), is(0.0));
+ assertThat(CoreMetrics.BLOCKER_VIOLATIONS.getBestValue(), is(0.0));
+ assertThat(CoreMetrics.VIOLATIONS.isOptimizedBestValue(), is(true));
+ assertThat(CoreMetrics.BLOCKER_VIOLATIONS.isOptimizedBestValue(), is(true));
+
+ final Resource javaFile = new JavaFile("org.foo.Bar");
+ assertThat(context.getMeasure(javaFile, CoreMetrics.VIOLATIONS), nullValue());
+ context.saveMeasure(javaFile, CoreMetrics.VIOLATIONS, 60.0); // saved
+ assertThat(context.getMeasure(javaFile, CoreMetrics.VIOLATIONS).getValue(), is(60.0));
+
+ assertThat(context.getMeasure(javaFile, CoreMetrics.BLOCKER_VIOLATIONS), nullValue());
+ context.saveMeasure(javaFile, CoreMetrics.BLOCKER_VIOLATIONS, 0.0); // not saved in database
+ assertThat(context.getMeasure(javaFile, CoreMetrics.BLOCKER_VIOLATIONS).getValue(), is(0.0));
+
+ check("doNotSaveOptimizedBestValues", "projects", "snapshots", "project_measures");
+ }
+
+ @Test
+ public void saveOptimizedBestValuesIfOptionalFields() throws ParseException {
+ setup("saveOptimizedBestValuesIfOptionalFields");
+
+ // best value of the metric violations is set as optimized
+ assertThat(CoreMetrics.VIOLATIONS.getBestValue(), is(0.0));
+ assertThat(CoreMetrics.VIOLATIONS.isOptimizedBestValue(), is(true));
+
+ final Resource javaFile = new JavaFile("org.foo.Bar");
+ assertThat(context.getMeasure(javaFile, CoreMetrics.VIOLATIONS), nullValue());
+ Measure measure = new Measure(CoreMetrics.VIOLATIONS, 0.0).setTendency(1);
+
+ context.saveMeasure(javaFile, measure); // saved
+
+ assertThat(context.getMeasure(javaFile, CoreMetrics.VIOLATIONS).getValue(), is(0.0));
+ assertThat(context.getMeasure(javaFile, CoreMetrics.VIOLATIONS).getTendency(), is(1));
+
+ check("saveOptimizedBestValuesIfOptionalFields", "projects", "snapshots", "project_measures");
+ }
+
+
+ @Test
+ public void saveDependency() throws ParseException {
+ setup("saveDependency");
+
+ JavaPackage pac1 = new JavaPackage("org.sonar.source");
+ JavaPackage pac2 = new JavaPackage("org.sonar.target");
+ context.saveResource(pac1);
+ context.saveResource(pac2);
+
+ Dependency dep = new Dependency(pac1, pac2)
+ .setUsage("INHERITS")
+ .setWeight(3);
+ context.saveDependency(dep);
+
+ assertThat(dep.getId(), not(nullValue()));
+
+ check("saveDependency", "projects", "snapshots", "dependencies");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void saveResourcesBeforeBuildingDependencies() throws ParseException {
+ setup("saveResourcesBeforeBuildingDependencies");
+
+ JavaPackage pac1 = new JavaPackage("org.sonar.source");
+ JavaPackage pac2 = new JavaPackage("org.sonar.target");
+ context.saveDependency(new Dependency(pac1, pac2));
+ }
+
+
+ private void setup(String unitTest) throws ParseException {
+// setupData(unitTest);
+// project = mock(Project.class);
+// when(project.getAnalysisVersion()).thenReturn("1.0");
+// when(project.getAnalysisDate()).thenReturn(new SimpleDateFormat("yyyy-MM-dd").parse("2008-12-25"));
+// when(project.getKey()).thenReturn("group:artifact");
+// when(project.getScope()).thenReturn(Resource.SCOPE_SET);
+// when(project.getQualifier()).thenReturn(Resource.QUALIFIER_PROJECT);
+// when(project.getLanguage()).thenReturn(Java.INSTANCE);
+// when(project.getId()).thenReturn(10);
+// when(project.getName()).thenReturn("my project");
+// when(project.isRoot()).thenReturn(true);
+// ProjectBootstrap projectBootstrap = new ProjectBootstrap(null);
+// projectBootstrap.setProject(project);
+// projectBootstrap.setSnapshot(getSnapshot(1));
+// context = new DefaultSensorContext(getSession(), projectBootstrap.setProject(project), getDao().getMeasuresDao(), null, null, null);
+ }
+
+ private void check(String unitTest, String... tables) {
+ getSession().commit();
+ checkTables(unitTest, tables);
+ }
+
+ private Snapshot getSnapshot(int id) {
+ Query query = getSession().createQuery("SELECT s FROM Snapshot s WHERE s.id=:id");
+ query.setParameter("id", id);
+ return (Snapshot) query.getSingleResult();
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/DefaultTimeMachineTest.java b/sonar-batch/src/test/java/org/sonar/batch/DefaultTimeMachineTest.java
new file mode 100644
index 00000000000..8e097ddccc3
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/DefaultTimeMachineTest.java
@@ -0,0 +1,108 @@
+/*
+ * 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.batch;
+
+import org.junit.Test;
+import org.sonar.api.batch.TimeMachineQuery;
+import org.sonar.jpa.dao.MeasuresDao;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.Resource;
+import org.sonar.batch.indexer.DefaultSonarIndex;
+
+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.hamcrest.number.OrderingComparisons.greaterThan;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class DefaultTimeMachineTest extends AbstractDbUnitTestCase {
+
+ @Test(timeout = 3000)
+ public void loadMeasureFieldsFromDate() throws ParseException {
+ setupData("loadMeasuresFromDate");
+ DefaultTimeMachine timeMachine = initTimeMachine();
+
+ TimeMachineQuery query = new TimeMachineQuery(null).setFrom(date("2008-02-01")).setMetrics(Arrays.asList(CoreMetrics.NCLOC));
+ List<Object[]> measures = timeMachine.getMeasuresFields(query);
+
+ assertThat(measures.size(), is(3));
+ for (Object[] measure : measures) {
+ assertThat(measure.length, is(3)); // 3 fields
+ assertThat(measure[1], is((Object) CoreMetrics.NCLOC));
+ }
+ assertThat(measures.get(0)[2], is((Object) 200d));
+ assertThat(measures.get(1)[2], is((Object) 230d));
+ assertThat(measures.get(2)[2], is((Object) 180d));
+ }
+
+ private DefaultTimeMachine initTimeMachine() {
+ DefaultSonarIndex index = mock(DefaultSonarIndex.class);
+ when(index.getResource((Resource) anyObject())).thenReturn(new Project("group:artifact").setId(1));
+ DefaultTimeMachine timeMachine = new DefaultTimeMachine(getSession(), index, new MeasuresDao(getSession()));
+ return timeMachine;
+ }
+
+ @Test(timeout = 3000)
+ public void loadMeasuresFromDate() throws ParseException {
+ setupData("loadMeasuresFromDate");
+ DefaultTimeMachine timeMachine = initTimeMachine();
+
+
+ TimeMachineQuery query = new TimeMachineQuery(null).setFrom(date("2008-02-01")).setMetrics(Arrays.asList(CoreMetrics.NCLOC));
+ List<Measure> measures = timeMachine.getMeasures(query);
+
+ assertThat(measures.size(), is(3));
+ long previous = 0;
+ for (Measure measure : measures) {
+ assertThat(measure.getMetric(), is(CoreMetrics.NCLOC));
+ assertThat(measure.getDate().getTime(), greaterThan(previous));
+ previous = measure.getDate().getTime();
+ }
+ assertThat(measures.get(0).getValue(), is(200d));
+ assertThat(measures.get(1).getValue(), is(230d));
+ assertThat(measures.get(2).getValue(), is(180d));
+ }
+
+ @Test(timeout = 3000)
+ public void loadMeasuresFromDateInterval() throws ParseException {
+ setupData("loadMeasuresFromDate");
+ DefaultTimeMachine timeMachine = initTimeMachine();
+
+
+ TimeMachineQuery query = new TimeMachineQuery(null).setFrom(date("2008-01-01")).setTo(date("2008-12-25")).setMetrics(Arrays.asList(CoreMetrics.NCLOC));
+ List<Measure> measures = timeMachine.getMeasures(query);
+ assertThat(measures.size(), is(1));
+ assertThat(measures.get(0).getValue(), is(200d));
+ }
+
+ private Date date(String date) throws ParseException {
+ return new SimpleDateFormat("yyyy-MM-dd").parse(date);
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/FinalizeSnapshotsJobTest.java b/sonar-batch/src/test/java/org/sonar/batch/FinalizeSnapshotsJobTest.java
new file mode 100644
index 00000000000..9158839ea1a
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/FinalizeSnapshotsJobTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.batch;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.api.batch.Purge;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Project;
+import org.sonar.core.purge.DefaultPurgeContext;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import javax.persistence.Query;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+public class FinalizeSnapshotsJobTest extends AbstractDbUnitTestCase {
+
+ private Purge purgeMock=null;
+
+ @Before
+ public void before() {
+ purgeMock = mock(Purge.class);
+ }
+
+ @Test
+ public void shouldUnflagPenultimateLastSnapshot() throws Exception {
+ assertAnalysis(11, "shouldUnflagPenultimateLastSnapshot");
+ verify(purgeMock).purge(new DefaultPurgeContext(11, 1));
+ }
+
+ @Test
+ public void doNotFailIfNoPenultimateLast() throws Exception {
+ assertAnalysis(5, "doNotFailIfNoPenultimateLast");
+ verify(purgeMock).purge(new DefaultPurgeContext(5, null));
+ }
+
+ @Test
+ public void lastSnapshotIsNotUpdatedWhenAnalyzingPastSnapshot() {
+ assertAnalysis(6, "lastSnapshotIsNotUpdatedWhenAnalyzingPastSnapshot");
+ verify(purgeMock).purge(new DefaultPurgeContext(6, null));
+ }
+
+ private void assertAnalysis(int snapshotId, String fixture) {
+ setupData("sharedFixture", fixture);
+
+ FinalizeSnapshotsJob sensor = new FinalizeSnapshotsJob(mock(ServerMetadata.class), getSession(), new Purge[]{purgeMock}, loadSnapshot(snapshotId));
+ sensor.execute(new Project("key"), null);
+
+ getSession().stop();
+ checkTables(fixture, "snapshots");
+ }
+
+
+ private Snapshot loadSnapshot(int id) {
+ Query query = getSession().createQuery("SELECT s FROM Snapshot s WHERE s.id=:id");
+ query.setParameter("id", id);
+ return (Snapshot) query.getSingleResult();
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/MavenPhaseExecutorTest.java b/sonar-batch/src/test/java/org/sonar/batch/MavenPhaseExecutorTest.java
new file mode 100644
index 00000000000..77d1e333e9c
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/MavenPhaseExecutorTest.java
@@ -0,0 +1,58 @@
+/*
+ * 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.batch;
+
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.junit.Test;
+import org.sonar.api.batch.SensorContext;
+import org.sonar.api.resources.Project;
+
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.*;
+
+public class MavenPhaseExecutorTest {
+
+ @Test
+ public void doNothingIfNoPhase() {
+ MavenPluginExecutor mavenPluginExecutor = mock(MavenPluginExecutor.class);
+ MavenPhaseExecutor phaseExecutor = new MavenPhaseExecutor(mavenPluginExecutor);
+
+
+ Project project = new Project("key");
+ phaseExecutor.execute(project, mock(SensorContext.class));
+
+ verify(mavenPluginExecutor, never()).execute(eq(project), anyString());
+ }
+
+ @Test
+ public void executePhase() {
+ MavenPluginExecutor mavenPluginExecutor = mock(MavenPluginExecutor.class);
+ MavenPhaseExecutor phaseExecutor = new MavenPhaseExecutor(mavenPluginExecutor);
+
+ Project project = new Project("key");
+ PropertiesConfiguration conf = new PropertiesConfiguration();
+ conf.setProperty(MavenPhaseExecutor.PROP_PHASE, "myphase");
+ project.setConfiguration(conf);
+
+ phaseExecutor.execute(project, mock(SensorContext.class));
+
+ verify(mavenPluginExecutor).execute(project, "myphase");
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/MavenPluginsConfiguratorTest.java b/sonar-batch/src/test/java/org/sonar/batch/MavenPluginsConfiguratorTest.java
new file mode 100644
index 00000000000..aea7b42c6cb
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/MavenPluginsConfiguratorTest.java
@@ -0,0 +1,77 @@
+/*
+ * 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.batch;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.junit.Test;
+import org.sonar.api.batch.BatchExtensionDictionnary;
+import org.sonar.api.batch.SensorContext;
+import org.sonar.api.batch.maven.MavenPlugin;
+import org.sonar.api.batch.maven.MavenPluginHandler;
+import org.sonar.api.resources.Project;
+import org.sonar.api.test.MavenTestUtils;
+import org.sonar.api.utils.ServerHttpClient;
+
+import java.util.Arrays;
+
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Mockito.*;
+
+public class MavenPluginsConfiguratorTest {
+
+ private MavenPluginsConfigurator newConfigurator(MavenPluginHandler... handlers) {
+ BatchExtensionDictionnary selector = mock(BatchExtensionDictionnary.class);
+ when(selector.selectMavenPluginHandlers((Project) anyObject())).thenReturn(Arrays.asList(handlers));
+ return new MavenPluginsConfigurator(selector);
+ }
+
+ @Test
+ public void configureHandlers() {
+ MavenPluginHandler handler1 = mock(MavenPluginHandler.class);
+ when(handler1.getArtifactId()).thenReturn("myartifact1");
+
+ MavenPluginHandler handler2 = mock(MavenPluginHandler.class);
+ when(handler2.getArtifactId()).thenReturn("myartifact2");
+
+ Project project = MavenTestUtils.loadProjectFromPom(getClass(), "pom.xml");
+
+ newConfigurator(handler1, handler2).execute(project, mock(SensorContext.class));
+
+ verify(handler1).configure(eq(project), argThat(new IsMavenPlugin("myartifact1")));
+ verify(handler2).configure(eq(project), argThat(new IsMavenPlugin("myartifact2")));
+ }
+
+ private class IsMavenPlugin extends BaseMatcher<MavenPlugin> {
+ private String artifactId;
+
+ public IsMavenPlugin(String artifactId) {
+ this.artifactId = artifactId;
+ }
+
+ public boolean matches(Object o) {
+ return artifactId.equals(((MavenPlugin) o).getPlugin().getArtifactId());
+ }
+
+ public void describeTo(Description description) {
+
+ }
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/PostJobsExecutorTest.java b/sonar-batch/src/test/java/org/sonar/batch/PostJobsExecutorTest.java
new file mode 100644
index 00000000000..6a1d72cbc58
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/PostJobsExecutorTest.java
@@ -0,0 +1,66 @@
+/*
+ * 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.batch;
+
+import org.junit.Test;
+import org.sonar.api.batch.PostJob;
+import org.sonar.api.batch.SensorContext;
+import org.sonar.api.resources.Project;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.*;
+
+public class PostJobsExecutorTest {
+
+ @Test
+ public void doNotExecuteOnModules() {
+ PostJob job1 = mock(PostJob.class);
+ Project module = new Project("module").setParent(new Project("project"));
+
+ PostJobsExecutor executor = new PostJobsExecutor(Arrays.<PostJob>asList(job1), mock(MavenPluginExecutor.class));
+ executor.execute(module, mock(SensorContext.class));
+
+ verify(job1, never()).executeOn((Project) anyObject(), (SensorContext) anyObject());
+ }
+
+ @Test
+ public void executeAllPostJobs() {
+ PostJob job1 = mock(PostJob.class);
+ PostJob job2 = mock(PostJob.class);
+ List<PostJob> jobs = Arrays.asList(job1, job2);
+
+ PostJobsExecutor executor = new PostJobsExecutor(jobs, mock(MavenPluginExecutor.class));
+ Project project = new Project("project");
+ SensorContext context = mock(SensorContext.class);
+ executor.execute(project, context);
+
+ verify(job1).executeOn(project, context);
+ verify(job2).executeOn(project, context);
+
+ }
+
+ static class FakePostJob implements PostJob {
+ public void executeOn(Project project, SensorContext context) {
+ }
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/ProfileProviderTest.java b/sonar-batch/src/test/java/org/sonar/batch/ProfileProviderTest.java
new file mode 100644
index 00000000000..bdefef5c6c8
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/ProfileProviderTest.java
@@ -0,0 +1,95 @@
+/*
+ * 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.batch;
+
+import org.apache.commons.configuration.MapConfiguration;
+import org.junit.Test;
+import org.sonar.jpa.dao.ProfilesDao;
+import org.sonar.api.profiles.Alert;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.resources.Java;
+import org.sonar.api.resources.Project;
+import org.sonar.api.rules.ActiveRule;
+
+import java.util.Collections;
+import java.util.HashMap;
+
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.*;
+
+public class ProfileProviderTest {
+
+ @Test
+ public void shouldGetProjectProfile() {
+ ProfileProvider provider = new ProfileProvider();
+ Project project = new Project("project").setLanguageKey(Java.KEY);
+ Project module = new Project("module").setParent(project).setLanguageKey(Java.KEY);
+ ProfilesDao dao = mock(ProfilesDao.class);
+
+ when(dao.getActiveProfile(Java.KEY, "project")).thenReturn(newProfile());
+
+ assertNotNull(provider.provide(module, dao));
+
+ verify(dao, never()).getActiveProfile(Java.KEY, "module");
+ verify(dao).getActiveProfile(Java.KEY, "project");
+ }
+
+ private RulesProfile newProfile() {
+ RulesProfile profile = new RulesProfile();
+ profile.setAlerts(Collections.<Alert>emptyList());
+ profile.setActiveRules(Collections.<ActiveRule>emptyList());
+ return profile;
+ }
+
+ @Test
+ public void mavenPropertyShouldOverrideProfile() {
+ ProfileProvider provider = new ProfileProvider();
+ ProfilesDao dao = mock(ProfilesDao.class);
+ Project project = new Project("project").setLanguageKey(Java.KEY);
+
+ MapConfiguration conf = new MapConfiguration(new HashMap());
+ conf.addProperty(ProfileProvider.PARAM_PROFILE, "profile1");
+ project.setConfiguration(conf);
+
+ when(dao.getProfile(Java.KEY, "profile1")).thenReturn(newProfile());
+
+ provider.provide(project, dao);
+
+ verify(dao).getProfile(Java.KEY, "profile1");
+ verify(dao, never()).getActiveProfile(Java.KEY, "project");
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void shouldFailIfProfileIsNotFound() {
+ ProfileProvider provider = new ProfileProvider();
+ Project project = new Project("project").setLanguageKey(Java.KEY);
+ ProfilesDao dao = mock(ProfilesDao.class);
+
+ MapConfiguration conf = new MapConfiguration(new HashMap());
+ conf.addProperty(ProfileProvider.PARAM_PROFILE, "unknown");
+ project.setConfiguration(conf);
+
+
+ when(dao.getProfile(Java.KEY, "profile1")).thenReturn(null);
+
+ provider.provide(project, dao);
+ }
+
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/ProjectBuilderTest.java b/sonar-batch/src/test/java/org/sonar/batch/ProjectBuilderTest.java
new file mode 100644
index 00000000000..586edaa9300
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/ProjectBuilderTest.java
@@ -0,0 +1,210 @@
+/*
+ * 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.batch;
+
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.api.CoreProperties;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.resources.Java;
+import org.sonar.api.resources.Project;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class ProjectBuilderTest extends AbstractDbUnitTestCase {
+
+ private ProjectBuilder builder = null;
+
+ @Before
+ public void before() {
+ builder = new ProjectBuilder(getSession());
+ }
+
+ @Test
+ public void noExclusionPatterns() {
+ Project project = new Project("key");
+ builder.configure(project, new PropertiesConfiguration());
+
+ assertThat(project.getExclusionPatterns().length, is(0));
+ }
+
+ @Test
+ public void manyExclusionPatterns() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "**/*,foo,*/bar");
+
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+
+ assertThat(project.getExclusionPatterns().length, is(3));
+ assertThat(project.getExclusionPatterns()[0], is("**/*"));
+ assertThat(project.getExclusionPatterns()[1], is("foo"));
+ assertThat(project.getExclusionPatterns()[2], is("*/bar"));
+ }
+
+ @Test
+ public void getLanguageFromConfiguration() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.PROJECT_LANGUAGE_PROPERTY, "foo");
+
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+
+ assertThat(project.getLanguageKey(), is("foo"));
+ }
+
+ @Test
+ public void defaultLanguageIsJava() {
+ Project project = new Project("key");
+ builder.configure(project, new PropertiesConfiguration());
+
+ assertThat(project.getLanguageKey(), is(Java.KEY));
+ }
+
+ @Test
+ public void analysisIsTodayByDefault() {
+ Project project = new Project("key");
+ builder.configure(project, new PropertiesConfiguration());
+ Date today = new Date();
+ assertTrue(today.getTime() - project.getAnalysisDate().getTime() < 1000);
+ }
+
+ @Test
+ public void analysisDateCouldBeExplicitlySet() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2005-01-30");
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+
+ assertEquals("30012005", new SimpleDateFormat("ddMMyyyy").format(project.getAnalysisDate()));
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void failIfAnalyisDateIsNotValid() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2005/30/01");
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+
+ project.getAnalysisDate();
+ }
+
+ @Test
+ public void sonarLightIsDeprecated() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty("sonar.light", "true");
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+
+ assertThat(project.getAnalysisType(), is(Project.AnalysisType.STATIC));
+ }
+
+ @Test
+ public void defaultAnalysisTypeIsDynamic() {
+ Project project = new Project("key");
+ builder.configure(project, new PropertiesConfiguration());
+ assertThat(project.getAnalysisType(), is(Project.AnalysisType.DYNAMIC));
+ }
+
+ @Test
+ public void explicitDynamicAnalysis() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.DYNAMIC_ANALYSIS_PROPERTY, "true");
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+ assertThat(project.getAnalysisType(), is(Project.AnalysisType.DYNAMIC));
+ }
+
+ @Test
+ public void explicitStaticAnalysis() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.DYNAMIC_ANALYSIS_PROPERTY, "false");
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+ assertThat(project.getAnalysisType(), is(Project.AnalysisType.STATIC));
+ }
+
+ @Test
+ public void explicitDynamicAnalysisReusingReports() {
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.DYNAMIC_ANALYSIS_PROPERTY, "reuseReports");
+ Project project = new Project("key");
+ builder.configure(project, configuration);
+ assertThat(project.getAnalysisType(), is(Project.AnalysisType.REUSE_REPORTS));
+ }
+
+ @Test
+ public void isDynamicAnalysis() {
+ assertThat(Project.AnalysisType.DYNAMIC.isDynamic(false), is(true));
+ assertThat(Project.AnalysisType.DYNAMIC.isDynamic(true), is(true));
+
+ assertThat(Project.AnalysisType.STATIC.isDynamic(false), is(false));
+ assertThat(Project.AnalysisType.STATIC.isDynamic(true), is(false));
+
+ assertThat(Project.AnalysisType.REUSE_REPORTS.isDynamic(false), is(false));
+ assertThat(Project.AnalysisType.REUSE_REPORTS.isDynamic(true), is(true));
+ }
+
+ @Test
+ public void isLatestAnalysis() {
+ setupData("isLatestAnalysis");
+
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2010-12-25");
+
+ Project project = new Project("my:key");
+ builder.configure(project, configuration);
+
+ assertThat(project.isLatestAnalysis(), is(true));
+ }
+
+ @Test
+ public void isLatestAnalysisIfNeverAnalysed() {
+ setupData("isLatestAnalysisIfNeverAnalysed");
+
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2010-12-25");
+
+ Project project = new Project("my:key");
+ builder.configure(project, configuration);
+
+ assertThat(project.isLatestAnalysis(), is(true));
+ }
+
+ @Test
+ public void isNotLatestAnalysis() {
+ setupData("isNotLatestAnalysis");
+
+ PropertiesConfiguration configuration = new PropertiesConfiguration();
+ configuration.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2005-12-25");
+
+ Project project = new Project("my:key");
+ builder.configure(project, configuration);
+
+ assertThat(project.isLatestAnalysis(), is(false));
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/ProjectConfigurationTest.java b/sonar-batch/src/test/java/org/sonar/batch/ProjectConfigurationTest.java
new file mode 100644
index 00000000000..247f0d09c0d
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/ProjectConfigurationTest.java
@@ -0,0 +1,117 @@
+/*
+ * 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.batch;
+
+import org.apache.maven.project.MavenProject;
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.resources.Project;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+
+public class ProjectConfigurationTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void loadSystemProperties() {
+ System.setProperty("foo", "bar");
+ setupData("global-properties");
+
+ ProjectConfiguration config = new ProjectConfiguration(getSession(), newProject());
+ assertThat(config.getString("foo"), is("bar"));
+ assertNull(config.getString("unknown"));
+ }
+
+ @Test
+ public void loadDatabaseProperties() {
+ setupData("global-properties");
+ ProjectConfiguration config = new ProjectConfiguration(getSession(), newProject());
+ assertThat(config.getString("key1"), is("value1"));
+ assertNull(config.getString("key3"));
+ }
+
+ @Test
+ public void loadProjectDatabaseProperties() {
+ setupData("project-properties");
+ ProjectConfiguration config = new ProjectConfiguration(getSession(), newProject());
+ assertThat(config.getString("key1"), is("overriden_value1"));
+ assertThat(config.getString("key2"), is("value2"));
+ assertThat(config.getString("key3"), is("value3"));
+ }
+
+ @Test
+ public void loadModuleDatabaseProperties() {
+ setupData("modules-properties");
+ ProjectConfiguration moduleConfig = new ProjectConfiguration(getSession(), newModule());
+
+ assertThat(moduleConfig.getString("key1"), is("project_value_1"));
+ assertThat(moduleConfig.getString("key2"), is("value_2"));
+ assertThat(moduleConfig.getString("key3"), is("module_value_3"));
+ assertThat(moduleConfig.getString("key4"), is("module_value_4"));
+ }
+
+ @Test
+ public void mavenSettingsLoadedBeforeGlobalSettings() {
+ setupData("global-properties");
+ Project project = newProject();
+ project.getPom().getProperties().put("key1", "maven1");
+ ProjectConfiguration config = new ProjectConfiguration(getSession(), project);
+ assertThat(config.getString("key1"), is("maven1"));
+ }
+
+ @Test
+ public void projectSettingsLoadedBeforeMavenSettings() {
+ setupData("project-properties");
+ Project project = newProject();
+ project.getPom().getProperties().put("key1", "maven1");
+ ProjectConfiguration config = new ProjectConfiguration(getSession(), project);
+ assertThat(config.getString("key1"), is("overriden_value1"));
+ }
+
+ @Test
+ public void addPropertyAtRuntime() {
+ setupData("global-properties");
+ ProjectConfiguration config = new ProjectConfiguration(getSession(), newProject());
+
+ config.getInMemoryConfiguration().setProperty("new-key", "new-value");
+ assertThat(config.getString("new-key"), is("new-value"));
+ }
+
+ @Test
+ public void overridePropertyAtRuntime() {
+ setupData("global-properties");
+ ProjectConfiguration config = new ProjectConfiguration(getSession(), newProject());
+
+ assertThat(config.getString("key1"), is("value1"));
+ config.setProperty("key1", "new1");
+ assertThat(config.getString("key1"), is("new1"));
+ }
+
+ private Project newProject() {
+ return new Project("mygroup:myproject").setPom(new MavenProject());
+ }
+
+ private Project newModule() {
+ Project module = new Project("mygroup:mymodule").setPom(new MavenProject());
+ module.setParent(newProject());
+ return module;
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/ProjectTreeTest.java b/sonar-batch/src/test/java/org/sonar/batch/ProjectTreeTest.java
new file mode 100644
index 00000000000..8473b959f3d
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/ProjectTreeTest.java
@@ -0,0 +1,209 @@
+/*
+ * 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.batch;
+
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.commons.io.FileUtils;
+import org.apache.maven.model.Model;
+import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
+import org.apache.maven.project.MavenProject;
+import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.resources.Project;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertNull;
+import static org.junit.internal.matchers.IsCollectionContaining.hasItem;
+
+
+public class ProjectTreeTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void moduleNameShouldEqualArtifactId() throws Exception {
+ MavenProject parent = loadProject("/org/sonar/batch/ProjectTreeTest/moduleNameShouldEqualArtifactId/pom.xml", true);
+ MavenProject module1 = loadProject("/org/sonar/batch/ProjectTreeTest/moduleNameShouldEqualArtifactId/module1/pom.xml", false);
+ MavenProject module2 = loadProject("/org/sonar/batch/ProjectTreeTest/moduleNameShouldEqualArtifactId/module2/pom.xml", false);
+
+ ProjectTree tree = new ProjectTree(newProjectBuilder(), Arrays.asList(parent, module1, module2));
+ tree.start();
+
+ Project root = tree.getRootProject();
+ assertThat(root.getModules().size(), is(2));
+ assertThat(root.getKey(), is("org.test:parent"));
+ assertNull(root.getParent());
+ assertThat(tree.getProjectByArtifactId("module1").getKey(), is("org.test:module1"));
+ assertThat(tree.getProjectByArtifactId("module1").getParent(), is(root));
+ assertThat(tree.getProjectByArtifactId("module2").getKey(), is("org.test:module2"));
+ assertThat(tree.getProjectByArtifactId("module2").getParent(), is(root));
+ }
+
+ @Test
+ public void moduleNameDifferentThanArtifactId() throws Exception {
+ MavenProject parent = loadProject("/org/sonar/batch/ProjectTreeTest/moduleNameDifferentThanArtifactId/pom.xml", true);
+ MavenProject module1 = loadProject("/org/sonar/batch/ProjectTreeTest/moduleNameDifferentThanArtifactId/path1/pom.xml", false);
+ MavenProject module2 = loadProject("/org/sonar/batch/ProjectTreeTest/moduleNameDifferentThanArtifactId/path2/pom.xml", false);
+
+ ProjectTree tree = new ProjectTree(newProjectBuilder(), Arrays.asList(parent, module1, module2));
+ tree.start();
+
+
+ Project root = tree.getRootProject();
+ assertThat(root.getModules().size(), is(2));
+ assertThat(root.getKey(), is("org.test:parent"));
+ assertNull(root.getParent());
+ assertThat(tree.getProjectByArtifactId("module1").getKey(), is("org.test:module1"));
+ assertThat(tree.getProjectByArtifactId("module1").getParent(), is(root));
+ assertThat(tree.getProjectByArtifactId("module2").getKey(), is("org.test:module2"));
+ assertThat(tree.getProjectByArtifactId("module2").getParent(), is(root));
+ }
+
+ @Test
+ public void singleProjectWithoutModules() throws Exception {
+ MavenProject parent = loadProject("/org/sonar/batch/ProjectTreeTest/singleProjectWithoutModules/pom.xml", true);
+
+ ProjectTree tree = new ProjectTree(newProjectBuilder(), Arrays.asList(parent));
+ tree.start();
+
+ Project root = tree.getRootProject();
+ assertThat(root.getModules().size(), is(0));
+ assertThat(root.getKey(), is("org.test:parent"));
+ }
+
+ @Test
+ public void keyIncludesBranch() throws IOException, XmlPullParserException, URISyntaxException {
+ MavenProject pom = loadProject("/org/sonar/batch/ProjectTreeTest/keyIncludesBranch/pom.xml", true);
+
+ ProjectTree tree = new ProjectTree(newProjectBuilder(), Arrays.asList(pom));
+ tree.start();
+
+ assertThat(tree.getRootProject().getKey(), is("org.test:project:BRANCH-1.X"));
+ assertThat(tree.getRootProject().getName(), is("Project BRANCH-1.X"));
+ }
+
+
+ @Test
+ public void keyIncludesDeprecatedBranch() throws IOException, XmlPullParserException, URISyntaxException {
+ MavenProject pom = loadProject("/org/sonar/batch/ProjectTreeTest/keyIncludesDeprecatedBranch/pom.xml", true);
+
+ ProjectTree tree = new ProjectTree(newProjectBuilder(), Arrays.asList(pom));
+ tree.start();
+
+ assertThat(tree.getRootProject().getKey(), is("org.test:project:BRANCH-1.X"));
+ assertThat(tree.getRootProject().getName(), is("Project BRANCH-1.X"));
+ }
+
+ @Test
+ public void doNotSkipAnyModules() {
+ Project foo = newProjectWithArtifactId("root");
+ Project bar = newProjectWithArtifactId("sub1");
+ Project baz = newProjectWithArtifactId("sub2");
+
+ ProjectTree tree = new ProjectTree(Arrays.asList(foo, bar, baz));
+ tree.applyModuleExclusions();
+
+ assertThat(tree.getProjects().size(), is(3));
+ }
+
+ @Test
+ public void skipModule() {
+ Project root = newProjectWithArtifactId("root");
+ root.getConfiguration().setProperty("sonar.skippedModules", "sub1");
+ Project sub1 = newProjectWithArtifactId("sub1");
+ Project sub2 = newProjectWithArtifactId("sub2");
+
+ ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ tree.applyModuleExclusions();
+
+ assertThat(tree.getProjects().size(), is(2));
+ assertThat(tree.getProjects(), hasItem(root));
+ assertThat(tree.getProjects(), hasItem(sub2));
+ }
+
+ @Test
+ public void skipModules() {
+ Project root = newProjectWithArtifactId("root");
+ root.getConfiguration().setProperty("sonar.skippedModules", "sub1,sub2");
+ Project sub1 = newProjectWithArtifactId("sub1");
+ Project sub2 = newProjectWithArtifactId("sub2");
+
+ ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ tree.applyModuleExclusions();
+
+ assertThat(tree.getProjects().size(), is(1));
+ assertThat(tree.getProjects(), hasItem(root));
+ }
+
+ @Test
+ public void includeModules() {
+ Project root = newProjectWithArtifactId("root");
+ root.getConfiguration().setProperty("sonar.includedModules", "sub1,sub2");
+ Project sub1 = newProjectWithArtifactId("sub1");
+ Project sub2 = newProjectWithArtifactId("sub2");
+
+ ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ tree.applyModuleExclusions();
+
+ assertThat(tree.getProjects().size(), is(2));
+ assertThat(tree.getProjects(), hasItem(sub1));
+ assertThat(tree.getProjects(), hasItem(sub2));
+ }
+
+ @Test
+ public void skippedModulesTakePrecedenceOverIncludedModules() {
+ Project root = newProjectWithArtifactId("root");
+ root.getConfiguration().setProperty("sonar.includedModules", "sub1,sub2");
+ root.getConfiguration().setProperty("sonar.skippedModules", "sub1");
+ Project sub1 = newProjectWithArtifactId("sub1");
+ Project sub2 = newProjectWithArtifactId("sub2");
+
+ ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ tree.applyModuleExclusions();
+
+ assertThat(tree.getProjects().size(), is(1));
+ assertThat(tree.getProjects(), hasItem(sub2));
+ }
+
+ private Project newProjectWithArtifactId(String artifactId) {
+ MavenProject pom = new MavenProject();
+ pom.setArtifactId(artifactId);
+ return new Project(artifactId).setPom(pom).setConfiguration(new PropertiesConfiguration());
+ }
+
+ private MavenProject loadProject(String pomPath, boolean isRoot) throws URISyntaxException, IOException, XmlPullParserException {
+ File pomFile = new File(getClass().getResource(pomPath).toURI());
+ Model model = new MavenXpp3Reader().read(new StringReader(FileUtils.readFileToString(pomFile)));
+ MavenProject pom = new MavenProject(model);
+ pom.setFile(pomFile);
+ pom.setExecutionRoot(isRoot);
+ return pom;
+ }
+
+ private ProjectBuilder newProjectBuilder() {
+ return new ProjectBuilder(getSession());
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/RemoteClassLoaderTest.java b/sonar-batch/src/test/java/org/sonar/batch/RemoteClassLoaderTest.java
new file mode 100644
index 00000000000..f79d4535a0e
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/RemoteClassLoaderTest.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.batch;
+
+import org.junit.Test;
+
+import java.net.URL;
+import java.util.Arrays;
+
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertNull;
+
+public class RemoteClassLoaderTest {
+
+ @Test
+ public void testClassLoader() {
+ /* foo.jar has just one file /foo/foo.txt */
+ assertNull(getClass().getClassLoader().getResource("foo/foo.txt"));
+
+ URL url = getClass().getResource("/org/sonar/batch/RemoteClassLoaderTest/foo.jar");
+ RemoteClassLoader classloader = new RemoteClassLoader(Arrays.asList(url), null);
+ assertNotNull(classloader.getClassLoader());
+ assertNotNull(classloader.getClassLoader().getResource("foo/foo.txt"));
+
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/ServerMetadataTest.java b/sonar-batch/src/test/java/org/sonar/batch/ServerMetadataTest.java
new file mode 100644
index 00000000000..cef7537c63a
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/ServerMetadataTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.batch;
+
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.junit.Test;
+import org.sonar.api.CoreProperties;
+
+import java.text.ParseException;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class ServerMetadataTest {
+
+ @Test
+ public void testLoadProperties() throws ParseException {
+ PropertiesConfiguration conf = new PropertiesConfiguration();
+ conf.setProperty(CoreProperties.SERVER_ID, "123");
+ conf.setProperty(CoreProperties.SERVER_VERSION, "2.2");
+ conf.setProperty(CoreProperties.SERVER_STARTTIME, "2010-05-18T17:59:00+0000");
+ conf.setProperty("sonar.host.url", "http://foo.com");
+
+ ServerMetadata server = new ServerMetadata(conf);
+
+ assertThat(server.getId(), is("123"));
+ assertThat(server.getVersion(), is("2.2"));
+ assertThat(server.getStartedAt().getDate(), is(18));
+ assertThat(server.getUrl(), is("http://foo.com"));
+ }
+
+ /**
+ * http://jira.codehaus.org/browse/SONAR-1685
+ * The maven plugin fails if the property sonar.host.url ends with a slash
+ */
+ @Test
+ public void urlMustNotEndWithSlash() throws ParseException {
+ PropertiesConfiguration conf = new PropertiesConfiguration();
+ conf.setProperty("sonar.host.url", "http://localhost:80/");
+
+ ServerMetadata server = new ServerMetadata(conf);
+ assertThat(server.getUrl(), is("http://localhost:80"));
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/ViolationFiltersTest.java b/sonar-batch/src/test/java/org/sonar/batch/ViolationFiltersTest.java
new file mode 100644
index 00000000000..53eb38959b2
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/ViolationFiltersTest.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.batch;
+
+import org.junit.Test;
+import org.sonar.api.rules.Violation;
+import org.sonar.api.rules.ViolationFilter;
+
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class ViolationFiltersTest {
+
+ @Test
+ public void doNotFailIfNoFilters() {
+ ViolationFilters filters = new ViolationFilters();
+ assertThat(filters.isIgnored(new Violation(null)), is(false));
+ }
+
+ @Test
+ public void ignoreViolation() {
+ ViolationFilters filters = new ViolationFilters(new ViolationFilter[]{
+ new FakeFilter(false),
+ new FakeFilter(true),
+ new FakeFilter(false),
+ });
+ assertThat(filters.isIgnored(new Violation(null)), is(true));
+ }
+
+ @Test
+ public void doNotIgnoreValidViolations() {
+ ViolationFilters filters = new ViolationFilters(new ViolationFilter[]{
+ new FakeFilter(false),
+ new FakeFilter(false),
+ new FakeFilter(false),
+ });
+ assertThat(filters.isIgnored(new Violation(null)), is(false));
+ }
+
+ private static class FakeFilter implements ViolationFilter {
+ private boolean ignore;
+
+ private FakeFilter(boolean ignore) {
+ this.ignore = ignore;
+ }
+
+ public boolean isIgnored(Violation violation) {
+ return ignore;
+ }
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultPersisterTest.java b/sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultPersisterTest.java
new file mode 100644
index 00000000000..efeec499d64
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultPersisterTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.batch.indexer;
+
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.JavaPackage;
+import org.sonar.api.resources.Project;
+
+public class DefaultPersisterTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void createResource() {
+ setupData("createResource");
+
+ Bucket bucket = createBucket(new JavaPackage("org.foo"));
+
+ new DefaultPersister(getSession()).persist(bucket);
+
+ checkTables("createResource", "projects", "snapshots");
+ }
+
+ private Bucket createBucket(JavaPackage resource) {
+ Bucket projectBucket = new Bucket(new Project("my:key").setId(5));
+ projectBucket.setSnapshot(getSession().getSingleResult(Snapshot.class, "id", 30));
+
+ Bucket bucket = new Bucket(resource);
+ bucket.setProject(projectBucket);
+ bucket.setParent(projectBucket);
+ return bucket;
+ }
+
+ @Test
+ public void updateExistingResource() {
+ setupData("updateExistingResource");
+
+ Bucket bucket = createBucket(new JavaPackage("org.foo"));
+
+ new DefaultPersister(getSession()).persist(bucket);
+
+ checkTables("updateExistingResource", "projects", "snapshots");
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultSonarIndexTest.java b/sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultSonarIndexTest.java
new file mode 100644
index 00000000000..fdbc09cc47c
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/indexer/DefaultSonarIndexTest.java
@@ -0,0 +1,56 @@
+/*
+ * 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.batch.indexer;
+
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.design.Dependency;
+import org.sonar.api.resources.JavaFile;
+import org.sonar.api.resources.Resource;
+
+import static junit.framework.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class DefaultSonarIndexTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void indexDependencies() {
+ DefaultSonarIndex index = new DefaultSonarIndex(getSession(), null);
+
+ Resource from = new JavaFile("org.foo.Foo");
+ Resource to = new JavaFile("org.bar.Bar");
+ Dependency dependency = new Dependency(from, to);
+
+ index.registerDependency(dependency);
+
+ assertThat(index.getDependencies().size(), is(1));
+ assertTrue(index.getDependencies().contains(dependency));
+ assertThat(index.getEdge(from, to), is(dependency));
+
+ assertThat(index.getIncomingEdges(to).size(), is(1));
+ assertTrue(index.getIncomingEdges(to).contains(dependency));
+ assertThat(index.getIncomingEdges(from).isEmpty(), is(true));
+
+ assertThat(index.getOutgoingEdges(from).size(), is(1));
+ assertTrue(index.getOutgoingEdges(from).contains(dependency));
+ assertThat(index.getOutgoingEdges(to).isEmpty(), is(true));
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/indexer/LibraryPersisterTest.java b/sonar-batch/src/test/java/org/sonar/batch/indexer/LibraryPersisterTest.java
new file mode 100644
index 00000000000..49933e44a7d
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/indexer/LibraryPersisterTest.java
@@ -0,0 +1,94 @@
+/*
+ * 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.batch.indexer;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Library;
+import org.sonar.api.resources.Project;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+
+public class LibraryPersisterTest extends AbstractDbUnitTestCase {
+
+ private Bucket<Project> projectBucket;
+ private LibraryPersister persister;
+
+ @Before
+ public void before() throws ParseException {
+ persister = new LibraryPersister(getSession(), new SimpleDateFormat("yyyy-MM-dd HH:mm").parse( "2010-05-18 17:00"));
+ }
+
+ @Test
+ public void createLibrary() throws Exception {
+ setup("createLibrary");
+
+ Library library = new Library("commons-lang:commons-lang", "1.1")
+ .setName("Commons Lang");
+
+ Bucket<Library> bucket = new Bucket<Library>(library).setProject(projectBucket);
+ persister.persist(bucket);
+
+ check("createLibrary", "projects", "snapshots");
+ }
+
+ @Test
+ public void reuseExistingLibrary() throws Exception {
+ setup("reuseExistingLibrary");
+
+ Library library = new Library("commons-lang:commons-lang", "1.1")
+ .setName("Commons Lang");
+
+ Bucket<Library> bucket = new Bucket<Library>(library).setProject(projectBucket);
+ persister.persist(bucket);
+
+ check("reuseExistingLibrary", "projects", "snapshots");
+ }
+
+ @Test
+ public void addNewLibraryVersion() throws Exception {
+ setup("addNewLibraryVersion");
+
+ Library library = new Library("commons-lang:commons-lang", "1.2")
+ .setName("Commons Lang");
+
+ Bucket<Library> bucket = new Bucket<Library>(library).setProject(projectBucket);
+ persister.persist(bucket);
+
+ check("addNewLibraryVersion", "projects", "snapshots");
+ }
+
+ private void setup(String unitTest) throws Exception {
+ setupData(unitTest);
+
+ Project project = new Project("my:project");
+ project.setId(1);
+ projectBucket = new Bucket<Project>(project);
+ projectBucket.setSnapshot(getSession().getSingleResult(Snapshot.class, "id", 1));
+ }
+
+ private void check(String unitTest, String... tables) {
+ getSession().commit();
+ checkTables(unitTest, tables);
+ }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/indexer/ResourcePersistersTest.java b/sonar-batch/src/test/java/org/sonar/batch/indexer/ResourcePersistersTest.java
new file mode 100644
index 00000000000..cb75095aef4
--- /dev/null
+++ b/sonar-batch/src/test/java/org/sonar/batch/indexer/ResourcePersistersTest.java
@@ -0,0 +1,67 @@
+/*
+ * 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.batch.indexer;
+
+import org.junit.Test;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import org.sonar.api.resources.*;
+
+import static junit.framework.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+public class ResourcePersistersTest extends AbstractDbUnitTestCase {
+
+ @Test
+ public void getDefaultPersisterForFilesAndPackages() {
+ ResourcePersisters persisters = new ResourcePersisters(getSession());
+
+
+ JavaFile file = new JavaFile("org.foo.Bar");
+ assertThat(persisters.get(file), is(DefaultPersister.class));
+ assertThat(persisters.get(new JavaPackage("org.foo")), is(DefaultPersister.class));
+ assertThat(persisters.get(new File("org/foo/Bar.sql")), is(DefaultPersister.class));
+
+ // always the same instance
+ assertTrue(persisters.get(file)==persisters.get(file));
+ }
+
+ @Test
+ public void getForProjects() {
+ ResourcePersisters persisters = new ResourcePersisters(getSession());
+
+ Project project = new Project("my:project");
+ assertThat(persisters.get(project), is(ProjectPersister.class));
+
+ // always the same instance
+ assertTrue(persisters.get(project)==persisters.get(project));
+ }
+
+ @Test
+ public void getForLibraries() {
+ ResourcePersisters persisters = new ResourcePersisters(getSession());
+
+ Library lib = new Library("commons-lang:commons-lang", "1.0");
+ assertThat(persisters.get(lib), is(LibraryPersister.class));
+
+ // always the same instance
+ assertTrue(persisters.get(lib)==persisters.get(lib));
+ }
+}