@Test public void shouldExecuteOnRootProjectWithAllParams() throws Exception { Project project = mock(Project.class); when(project.isRoot()).thenReturn(true).thenReturn(false); assertThat(sensor.shouldExecuteOnProject(project)).isEqualTo(true); }
@Test public void shouldReuseReport() throws Exception { Project project = createProject(); FindbugsExecutor executor = mock(FindbugsExecutor.class); SensorContext context = mock(SensorContext.class); Configuration conf = mock(Configuration.class); File xmlFile = new File(getClass().getResource("/org/sonar/plugins/findbugs/findbugsReport.xml").toURI()); when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn(xmlFile.getAbsolutePath()); when(project.getConfiguration()).thenReturn(conf); when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass")); FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithActiveRules(), new FakeRuleFinder(), executor); analyser.analyse(project, context); verify(executor, never()).execute(); verify(context, times(2)).saveViolation(any(Violation.class)); Violation wanted = Violation.create((Rule) null, new JavaFile("org.sonar.commons.ZipUtils")) .setMessage( "Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream)") .setLineId(107); verify(context).saveViolation(argThat(new IsViolation(wanted))); wanted = Violation.create((Rule) null, new JavaFile("org.sonar.commons.resources.MeasuresDao")) .setMessage( "The class org.sonar.commons.resources.MeasuresDao$1 could be refactored into a named _static_ inner class") .setLineId(56); verify(context).saveViolation(argThat(new IsViolation(wanted))); }
private boolean shouldDecorateResource(Resource resource) { if (isProject(resource)) { Project project = (Project) resource; return project.getId() != null && countRoles(project.getId()) == 0; } return false; }
@Test public void testShouldAnalyseReusedReports() throws Exception { conf.addProperty(GendarmeConstants.MODE, GendarmeSensor.MODE_REUSE_REPORT); conf.addProperty(GendarmeConstants.REPORTS_PATH_KEY, "**/*.xml"); initializeSensor(); GendarmeRunner runner = mock(GendarmeRunner.class); GendarmeCommandBuilder builder = GendarmeCommandBuilder.createBuilder(null, vsProject); builder.setExecutable(new File("FxCopCmd.exe")); when(runner.createCommandBuilder(eq(solution), any(VisualStudioProject.class))) .thenReturn(builder); PowerMockito.mockStatic(GendarmeRunner.class); when(GendarmeRunner.create(anyString(), anyString())).thenReturn(runner); File fakeReport = TestUtils.getResource("/Sensor/FakeGendarmeConfigFile.xml"); PowerMockito.mockStatic(FileFinder.class); when(FileFinder.findFiles(solution, vsProject, "**/*.xml")) .thenReturn(Lists.newArrayList(fakeReport, fakeReport)); Project project = mock(Project.class); when(project.getName()).thenReturn("Project #1"); SensorContext context = mock(SensorContext.class); sensor.analyse(project, context); verify(resultParser, times(2)).parse(any(File.class)); }
@Test public void testShouldExecuteOnProject() throws Exception { Configuration conf = new BaseConfiguration(); GendarmeSensor sensor = new GendarmeSensor.RegularGendarmeSensor( null, rulesProfile, profileExporter, null, new CSharpConfiguration(conf), microsoftWindowsEnvironment); Project project = mock(Project.class); when(project.getName()).thenReturn("Project #1"); when(project.getLanguageKey()).thenReturn("cs"); assertTrue(sensor.shouldExecuteOnProject(project)); conf.addProperty(GendarmeConstants.MODE, AbstractRegularCSharpSensor.MODE_SKIP); sensor = new GendarmeSensor.RegularGendarmeSensor( null, rulesProfile, profileExporter, null, new CSharpConfiguration(conf), microsoftWindowsEnvironment); assertFalse(sensor.shouldExecuteOnProject(project)); }
@Test public void should_analyse() { ProjectFileSystem fs = mock(ProjectFileSystem.class); when(fs.getSourceCharset()).thenReturn(Charset.forName("UTF-8")); InputFile inputFile = InputFileUtils.create( new File("src/test/resources/cpd"), new File("src/test/resources/cpd/Person.js")); when(fs.mainFiles(JavaScript.KEY)).thenReturn(ImmutableList.of(inputFile)); Project project = new Project("key"); project.setFileSystem(fs); SensorContext context = mock(SensorContext.class); sensor.analyse(project, context); verify(context) .saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.FILES), Mockito.eq(1.0)); verify(context) .saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.LINES), Mockito.eq(22.0)); verify(context) .saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.NCLOC), Mockito.eq(10.0)); verify(context) .saveMeasure( Mockito.any(Resource.class), Mockito.eq(CoreMetrics.FUNCTIONS), Mockito.eq(2.0)); verify(context) .saveMeasure( Mockito.any(Resource.class), Mockito.eq(CoreMetrics.STATEMENTS), Mockito.eq(6.0)); verify(context) .saveMeasure( Mockito.any(Resource.class), Mockito.eq(CoreMetrics.COMPLEXITY), Mockito.eq(3.0)); verify(context) .saveMeasure( Mockito.any(Resource.class), Mockito.eq(CoreMetrics.COMMENT_LINES), Mockito.eq(2.0)); }
public void analyse(Project project, SensorContext context) { if (StringUtils.isBlank(project.getAnalysisVersion())) { return; } deleteDeprecatedEvents(project, context); context.createEvent(project, project.getAnalysisVersion(), null, Event.CATEGORY_VERSION, null); }
@Before public void initialise() { // create mock db objects databaseSession = new MockDatabaseSession(); databaseSession.setEntities(entities); // create quality profile hierarchy int numberOfProfiles = 4; int numberOfRules = 100; rulesProfiles = createRuleProfileHierarchy("qp", numberOfProfiles, numberOfRules); // create test project DTO Integer projectId = new Integer(123); testProject = new Project("test.project.key"); testProject.setId(projectId); testProject.setName("testProject"); testProject.setLanguage(Java.INSTANCE); // create test project entity testProjectModel = new ResourceModel(); testProjectModel.setId(projectId); testProjectModel.setKey(testProject.getKey()); testProjectModel.setEnabled(Boolean.TRUE); testProjectModel.setRootId(projectId); testProjectModel.setLanguageKey(Java.KEY); testProjectModel.setRulesProfile(createRulesProfile("testProjectProfile", numberOfRules)); // add project to db objects MockDatabaseSession.EntityKey projectKey = databaseSession.new EntityKey(ResourceModel.class, projectId); entities.put(projectKey, testProjectModel); databaseSession.addMockQueryResults(ResourceModel.class, Arrays.asList(testProjectModel)); // define test threshold int violationThreshold = 10; // create violations List<ActiveRule> rules = rulesProfiles[0].getActiveRules(); int numberOfViolationsToBUnderThreshold = ((numberOfRules / 100) * violationThreshold) - 1; for (int i = 0; i < numberOfViolationsToBUnderThreshold; i++) { violations.add(Violation.create(rules.get(i), testProject)); } // create context decoratorContext = new MockDecoratorContext(testProject, testProject, violations); // define default settings settings = new Settings(); settings.setProperty( ProfileProgressionPlugin.GLOBAL_QUALITY_PROFILE_CHANGE_ENABLED_KEY, "true"); settings.setProperty( ProfileProgressionPlugin.PROJECT_QUALITY_PROFILE_CHANGE_ENABLED_KEY, "true"); settings.setProperty( ProfileProgressionPlugin.QUALITY_PROFILE_CHANGE_THRESHOLD_KEY, String.valueOf(violationThreshold)); settings.setProperty( ProfileProgressionPlugin.GLOBAL_TARGET_LANGUAGE_QUALITY_PROFILE_KEY, rulesProfiles[numberOfProfiles - 1].getName()); }
private Project createProject() { ProjectFileSystem fileSystem = mock(ProjectFileSystem.class); when(fileSystem.hasJavaSourceFiles()).thenReturn(Boolean.TRUE); Project project = mock(Project.class); when(project.getFileSystem()).thenReturn(fileSystem); return project; }
@Test public void should_execute_on_javascript_project() { Project project = new Project("key"); project.setLanguageKey("java"); assertThat(sensor.shouldExecuteOnProject(project)).isFalse(); project.setLanguageKey("js"); assertThat(sensor.shouldExecuteOnProject(project)).isTrue(); }
public Project getRootProject() { for (Project project : projects) { if (project.getParent() == null) { return project; } } throw new IllegalStateException("Can not find the root project from the list of Maven modules"); }
@Test public void testShouldNotExecuteOnTestProject() throws Exception { Project project = mock(Project.class); when(project.getName()).thenReturn("Project Test"); when(project.getLanguageKey()).thenReturn("cs"); assertFalse(sensor.shouldExecuteOnProject(project)); }
@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 should_execute_on_java_project() { Project project = mock(Project.class); when(project.getLanguageKey()).thenReturn("java"); assertThat(sensor.shouldExecuteOnProject(project)).isTrue(); when(project.getLanguageKey()).thenReturn("py"); assertThat(sensor.shouldExecuteOnProject(project)).isFalse(); }
/** {@inheritDoc} */ public boolean shouldExecuteOnProject(Project project) { if (project.isRoot() || !CSharpConstants.LANGUAGE_KEY.equals(project.getLanguageKey())) { return false; } boolean skipMode = AbstractCSharpSensor.MODE_SKIP.equalsIgnoreCase(executionMode); boolean isTestProject = microsoftWindowsEnvironment.getCurrentProject(project.getName()).isTest(); return !isTestProject && !skipMode; }
@Test public void shouldNotNotifyIfNotRootProject() throws Exception { Project project = mock(Project.class); when(project.getQualifier()).thenReturn(Qualifiers.MODULE); decorator.decorate(project, context); verify(notificationManager, never()).scheduleForSending(any(Notification.class)); }
@Test public void testShouldNotExecuteOnTestProjectOnReuseMode() throws Exception { conf.setProperty(GendarmeConstants.MODE, GendarmeSensor.MODE_REUSE_REPORT); Project project = mock(Project.class); when(project.getName()).thenReturn("Project Test"); when(project.getLanguageKey()).thenReturn("cs"); assertFalse(sensor.shouldExecuteOnProject(project)); }
@Test public void testShouldSkipProject() throws Exception { Project project = mock(Project.class); when(project.getName()).thenReturn("Project #1"); when(project.getLanguageKey()).thenReturn("cs"); conf.addProperty(GendarmeConstants.MODE, GendarmeSensor.MODE_SKIP); initializeSensor(); assertFalse(sensor.shouldExecuteOnProject(project)); }
@Test public void shouldNotExecuteOnRootProjectifOneParamMissing() throws Exception { Project project = mock(Project.class); when(project.isRoot()).thenReturn(true).thenReturn(false); settings.removeProperty(JiraConstants.SERVER_URL_PROPERTY); sensor = new JiraSensor(settings); assertThat(sensor.shouldExecuteOnProject(project)).isEqualTo(false); }
private static File getReportsDirectoryFromProperty(Project project) { String path = (String) project.getProperty(SUREFIRE_REPORTS_PATH_PROPERTY); if (StringUtils.isBlank(path)) { path = (String) project.getProperty(SUREFIRE_REPORTS_PATH_DEPRECATED_PROPERTY); } if (path != null) { return project.getFileSystem().resolvePath(path); } return null; }
@Test public void shouldExecuteIfLastAnalysis() { Project project = mock(Project.class); when(project.isLatestAnalysis()).thenReturn(false); assertThat(decorator.shouldExecuteOnProject(project), is(false)); when(project.isLatestAnalysis()).thenReturn(true); assertThat(decorator.shouldExecuteOnProject(project), is(true)); }
void doStart(Project rootProject) { Bucket bucket = new Bucket(rootProject); addBucket(rootProject, bucket); BatchComponent component = componentCache.add(rootProject, null); component.setInputComponent(new DefaultInputModule(rootProject.getEffectiveKey())); currentProject = rootProject; for (Project module : rootProject.getModules()) { addModule(rootProject, module); } }
private void addModule(Project parent, Project module) { ProjectDefinition parentDefinition = projectTree.getProjectDefinition(parent); java.io.File parentBaseDir = parentDefinition.getBaseDir(); ProjectDefinition moduleDefinition = projectTree.getProjectDefinition(module); java.io.File moduleBaseDir = moduleDefinition.getBaseDir(); module.setPath(new PathResolver().relativePath(parentBaseDir, moduleBaseDir)); addResource(module); for (Project submodule : module.getModules()) { addModule(module, submodule); } }
@Test public void testGetReportWithProperty() { File desired = new File(getClass().getResource("big/pylint.txt").getFile()); String dir = desired.getParent(); ProjectFileSystem fileSystem = mock(ProjectFileSystem.class); when(fileSystem.resolvePath(anyString())).thenReturn(new File(dir)); when(project.getFileSystem()).thenReturn(fileSystem); when(project.getProperty(PyLintUtils.PYLINT_REPORT_PATH_PROPERTY)).thenReturn(dir); File report = PyLintUtils.getReport(project); assertEquals(desired, report); }
private static File getReportsDirectoryFromPluginConfiguration(Project project) { MavenPlugin plugin = MavenPlugin.getPlugin( project.getPom(), MavenSurefireUtils.GROUP_ID, MavenSurefireUtils.ARTIFACT_ID); if (plugin != null) { String path = plugin.getParameter("reportsDirectory"); if (path != null) { return project.getFileSystem().resolvePath(path); } } return null; }
@Test public void writeConfigurationToWorkingDir() throws IOException { Project project = MavenTestUtils.loadProjectFromPom(getClass(), "writeConfigurationToWorkingDir/pom.xml"); CheckstyleProfileExporter exporter = new FakeExporter(); CheckstyleConfiguration configuration = new CheckstyleConfiguration(null, exporter, null, project.getFileSystem()); File xmlFile = configuration.getXMLDefinitionFile(); assertThat(xmlFile.exists(), is(true)); assertThat(FileUtils.readFileToString(xmlFile), is("<conf/>")); }
private void updateIssue(DefaultIssue issue, Rule rule, ActiveRule activeRule) { if (Strings.isNullOrEmpty(issue.message())) { issue.setMessage(rule.name()); } issue.setCreationDate(project.getAnalysisDate()); issue.setUpdateDate(project.getAnalysisDate()); if (issue.severity() == null) { issue.setSeverity(activeRule.severity()); } DebtRemediationFunction function = rule.debtRemediationFunction(); if (rule.debtSubCharacteristic() != null && function != null) { issue.setDebt(calculateDebt(function, issue.effortToFix(), rule.key())); } }
@Test public void shouldNotNotifyUserIfFirstAnalysis() throws Exception { Project project = new Project("key").setName("LongName"); project.setId(45); // PastSnapshot with targetDate==null means first analysis PastSnapshot pastSnapshot = new PastSnapshot("", null); when(timeMachineConfiguration.getProjectPastSnapshots()) .thenReturn(Lists.newArrayList(pastSnapshot)); Measure m = new Measure(CoreMetrics.NEW_VIOLATIONS).setVariation1(0.0); when(context.getMeasure(CoreMetrics.NEW_VIOLATIONS)).thenReturn(m); decorator.decorate(project, context); verify(notificationManager, never()).scheduleForSending(any(Notification.class)); }
@Test public void testSimpleProject() throws InterruptedException { final Project project = mockProject("project", true); when(project.getModules()).thenReturn(Collections.<Project>emptyList()); fakeAnalysis(profiler, project); assertThat(profiler.currentModuleProfiling.getProfilingPerPhase(Phase.MAVEN).totalTime()) .isEqualTo(4L); assertThat( profiler .currentModuleProfiling .getProfilingPerPhase(Phase.INIT) .getProfilingPerItem(new FakeInitializer()) .totalTime()) .isEqualTo(7L); assertThat( profiler .currentModuleProfiling .getProfilingPerPhase(Phase.SENSOR) .getProfilingPerItem(new FakeSensor()) .totalTime()) .isEqualTo(10L); assertThat( profiler .currentModuleProfiling .getProfilingPerPhase(Phase.DECORATOR) .getProfilingPerItem(new FakeDecorator1()) .totalTime()) .isEqualTo(20L); assertThat( profiler .currentModuleProfiling .getProfilingPerPhase(Phase.PERSISTER) .getProfilingPerItem(new FakeScanPersister()) .totalTime()) .isEqualTo(40L); assertThat( profiler .currentModuleProfiling .getProfilingPerPhase(Phase.POSTJOB) .getProfilingPerItem(new FakePostJob()) .totalTime()) .isEqualTo(30L); assertThat(profiler.currentModuleProfiling.getProfilingPerBatchStep("Free memory").totalTime()) .isEqualTo(9L); }
@Test public void should_send_notification_if_issue_change() throws Exception { when(project.getAnalysisDate()).thenReturn(DateUtils.parseDate("2013-05-18")); RuleKey ruleKey = RuleKey.of("squid", "AvoidCycles"); Rule rule = new Rule("squid", "AvoidCycles"); DefaultIssue issue = new DefaultIssue() .setNew(false) .setChanged(true) .setFieldChange(mock(IssueChangeContext.class), "severity", "MINOR", "BLOCKER") .setRuleKey(ruleKey); when(issueCache.all()).thenReturn(Arrays.asList(issue)); when(ruleFinder.findByKey(ruleKey)).thenReturn(rule); SendIssueNotificationsPostJob job = new SendIssueNotificationsPostJob(issueCache, notifications, ruleFinder); job.executeOn(project, sensorContext); verify(notifications) .sendChanges( eq(issue), any(IssueChangeContext.class), eq(rule), any(Component.class), (Component) isNull()); }