public void PreProc_NoPlugin() { // Arrange string workingDir = TestUtils.CreateTestSpecificFolder(this.TestContext); TestLogger logger = new TestLogger(); // Configure the server MockSonarQubeServer mockServer = new MockSonarQubeServer(); ServerDataModel data = mockServer.Data; data.ServerProperties.Add("server.key", "server value 1"); data.Languages.Add("invalid_plugin"); MockRoslynAnalyzerProvider mockAnalyzerProvider = new MockRoslynAnalyzerProvider(); mockAnalyzerProvider.SettingsToReturn = new AnalyzerSettings(); mockAnalyzerProvider.SettingsToReturn.RuleSetFilePath = "c:\\xxx.ruleset"; Mock <ITargetsInstaller> mockTargetsInstaller = new Mock <ITargetsInstaller>(); MockObjectFactory mockFactory = new MockObjectFactory(mockServer, mockTargetsInstaller.Object, mockAnalyzerProvider, new RulesetGenerator()); TeamBuildSettings settings; using (PreprocessTestUtils.CreateValidNonTeamBuildScope()) using (new WorkingDirectoryScope(workingDir)) { settings = TeamBuildSettings.GetSettingsFromEnvironment(new TestLogger()); Assert.IsNotNull(settings, "Test setup error: TFS environment variables have not been set correctly"); Assert.AreEqual(BuildEnvironment.NotTeamBuild, settings.BuildEnvironment, "Test setup error: build environment was not set correctly"); TeamBuildPreProcessor preProcessor = new TeamBuildPreProcessor(mockFactory, logger); // Act bool success = preProcessor.Execute(CreateValidArgs("key", "name", "1.0")); Assert.IsTrue(success, "Expecting the pre-processing to complete successfully"); } // Assert AssertDirectoriesCreated(settings); mockTargetsInstaller.Verify(x => x.InstallLoaderTargets(logger, workingDir), Times.Once()); mockServer.AssertMethodCalled("GetProperties", 1); mockServer.AssertMethodCalled("GetAllLanguages", 1); mockServer.AssertMethodCalled("TryGetQualityProfile", 0); // No valid plugin mockServer.AssertMethodCalled("GetActiveRules", 0); // No valid plugin mockServer.AssertMethodCalled("GetInactiveRules", 0); // No valid plugin AssertAnalysisConfig(settings.AnalysisConfigFilePath, 0, logger); // only contains SonarQubeAnalysisConfig (no rulesets or aditional files) AssertDirectoryContains(settings.SonarConfigDirectory, Path.GetFileName(settings.AnalysisConfigFilePath)); }
public void GenerateFile_WhenLocalSettingsNull_ThrowArgumentNullException() { // Arrange var analysisDir = TestUtils.CreateTestSpecificFolder(TestContext); var tbSettings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(analysisDir); Action act = () => AnalysisConfigGenerator.GenerateFile(null, tbSettings, new Dictionary <string, string>(), new List <AnalyzerSettings>(), new MockSonarQubeServer(), new TestLogger()); // Act & Assert act.Should().ThrowExactly <ArgumentNullException>().And.ParamName.Should().Be("localSettings"); }
AnalyzerSettings IAnalyzerProvider.SetupAnalyzer(TeamBuildSettings teamBuildSettings, IAnalysisPropertyProvider sonarProperties, IEnumerable <SonarRule> activeRules, IEnumerable <SonarRule> inactiveRules, string language) { teamBuildSettings.Should().NotBeNull(); sonarProperties.Should().NotBeNull(); language.Should().NotBeNullOrWhiteSpace(); SuppliedSonarProperties = sonarProperties; return(SettingsToReturn); }
public void AnalysisConfGen_FileProperties() { // File properties should not be copied to the file. // Instead, a pointer to the file should be created. // Arrange var analysisDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext); var logger = new TestLogger(); // The set of file properties to supply var fileProperties = new AnalysisProperties { new Property() { Id = SonarProperties.HostUrl, Value = "http://myserver" }, new Property() { Id = "file.only", Value = "file value" } }; var settingsFilePath = Path.Combine(analysisDir, "settings.txt"); fileProperties.Save(settingsFilePath); var fileProvider = FilePropertyProvider.Load(settingsFilePath); var args = new ProcessedArgs("key", "name", "version", "organization", false, EmptyPropertyProvider.Instance, fileProvider, EmptyPropertyProvider.Instance, logger); var settings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(analysisDir); Directory.CreateDirectory(settings.SonarConfigDirectory); // config directory needs to exist // Act var actualConfig = AnalysisConfigGenerator.GenerateFile(args, settings, new Dictionary <string, string>(), new List <AnalyzerSettings>(), new MockSonarQubeServer(), logger); // Assert AssertConfigFileExists(actualConfig); logger.AssertErrorsLogged(0); logger.AssertWarningsLogged(0); var actualSettingsFilePath = actualConfig.GetSettingsFilePath(); actualSettingsFilePath.Should().Be(settingsFilePath, "Unexpected settings file path"); // Check the file setting value do not appear in the config file AssertFileDoesNotContainText(actualConfig.FileName, "file.only"); actualConfig.SourcesDirectory.Should().Be(settings.SourcesDirectory); actualConfig.SonarScannerWorkingDirectory.Should().Be(settings.SonarScannerWorkingDirectory); AssertExpectedLocalSetting(SonarProperties.Organization, "organization", actualConfig); }
public bool Initialise(AnalysisConfig config, TeamBuildSettings settings, ILogger logger) { if (settings == null) { throw new ArgumentNullException("settings"); } this.TryCreateCoverageReportProcessor(settings); this.initialisedSuccesfully = (this.processor != null && this.processor.Initialise(config, settings, logger)); return(this.initialisedSuccesfully); }
/// <summary> /// Factory method to create a coverage report processor for the current build environment. /// </summary> private void TryCreateCoverageReportProcessor(TeamBuildSettings settings) { if (settings.BuildEnvironment == BuildEnvironment.TeamBuild) { this.processor = new BuildVNextCoverageReportProcessor(); } else if (settings.BuildEnvironment == BuildEnvironment.LegacyTeamBuild && !TeamBuildSettings.SkipLegacyCodeCoverageProcessing) { this.processor = new TfsLegacyCoverageReportProcessor(); } }
public void GenerateFile_WhenLoggerNull_ThrowArgumentNullException() { // Arrange var analysisDir = TestUtils.CreateTestSpecificFolder(TestContext); var tbSettings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(analysisDir); Action act = () => AnalysisConfigGenerator.GenerateFile(new ProcessedArgs("key", "name", "version", "org", false, EmptyPropertyProvider.Instance, EmptyPropertyProvider.Instance, EmptyPropertyProvider.Instance), tbSettings, new Dictionary <string, string>(), new List <AnalyzerSettings>(), new MockSonarQubeServer(), null); // Act & Assert act.Should().ThrowExactly <ArgumentNullException>().And.ParamName.Should().Be("logger"); }
public PostProcTestContext(TestContext testContext) { this.Config = new AnalysisConfig(); this.settings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(testContext.DeploymentDirectory); this.logger = new TestLogger(); this.codeCoverage = new MockCodeCoverageProcessor(); this.runner = new MockSonarRunner(); this.reportBuilder = new MockSummaryReportBuilder(); this.codeCoverage.InitialiseValueToReturn = true; this.codeCoverage.ProcessValueToReturn = true; }
private static void CheckExpectedSettings(TeamBuildSettings actual, BuildEnvironment expectedEnvironment, string expectedDir, string expectedBuildUri, string expectedCollectionUri) { Assert.IsNotNull(actual, "Returned settings should never be null"); Assert.AreEqual(expectedEnvironment, actual.BuildEnvironment, "Unexpected build environment returned"); Assert.AreEqual(expectedDir, actual.BuildDirectory, "Unexpected build directory returned"); Assert.AreEqual(expectedBuildUri, actual.BuildUri, "Unexpected build uri returned"); Assert.AreEqual(expectedCollectionUri, actual.TfsUri, "Unexpected tfs uri returned"); // Check the calculated values Assert.AreEqual(Path.Combine(expectedDir, "sqtemp\\conf"), actual.SonarConfigDirectory, "Unexpected config dir"); Assert.AreEqual(Path.Combine(expectedDir, "sqtemp\\out"), actual.SonarOutputDirectory, "Unexpected output dir"); Assert.AreEqual(Path.Combine(expectedDir, "sqtemp\\conf", FileConstants.ConfigFileName), actual.AnalysisConfigFilePath, "Unexpected analysis file path"); }
/// <summary> /// Generates several files related to rulesets and roslyn analyzer assemblies. /// Active rules should never be empty, but depending on the server settings of repo keys, we might have no rules in the ruleset. /// In that case, this method returns null. /// </summary> public AnalyzerSettings SetupAnalyzer(TeamBuildSettings teamBuildSettings, IAnalysisPropertyProvider sonarProperties, IEnumerable <SonarRule> rules, string language) { this.teamBuildSettings = teamBuildSettings ?? throw new ArgumentNullException(nameof(teamBuildSettings)); this.sonarProperties = sonarProperties ?? throw new ArgumentNullException(nameof(sonarProperties)); _ = language ?? throw new ArgumentNullException(nameof(language)); _ = rules ?? throw new ArgumentNullException(nameof(rules)); var rulesetPath = CreateRuleSet(language, rules, false); var deactivatedRulesetPath = CreateRuleSet(language, rules, true); var analyzerPlugins = FetchAnalyzerPlugins(language, rules.Where(x => x.IsActive)); var additionalFiles = WriteAdditionalFiles(language, rules.Where(x => x.IsActive)); return(new AnalyzerSettings(language, rulesetPath, deactivatedRulesetPath, analyzerPlugins, additionalFiles)); }
public void AnalysisConfGen_FileProperties() { // File properties should not be copied to the file. // Instead, a pointer to the file should be created. // Arrange string analysisDir = TestUtils.CreateTestSpecificFolder(this.TestContext); TestLogger logger = new TestLogger(); // The set of file properties to supply AnalysisProperties fileProperties = new AnalysisProperties(); fileProperties.Add(new Property() { Id = SonarProperties.HostUrl, Value = "http://myserver" }); fileProperties.Add(new Property() { Id = "file.only", Value = "file value" }); string settingsFilePath = Path.Combine(analysisDir, "settings.txt"); fileProperties.Save(settingsFilePath); FilePropertyProvider fileProvider = FilePropertyProvider.Load(settingsFilePath); ProcessedArgs args = new ProcessedArgs("key", "name", "version", false, EmptyPropertyProvider.Instance, fileProvider); TeamBuildSettings settings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(analysisDir); Directory.CreateDirectory(settings.SonarConfigDirectory); // config directory needs to exist // Act AnalysisConfig actualConfig = AnalysisConfigGenerator.GenerateFile(args, settings, new Dictionary <string, string>(), logger); // Assert AssertConfigFileExists(actualConfig); logger.AssertErrorsLogged(0); logger.AssertWarningsLogged(0); string actualSettingsFilePath = actualConfig.GetSettingsFilePath(); Assert.AreEqual(settingsFilePath, actualSettingsFilePath, "Unexpected settings file path"); // Check the file setting value do not appear in the config file AssertFileDoesNotContainText(actualConfig.FileName, "file.only"); Assert.AreEqual(settings.SonarRunnerWorkingDirectory, actualConfig.SonarRunnerWorkingDirectory); }
public void RoslynConfig_SetupAnalyzers_ArgumentChecks() { // Arrange TestLogger logger = new TestLogger(); TeamBuildSettings settings = CreateSettings(this.TestContext.DeploymentDirectory); MockSonarQubeServer mockServer = CreateValidServer("valid.project", null, "valid.profile"); RoslynAnalyzerProvider testSubject = CreateTestSubject(logger); // Act and assert (branch can be null) AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzers(null, settings, "project", "branch")); AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzers(mockServer, null, "project", "branch")); AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzers(mockServer, settings, null, "branch")); }
public void TBSettings_NotTeamBuild() { // 0. Setup TestLogger logger; TeamBuildSettings settings; // 1. No environment vars set -> use the temp path using (EnvironmentVariableScope scope = new EnvironmentVariableScope()) { scope.SetVariable(TeamBuildSettings.EnvironmentVariables.SQAnalysisRootPath, null); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.IsInTeamBuild, null); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildDirectory_Legacy, null); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildDirectory_TFS2015, null); logger = new TestLogger(); settings = TeamBuildSettings.GetSettingsFromEnvironment(logger); // Check the environment properties CheckExpectedSettings(settings, BuildEnvironment.NotTeamBuild, Path.GetTempPath(), null, null); } // 2. SQ analysis dir set using (EnvironmentVariableScope scope = new EnvironmentVariableScope()) { scope.SetVariable(TeamBuildSettings.EnvironmentVariables.SQAnalysisRootPath, "d:\\sqdir"); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.IsInTeamBuild, null); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildDirectory_Legacy, null); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildDirectory_TFS2015, null); logger = new TestLogger(); settings = TeamBuildSettings.GetSettingsFromEnvironment(logger); CheckExpectedSettings(settings, BuildEnvironment.NotTeamBuild, "d:\\sqdir", null, null); } // 3. Some Team build settings provided, but not marked as in team build using (EnvironmentVariableScope scope = new EnvironmentVariableScope()) { scope.SetVariable(TeamBuildSettings.EnvironmentVariables.SQAnalysisRootPath, "x:\\a"); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.IsInTeamBuild, null); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildUri_Legacy, "build uri"); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.TfsCollectionUri_Legacy, "collection uri"); logger = new TestLogger(); settings = TeamBuildSettings.GetSettingsFromEnvironment(logger); CheckExpectedSettings(settings, BuildEnvironment.NotTeamBuild, "x:\\a", null, null); } }
public void RoslynConfig_NoActiveRules() { // Arrange TestLogger logger = new TestLogger(); IList <ActiveRule> activeRules = new List <ActiveRule>(); IList <string> inactiveRules = new List <string>(); string pluginKey = "csharp"; IDictionary <string, string> serverSettings = new Dictionary <string, string>(); TeamBuildSettings settings = CreateSettings(this.TestContext.DeploymentDirectory); RoslynAnalyzerProvider testSubject = CreateTestSubject(logger); // Act and assert Assert.IsNull(testSubject.SetupAnalyzer(settings, serverSettings, activeRules, inactiveRules, pluginKey)); }
public void SonarLint_ValidRuleset() { // Arrange string rootDir = CreateTestFolders(); TestLogger logger = new TestLogger(); TeamBuildSettings settings = CreateSettings(rootDir); MockSonarQubeServer mockServer = CreateValidServer("valid.project", "valid.profile"); // Act SonarLintAnalyzerProvider.SetupAnalyzers(mockServer, settings, "valid.project", logger); // Assert CheckRulesetExists(rootDir); CheckSonarLintBinariesExist(rootDir); }
/// <summary> /// Factory method to create a coverage report processor for the current build environment. /// TODO: replace with a general purpose pre- and post- processing extension mechanism. /// </summary> private static ICoverageReportProcessor TryCreateCoverageReportProcessor(TeamBuildSettings settings) { ICoverageReportProcessor processor = null; if (settings.BuildEnvironment == BuildEnvironment.TeamBuild) { processor = new BuildVNextCoverageReportProcessor(); } else if (settings.BuildEnvironment == BuildEnvironment.LegacyTeamBuild && !TeamBuildSettings.SkipLegacyCodeCoverageProcessing) { processor = new TfsLegacyCoverageReportProcessor(); } return(processor); }
public bool Execute(string[] args, AnalysisConfig config, TeamBuildSettings settings, ILogger logger) { if (args == null) { throw new ArgumentNullException("args"); } if (config == null) { throw new ArgumentNullException("config"); } if (settings == null) { throw new ArgumentNullException("settings"); } if (logger == null) { throw new ArgumentNullException("logger"); } IAnalysisPropertyProvider provider; if (!ArgumentProcessor.TryProcessArgs(args, logger, out provider)) { return(false); } logger.Verbosity = VerbosityCalculator.ComputeVerbosity(config.GetAnalysisSettings(true), logger); LogStartupSettings(config, settings, logger); if (!CheckEnvironmentConsistency(config, settings, logger)) { return(false); } // if initialisation fails a warning will have been logged at the source of the failure bool initialised = this.codeCoverageProcessor.Initialise(config, settings, logger); if (initialised && !this.codeCoverageProcessor.ProcessCoverageReports()) { // if processing fails, stop the workflow return(false); } ProjectInfoAnalysisResult result = InvokeSonarScanner(provider, config, logger); this.reportBuilder.GenerateReports(settings, config, result, logger); return(result.RanToCompletion); }
private bool FetchArgumentsAndRulesets(ProcessedArgs args, TeamBuildSettings settings, out IDictionary <string, string> serverSettings, out AnalyzerSettings analyzerSettings) { string hostUrl = args.GetSetting(SonarProperties.HostUrl); serverSettings = null; analyzerSettings = null; ISonarQubeServer server = this.factory.CreateSonarQubeServer(args, this.logger); try { this.logger.LogInfo(Resources.MSG_FetchingAnalysisConfiguration); // Respect sonar.branch setting if set string projectBranch = null; args.TryGetSetting(SonarProperties.ProjectBranch, out projectBranch); // Fetch the SonarQube project properties serverSettings = server.GetProperties(args.ProjectKey, projectBranch); // Generate the FxCop rulesets this.logger.LogInfo(Resources.MSG_GeneratingRulesets); GenerateFxCopRuleset(server, args.ProjectKey, projectBranch, "csharp", "cs", "fxcop", Path.Combine(settings.SonarConfigDirectory, FxCopCSharpRuleset)); GenerateFxCopRuleset(server, args.ProjectKey, projectBranch, "vbnet", "vbnet", "fxcop-vbnet", Path.Combine(settings.SonarConfigDirectory, FxCopVBNetRuleset)); IAnalyzerProvider analyzerProvider = this.factory.CreateAnalyzerProvider(this.logger); Debug.Assert(analyzerProvider != null, "Factory should not return null"); analyzerSettings = analyzerProvider.SetupAnalyzers(server, settings, args.ProjectKey, projectBranch); } catch (WebException ex) { if (Utilities.HandleHostUrlWebException(ex, hostUrl, this.logger)) { return(false); } throw; } finally { Utilities.SafeDispose(server); } return(true); }
public void TBSettings_NotTeamBuild() { // 0. Setup TestLogger logger; TeamBuildSettings settings; // 1. No environment vars set using (var scope = new EnvironmentVariableScope()) { scope.SetVariable(TeamBuildSettings.EnvironmentVariables.IsInTeamFoundationBuild, null); logger = new TestLogger(); settings = TeamBuildSettings.GetSettingsFromEnvironment(logger); // Check the environment properties CheckExpectedSettings( settings, BuildEnvironment.NotTeamBuild, Directory.GetCurrentDirectory(), null, null, null, null); } // 2. Some Team build settings provided, but not marked as in team build using (var scope = new EnvironmentVariableScope()) { scope.SetVariable(TeamBuildSettings.EnvironmentVariables.IsInTeamFoundationBuild, null); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildUri_Legacy, "build uri"); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.TfsCollectionUri_Legacy, "collection uri"); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildDirectory_Legacy, "should be ignored"); scope.SetVariable(TeamBuildSettings.EnvironmentVariables.BuildDirectory_TFS2015, "should be ignored"); logger = new TestLogger(); settings = TeamBuildSettings.GetSettingsFromEnvironment(logger); CheckExpectedSettings( settings, BuildEnvironment.NotTeamBuild, Directory.GetCurrentDirectory(), null, null, null, null); } }
public void PreProc_EmptySonarRunnerProperties() { // Checks the pre-processor creates a valid config file // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); string propertiesFile = CreateEmptyPropertiesFile(testDir); MockPropertiesFetcher mockPropertiesFetcher = new MockPropertiesFetcher(); MockRulesetGenerator mockRulesetGenerator = new MockRulesetGenerator(); TestLogger logger = new TestLogger(); string expectedConfigFileName; using (PreprocessTestUtils.CreateValidLegacyTeamBuildScope("tfs uri", "http://builduri", testDir)) { TeamBuildSettings settings = TeamBuildSettings.GetSettingsFromEnvironment(new ConsoleLogger()); Assert.IsNotNull(settings, "Test setup error: TFS environment variables have not been set correctly"); expectedConfigFileName = settings.AnalysisConfigFilePath; TeamBuildPreProcessor preProcessor = new TeamBuildPreProcessor(mockPropertiesFetcher, mockRulesetGenerator); // Act preProcessor.Execute(logger, "key", "name", "ver", propertiesFile); } // Assert Assert.IsTrue(File.Exists(expectedConfigFileName), "Config file does not exist: {0}", expectedConfigFileName); AnalysisConfig config = AnalysisConfig.Load(expectedConfigFileName); Assert.IsTrue(Directory.Exists(config.SonarOutputDir), "Output directory was not created: {0}", config.SonarOutputDir); Assert.IsTrue(Directory.Exists(config.SonarConfigDir), "Config directory was not created: {0}", config.SonarConfigDir); Assert.AreEqual("key", config.SonarProjectKey); Assert.AreEqual("name", config.SonarProjectName); Assert.AreEqual("ver", config.SonarProjectVersion); Assert.AreEqual("http://builduri", config.GetBuildUri()); Assert.AreEqual("tfs uri", config.GetTfsUri()); Assert.AreEqual(propertiesFile, config.SonarRunnerPropertiesPath); mockPropertiesFetcher.AssertFetchPropertiesCalled(); mockPropertiesFetcher.CheckFetcherArguments("http://localhost:9000", "key"); mockRulesetGenerator.AssertGenerateCalled(); mockRulesetGenerator.CheckGeneratorArguments("http://localhost:9000", "key"); }
public static int Execute(string[] args, ILogger logger) { try { /* Expected Arguments : * Method : 0 * SonarQubeAnalysisConfig.xml path : 1 * sonar-project.properties : 2 * ranToCompletion : 3 */ if (args.Length < 1) { logger.LogError("No argument found. Exiting..."); return(1); } CommandLineArgs commandLineArgs = new CommandLineArgs(logger); if (!commandLineArgs.ParseArguments(args)) { return(1); } var teamBuildSettings = TeamBuildSettings.GetSettingsFromEnvironment(logger); AnalysisConfig config = AnalysisConfig.Load(commandLineArgs.SonarQubeAnalysisConfigPath); var legacyTeamBuildFactory = new LegacyTeamBuildFactory(logger, config); switch (commandLineArgs.ProcessToExecute) { case Method.ConvertCoverage: ExecuteCoverageConverter(logger, config, legacyTeamBuildFactory, teamBuildSettings, commandLineArgs.SonarProjectPropertiesPath); break; case Method.SummaryReportBuilder: ExecuteReportBuilder(logger, config, legacyTeamBuildFactory, teamBuildSettings, commandLineArgs.RanToCompletion, commandLineArgs.SonarProjectPropertiesPath); break; } } catch (Exception ex) { logger.LogError("An exception occured while executing the process : " + ex.Message); logger.LogError(ex.StackTrace); } return(0); }
private bool DoExecute(ProcessedArgs args, ILogger logger) { if (args == null) { throw new ArgumentNullException("args"); } if (logger == null) { throw new ArgumentNullException("logger"); } logger.Verbosity = VerbosityCalculator.ComputeVerbosity(args.AggregateProperties, logger); InstallLoaderTargets(args, logger); TeamBuildSettings teamBuildSettings = TeamBuildSettings.GetSettingsFromEnvironment(logger); // We're checking the args and environment variables so we can report all // config errors to the user at once if (teamBuildSettings == null) { logger.LogError(Resources.ERROR_CannotPerformProcessing); return(false); } // Create the directories logger.LogDebug(Resources.MSG_CreatingFolders); if (!Utilities.TryEnsureEmptyDirectories(logger, teamBuildSettings.SonarConfigDirectory, teamBuildSettings.SonarOutputDirectory)) { return(false); } IDictionary <string, string> serverSettings; if (!FetchArgumentsAndRulesets(args, teamBuildSettings.SonarConfigDirectory, logger, out serverSettings)) { return(false); } AnalysisConfigGenerator.GenerateFile(args, teamBuildSettings, serverSettings, logger); return(true); }
private static void CheckExpectedSettings(TeamBuildSettings actual, BuildEnvironment expectedEnvironment, string expectedAnalysisDir, string expectedBuildUri, string expectedCollectionUri, string expectedBuildDir) { Assert.IsNotNull(actual, "Returned settings should never be null"); Assert.AreEqual(expectedEnvironment, actual.BuildEnvironment, "Unexpected build environment returned"); Assert.AreEqual(expectedAnalysisDir, actual.AnalysisBaseDirectory, "Unexpected analysis base directory returned"); Assert.AreEqual(expectedBuildDir, actual.BuildDirectory, "Unexpected build directory returned"); Assert.AreEqual(expectedBuildUri, actual.BuildUri, "Unexpected build uri returned"); Assert.AreEqual(expectedCollectionUri, actual.TfsUri, "Unexpected tfs uri returned"); // Check the calculated values Assert.AreEqual(Path.Combine(expectedAnalysisDir, "conf"), actual.SonarConfigDirectory, "Unexpected config dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "out"), actual.SonarOutputDirectory, "Unexpected output dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "bin"), actual.SonarBinDirectory, "Unexpected bin dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "conf", FileConstants.ConfigFileName), actual.AnalysisConfigFilePath, "Unexpected analysis file path"); Assert.AreEqual(Directory.GetParent(expectedAnalysisDir).FullName, actual.SonarRunnerWorkingDirectory, "Unexpected sonar-runner working dir"); }
private static void FetchBinaries(ISonarQubeServer server, TeamBuildSettings settings, ILogger logger) { // For the 1.1 release of the runner/scanner, we are hard-coding support for a single known version // of SonarLint. The required assemblies will be packaged in the "static" folder of the jar (in the // same way that the SonarQube.MSBuild.Runner.Implementation.zip file is). logger.LogDebug(Resources.SLAP_FetchingSonarLintAnalyzer); if (server.TryDownloadEmbeddedFile(CSharpPluginKey, EmbeddedSonarLintZipFileName, settings.SonarBinDirectory)) { string filePath = Path.Combine(settings.SonarBinDirectory, EmbeddedSonarLintZipFileName); logger.LogDebug(Resources.MSG_ExtractingFiles, settings.SonarBinDirectory); ZipFile.ExtractToDirectory(filePath, settings.SonarBinDirectory); } else { logger.LogDebug(Resources.SLAP_AnalyzerNotFound); } }
private bool DoExecute(ProcessedArgs localSettings) { Debug.Assert(localSettings != null, "Not expecting the process arguments to be null"); this.logger.Verbosity = VerbosityCalculator.ComputeVerbosity(localSettings.AggregateProperties, this.logger); logger.ResumeOutput(); InstallLoaderTargets(localSettings); TeamBuildSettings teamBuildSettings = TeamBuildSettings.GetSettingsFromEnvironment(this.logger); // We're checking the args and environment variables so we can report all config errors to the user at once if (teamBuildSettings == null) { this.logger.LogError(Resources.ERROR_CannotPerformProcessing); return(false); } // Create the directories this.logger.LogDebug(Resources.MSG_CreatingFolders); if (!Utilities.TryEnsureEmptyDirectories(this.logger, teamBuildSettings.SonarConfigDirectory, teamBuildSettings.SonarOutputDirectory)) { return(false); } ISonarQubeServer server = this.factory.CreateSonarQubeServer(localSettings, this.logger); IDictionary <string, string> serverSettings; List <AnalyzerSettings> analyzersSettings; if (!FetchArgumentsAndRulesets(server, localSettings, teamBuildSettings, out serverSettings, out analyzersSettings)) { return(false); } Debug.Assert(analyzersSettings != null, "Not expecting the analyzers settings to be null"); // analyzerSettings can be empty AnalysisConfigGenerator.GenerateFile(localSettings, teamBuildSettings, serverSettings, analyzersSettings, this.logger); return(true); }
public PostProcTestContext(TestContext testContext) { Config = new AnalysisConfig(); Settings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(TestUtils.CreateTestSpecificFolderWithSubPaths(testContext)); Logger = new TestLogger(); TfsProcessor = new MockTfsProcessor(Logger); Scanner = new MockSonarScanner(Logger); TargetsUninstaller = new Mock <ITargetsUninstaller>(); var callCount = 0; TargetsUninstaller .Setup(m => m.UninstallTargets()) .Callback(() => { // Verify that the method was called maximum once callCount.Should().Be(0, "Method should be called exactly once"); callCount++; }); }
public void RoslynConfig_SetupAnalyzers_ArgumentChecks() { // Arrange TestLogger logger = new TestLogger(); IList <ActiveRule> activeRules = new List <ActiveRule>(); IList <string> inactiveRules = new List <string>(); string pluginKey = RoslynAnalyzerProvider.CSharpPluginKey; IDictionary <string, string> serverSettings = new Dictionary <string, string>(); TeamBuildSettings settings = CreateSettings(this.TestContext.DeploymentDirectory); RoslynAnalyzerProvider testSubject = CreateTestSubject(logger); // Act and assert AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzer(null, serverSettings, activeRules, inactiveRules, pluginKey)); AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzer(settings, null, activeRules, inactiveRules, pluginKey)); AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzer(settings, serverSettings, null, inactiveRules, pluginKey)); AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzer(settings, serverSettings, activeRules, null, pluginKey)); AssertException.Expects <ArgumentNullException>(() => testSubject.SetupAnalyzer(settings, serverSettings, activeRules, inactiveRules, null)); }
public void SonarLint_PluginNotInstalled() { // Arrange string rootDir = CreateTestFolders(); TestLogger logger = new TestLogger(); TeamBuildSettings settings = CreateSettings(rootDir); MockSonarQubeServer mockServer = CreateValidServer("valid.project", "valid.profile"); mockServer.Data.InstalledPlugins.Remove(SonarLintAnalyzerProvider.CSharpPluginKey); // Act SonarLintAnalyzerProvider.SetupAnalyzers(mockServer, settings, "valid.project", logger); // Assert CheckRulesetDoesNotExist(rootDir); CheckBinariesDoNotExist(rootDir); logger.AssertErrorsLogged(0); }
public void SonarLint_InvalidRuleset() { // Arrange string rootDir = CreateTestFolders(); TestLogger logger = new TestLogger(); TeamBuildSettings settings = CreateSettings(rootDir); MockSonarQubeServer mockServer = CreateValidServer("valid.project", "valid.profile"); mockServer.Data.FindProfile("valid.profile", SonarLintAnalyzerProvider.CSharpLanguage).SetExport(SonarLintAnalyzerProvider.SonarLintProfileFormatName, "not a ruleset"); // Act SonarLintAnalyzerProvider.SetupAnalyzers(mockServer, settings, "valid.project", logger); // Assert CheckRulesetDoesNotExist(rootDir); CheckBinariesDoNotExist(rootDir); logger.AssertErrorsLogged(1); // Expecting an error in this case: the profile exists but couldn't be retrieved }
public void SonarLint_ProjectNotInProfile() { // Arrange string rootDir = CreateTestFolders(); TestLogger logger = new TestLogger(); TeamBuildSettings settings = CreateSettings(rootDir); MockSonarQubeServer mockServer = CreateValidServer("valid.project", "valid.profile"); mockServer.Data.FindProfile("valid.profile", SonarLintAnalyzerProvider.CSharpLanguage).ActiveRules.Clear(); // Act SonarLintAnalyzerProvider.SetupAnalyzers(mockServer, settings, "unknown.project", logger); // Assert CheckRulesetDoesNotExist(rootDir); CheckBinariesDoNotExist(rootDir); logger.AssertErrorsLogged(0); }
private static void CheckExpectedSettings(TeamBuildSettings actual, BuildEnvironment expectedEnvironment, string expectedAnalysisDir, string expectedBuildUri, string expectedCollectionUri, string expectedBuildDir) { Assert.IsNotNull(actual, "Returned settings should never be null"); Assert.AreEqual(expectedEnvironment, actual.BuildEnvironment, "Unexpected build environment returned"); Assert.AreEqual(expectedAnalysisDir, actual.AnalysisBaseDirectory, "Unexpected analysis base directory returned"); Assert.AreEqual(expectedBuildDir, actual.BuildDirectory, "Unexpected build directory returned"); Assert.AreEqual(expectedBuildUri, actual.BuildUri, "Unexpected build uri returned"); Assert.AreEqual(expectedCollectionUri, actual.TfsUri, "Unexpected tfs uri returned"); // Check the calculated values Assert.AreEqual(Path.Combine(expectedAnalysisDir, "conf"), actual.SonarConfigDirectory, "Unexpected config dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "out"), actual.SonarOutputDirectory, "Unexpected output dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "bin"), actual.SonarBinDirectory, "Unexpected bin dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "conf", FileConstants.ConfigFileName), actual.AnalysisConfigFilePath, "Unexpected analysis file path"); }
private static void CheckExpectedSettings( TeamBuildSettings actual, BuildEnvironment expectedEnvironment, string expectedAnalysisDir, string expectedBuildUri, string expectedCollectionUri, string expectedBuildDir, string expectedSourcesDir) { Assert.IsNotNull(actual, "Returned settings should never be null"); Assert.AreEqual(expectedEnvironment, actual.BuildEnvironment, "Unexpected build environment returned"); Assert.AreEqual(expectedAnalysisDir, actual.AnalysisBaseDirectory, "Unexpected analysis base directory returned"); Assert.AreEqual(expectedBuildDir, actual.BuildDirectory, "Unexpected build directory returned"); Assert.AreEqual(expectedBuildUri, actual.BuildUri, "Unexpected build uri returned"); Assert.AreEqual(expectedCollectionUri, actual.TfsUri, "Unexpected tfs uri returned"); if (actual.BuildEnvironment == BuildEnvironment.NotTeamBuild) { Assert.IsNull(actual.SourcesDirectory, "Should not be able to set the sources directory"); } else { Assert.AreEqual(expectedSourcesDir, actual.SourcesDirectory, "Unexpected sources directory returned"); } // Check the calculated values Assert.AreEqual(Path.Combine(expectedAnalysisDir, "conf"), actual.SonarConfigDirectory, "Unexpected config dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "out"), actual.SonarOutputDirectory, "Unexpected output dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "bin"), actual.SonarBinDirectory, "Unexpected bin dir"); Assert.AreEqual(Path.Combine(expectedAnalysisDir, "conf", FileConstants.ConfigFileName), actual.AnalysisConfigFilePath, "Unexpected analysis file path"); Assert.AreEqual(Directory.GetParent(expectedAnalysisDir).FullName, actual.SonarRunnerWorkingDirectory, "Unexpected sonar-runner working dir"); }