public void PIRB_WriteSummaryReport_InvalidArgs_Throws() { var analysisConfig = new AnalysisConfig(); var analysisResult = new ProjectInfoAnalysisResult(); var loggerMock = new Mock<ILogger>().Object; // 1. Invalid analysis config Action op = () => ProjectInfoReportBuilder.WriteSummaryReport(null, analysisResult, loggerMock); op.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("config"); // 2. Invalid result op = () => ProjectInfoReportBuilder.WriteSummaryReport(analysisConfig, null, loggerMock); op.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("result"); // 3. Invalid logger op = () => ProjectInfoReportBuilder.WriteSummaryReport(analysisConfig, analysisResult, null); op.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("logger"); }
public void FileGen_ValidFiles_WithFixableSarif() { // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); // SARIF file path string testSarifPath = Path.Combine(testDir, "testSarif.json"); // Create SARIF report path property and add it to the project info AnalysisProperties projectSettings = new AnalysisProperties { new Property() { Id = PropertiesFileGenerator.ReportFileCsharpPropertyKey, Value = testSarifPath } }; Guid projectGuid = Guid.NewGuid(); CreateProjectWithFiles("withFiles1", testDir, projectGuid, true, projectSettings); TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); // Mock SARIF fixer simulates fixable SARIF with fixed name string returnPathDir = Path.GetDirectoryName(testSarifPath); string returnPathFileName = Path.GetFileNameWithoutExtension(testSarifPath) + RoslynV1SarifFixer.FixedFileSuffix + Path.GetExtension(testSarifPath); MockRoslynV1SarifFixer mockSarifFixer = new MockRoslynV1SarifFixer(returnPathFileName); string escapedMockReturnPath = mockSarifFixer.ReturnVal.Replace(@"\", @"\\"); // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger, mockSarifFixer); // Assert Assert.AreEqual(1, mockSarifFixer.CallCount); Assert.AreEqual(RoslynV1SarifFixer.CSharpLanguage, mockSarifFixer.LastLanguage); // Fixable SARIF -> new file saved -> changed property SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingExists(projectGuid.ToString().ToUpper() + "." + PropertiesFileGenerator.ReportFileCsharpPropertyKey, escapedMockReturnPath); }
public void FileGen_SharedFiles_CaseInsensitive() { // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); // Create 2 uuids and order them so that test is reproducible Guid[] uuids = new Guid[] { Guid.NewGuid(), Guid.NewGuid() }; Array.Sort(uuids); string project1Dir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "project1"); string project1Path = Path.Combine(project1Dir, "project1.proj"); string project1Info = CreateProjectInfoInSubDir(testDir, "projectName1", uuids[0], ProjectType.Product, false, project1Path, "UTF-8"); // not excluded var sharedFile = Path.Combine(testDir, "contentFile.txt"); var sharedFileDifferentCase = Path.Combine(testDir, "ContentFile.TXT"); CreateEmptyFile(testDir, "contentFile.txt"); // Reference shared file, but not under the project directory string contentFileList1 = CreateFile(project1Dir, "contentList.txt", sharedFile); AddAnalysisResult(project1Info, AnalysisType.FilesToAnalyze, contentFileList1); string project2Dir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "project2"); string project2Path = Path.Combine(project2Dir, "project2.proj"); string project2Info = CreateProjectInfoInSubDir(testDir, "projectName2", uuids[1], ProjectType.Product, false, project2Path, "UTF-8"); // not excluded // Reference shared file, but not under the project directory string contentFileList2 = CreateFile(project2Dir, "contentList.txt", sharedFileDifferentCase); AddAnalysisResult(project2Info, AnalysisType.FilesToAnalyze, contentFileList2); TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger); // Assert SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingExists("sonar.projectBaseDir", testDir); // First one wins provider.AssertSettingExists("sonar.sources", sharedFile); }
public void FileGen_VSBootstrapperIsDisabled_OverrideUserSettings_SameValue() { // Arrange TestLogger logger = new TestLogger(); Property bootstrapperProperty = new Property() { Id = PropertiesFileGenerator.VSBootstrapperPropertyKey, Value = "false" }; // Act ProjectInfoAnalysisResult result = ExecuteAndCheckSucceeds("disableBootstrapperSame", logger, bootstrapperProperty); // Assert SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingExists(PropertiesFileGenerator.VSBootstrapperPropertyKey, "false"); logger.AssertSingleDebugMessageExists(PropertiesFileGenerator.VSBootstrapperPropertyKey); logger.AssertWarningsLogged(0); // not expecting a warning if the user has supplied the value we want }
public void FileGen_ValidFiles() { // Only non-excluded projects with files to analyse should be marked as valid // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); string projectWithoutFiles = CreateProjectInfoInSubDir(testDir, "withoutFiles", Guid.NewGuid(), ProjectType.Product, false, null); // not excluded string projectWithContentDir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "projectWithContent"); string contentProjectPath = Path.Combine(projectWithContentDir, "contentProject.proj"); string contentProjectInfo = CreateProjectInfoInSubDir(testDir, "withContentFiles", Guid.NewGuid(), ProjectType.Product, false, contentProjectPath); // not excluded string managedProjectDir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "managedProject"); string managedProjectPath = Path.Combine(managedProjectDir, "managedProject.proj"); string managedProjectInfo = CreateProjectInfoInSubDir(testDir, "withManagedFiles", Guid.NewGuid(), ProjectType.Product, false, managedProjectPath); // not excluded // Create the content files under the relevant project directories string contentFile = CreateEmptyFile(projectWithContentDir, "contentFile1.txt"); string contentFileList = CreateFile(projectWithContentDir, "contentList.txt", contentFile); AddAnalysisResult(contentProjectInfo, AnalysisType.ContentFiles, contentFileList); string managedFile = CreateEmptyFile(managedProjectDir, "managedFile1.cs"); string managedFileList = CreateFile(managedProjectDir, "managedList.txt", managedFile); AddAnalysisResult(managedProjectInfo, AnalysisType.ManagedCompilerInputs, managedFileList); TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger); // Assert AssertExpectedStatus("withoutFiles", ProjectInfoValidity.NoFilesToAnalyze, result); AssertExpectedStatus("withContentFiles", ProjectInfoValidity.Valid, result); AssertExpectedStatus("withManagedFiles", ProjectInfoValidity.Valid, result); AssertExpectedProjectCount(3, result); // One valid project info file -> file created AssertPropertiesFilesCreated(result, logger); }
public void FileGen_SharedFiles_BelongToAnotherProject() { // Shared files that belong to another project should NOT be attached to the root project // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); string project1Dir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "project1"); string project1Path = Path.Combine(project1Dir, "project1.proj"); Guid project1Guid = Guid.NewGuid(); string project1Info = CreateProjectInfoInSubDir(testDir, "projectName1", project1Guid, ProjectType.Product, false, project1Path, "UTF-8"); // not excluded var fileInProject1 = Path.Combine(project1Dir, "contentFile.txt"); CreateEmptyFile(project1Dir, "contentFile.txt"); // Reference shared file, but not under the project directory string contentFileList1 = CreateFile(project1Dir, "contentList.txt", fileInProject1); AddAnalysisResult(project1Info, AnalysisType.FilesToAnalyze, contentFileList1); string project2Dir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "project2"); string project2Path = Path.Combine(project2Dir, "project2.proj"); string project2Info = CreateProjectInfoInSubDir(testDir, "projectName2", Guid.NewGuid(), ProjectType.Product, false, project2Path, "UTF-8"); // not excluded // Reference shared file, but not under the project directory string contentFileList2 = CreateFile(project2Dir, "contentList.txt", fileInProject1); AddAnalysisResult(project2Info, AnalysisType.FilesToAnalyze, contentFileList2); TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger); // Assert SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingExists("sonar.projectBaseDir", testDir); provider.AssertSettingDoesNotExist("sonar.sources"); provider.AssertSettingExists(project1Guid.ToString().ToUpper() + ".sonar.sources", fileInProject1); }
private static void UpdateTeamBuildSummary(AnalysisConfig config, ProjectInfoAnalysisResult result, ILogger logger) { logger.LogMessage(Resources.Report_UpdatingTeamBuildSummary); int skippedProjectCount = GetProjectsByStatus(result, ProjectInfoValidity.NoFilesToAnalyze).Count(); int invalidProjectCount = GetProjectsByStatus(result, ProjectInfoValidity.InvalidGuid).Count(); invalidProjectCount += GetProjectsByStatus(result, ProjectInfoValidity.DuplicateGuid).Count(); int excludedProjectCount = GetProjectsByStatus(result, ProjectInfoValidity.ExcludeFlagSet).Count(); IEnumerable <ProjectInfo> validProjects = GetProjectsByStatus(result, ProjectInfoValidity.Valid); int productProjectCount = validProjects.Count(p => p.ProjectType == ProjectType.Product); int testProjectCount = validProjects.Count(p => p.ProjectType == ProjectType.Test); using (BuildSummaryLogger summaryLogger = new BuildSummaryLogger(config.GetTfsUri(), config.GetBuildUri())) { string projectDescription = string.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.Report_SonarQubeProjectDescription, config.SonarProjectName, config.SonarProjectKey, config.SonarProjectVersion); // Add a link to SonarQube dashboard if analysis succeeded Debug.Assert(config.SonarRunnerPropertiesPath != null, "Not expecting the sonar-runner properties path to be null"); if (config.SonarRunnerPropertiesPath != null && result.RanToCompletion) { ISonarPropertyProvider propertyProvider = new FilePropertiesProvider(config.SonarRunnerPropertiesPath); string hostUrl = propertyProvider.GetProperty(SonarProperties.HostUrl).TrimEnd('/'); string sonarUrl = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/dashboard/index/{1}", hostUrl, config.SonarProjectKey); summaryLogger.WriteMessage(Resources.Report_AnalysisSucceeded, projectDescription, sonarUrl); } if (!result.RanToCompletion) { summaryLogger.WriteMessage(Resources.Report_AnalysisFailed, projectDescription); } summaryLogger.WriteMessage(Resources.Report_ProductAndTestMessage, productProjectCount, testProjectCount); summaryLogger.WriteMessage(Resources.Report_InvalidSkippedAndExcludedMessage, invalidProjectCount, skippedProjectCount, excludedProjectCount); } }
public void FileGen_VSBootstrapperIsDisabled_OverrideUserSettings_DifferentValue() { // 0. Arrange TestLogger logger = new TestLogger(); // Try to explicitly enable the setting Property bootstrapperProperty = new Property() { Id = PropertiesFileGenerator.VSBootstrapperPropertyKey, Value = "true" }; // Act ProjectInfoAnalysisResult result = ExecuteAndCheckSucceeds("disableBootstrapperDiff", logger, bootstrapperProperty); // Assert SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingExists(PropertiesFileGenerator.VSBootstrapperPropertyKey, "false"); logger.AssertSingleWarningExists(PropertiesFileGenerator.VSBootstrapperPropertyKey); }
public void FileGen_ValidFiles_WithUnfixableSarif() { // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); // SARIF file path string testSarifPath = Path.Combine(testDir, "testSarif.json"); string escapedSarifPath = testSarifPath.Replace(@"\", @"\\"); // Create SARIF report path property and add it to the project info AnalysisProperties projectSettings = new AnalysisProperties { new Property() { Id = PropertiesFileGenerator.ReportFileCsharpPropertyKey, Value = testSarifPath } }; Guid projectGuid = Guid.NewGuid(); CreateProjectWithFiles("withFiles1", testDir, projectGuid, true, projectSettings); TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); // Mock SARIF fixer simulated unfixable/absent file MockRoslynV1SarifFixer mockSarifFixer = new MockRoslynV1SarifFixer(null); // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger, mockSarifFixer); // Assert Assert.AreEqual(1, mockSarifFixer.CallCount); // One valid project info file -> file created AssertPropertiesFilesCreated(result, logger); // Unfixable SARIF -> cannot fix -> report file property removed SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingDoesNotExist(projectGuid.ToString().ToUpper() + "." + PropertiesFileGenerator.ReportFileCsharpPropertyKey); }
/// <summary> /// Creates a single new project valid project with dummy files and analysis config file with the specified local settings. /// Checks that a property file is created. /// </summary> private ProjectInfoAnalysisResult ExecuteAndCheckSucceeds(string projectName, TestLogger logger, params Property[] localSettings) { string analysisRootDir = TestUtils.CreateTestSpecificFolder(this.TestContext, projectName); CreateProjectWithFiles(projectName, analysisRootDir); AnalysisConfig config = CreateValidConfig(analysisRootDir); config.LocalSettings = new AnalysisProperties(); foreach (Property property in localSettings) { config.LocalSettings.Add(property); } // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger); // Assert AssertExpectedProjectCount(1, result); AssertPropertiesFilesCreated(result, logger); return(result); }
static int Main() { ILogger logger = new ConsoleLogger(includeTimestamp: true); TeamBuildSettings settings = TeamBuildSettings.GetSettingsFromEnvironment(logger); Debug.Assert(settings != null, "Settings should not be null"); AnalysisConfig config = GetAnalysisConfig(settings, logger); if (config == null) { logger.LogError(Resources.ERROR_MissingSettings); return(ErrorCode); } if (!CheckEnvironmentConsistency(config, settings, logger)) { return(ErrorCode); } ICoverageReportProcessor coverageReportProcessor = TryCreateCoverageReportProcessor(settings); // Handle code coverage reports if (!coverageReportProcessor.ProcessCoverageReports(config, settings, logger)) { return(ErrorCode); } ProjectInfoAnalysisResult result = InvokeSonarRunner(config, logger); // Write summary report if (settings.BuildEnvironment == BuildEnvironment.LegacyTeamBuild && !TeamBuildSettings.SkipLegacyCodeCoverageProcessing) { UpdateTeamBuildSummary(config, result, logger); } return(result.RanToCompletion ? SuccessCode : ErrorCode); }
public void FileGen_ValidFiles_WithAlreadyValidSarif() { // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); // SARIF file path string testSarifPath = Path.Combine(testDir, "testSarif.json"); // Create SARIF report path property and add it to the project info AnalysisProperties projectSettings = new AnalysisProperties { new Property() { Id = PropertiesFileGenerator.ReportFileCsharpPropertyKey, Value = testSarifPath } }; Guid projectGuid = Guid.NewGuid(); CreateProjectWithFiles("withFiles1", testDir, projectGuid, true, projectSettings); TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); // Mock SARIF fixer simulates already valid sarif MockRoslynV1SarifFixer mockSarifFixer = new MockRoslynV1SarifFixer(testSarifPath); string mockReturnPath = mockSarifFixer.ReturnVal; // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger, mockSarifFixer); // Assert Assert.AreEqual(1, mockSarifFixer.CallCount); // Already valid SARIF -> no change in file -> unchanged property SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingExists(projectGuid.ToString().ToUpper() + "." + PropertiesFileGenerator.ReportFileCsharpPropertyKey, mockReturnPath); }
public void SummaryReport_ReportIsGenerated() { // Arrange var hostUrl = "http://mySonarQube:9000"; var result = new ProjectInfoAnalysisResult(); var config = new AnalysisConfig() { SonarProjectKey = "Foo", SonarQubeHostUrl = hostUrl }; var settings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(TestContext.DeploymentDirectory); config.SonarOutputDir = TestContext.TestDeploymentDir; // this will be cleaned up by VS when there are too many results var expectedReportPath = Path.Combine(TestContext.TestDeploymentDir, SummaryReportBuilder.SummaryMdFilename); // Act var builder = new SummaryReportBuilder(); builder.GenerateReports(settings, config, result, new TestLogger()); // Assert Assert.IsTrue(File.Exists(expectedReportPath) && (new FileInfo(expectedReportPath)).Length > 0, "The report file cannot be found or is empty"); }
public void FileGen_ValidFiles_SourceEncoding_Provided() { // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); CreateProjectWithFiles("withFiles1", testDir); TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); config.LocalSettings = new AnalysisProperties(); config.LocalSettings.Add(new Property { Id = SonarProperties.SourceEncoding, Value = "test-encoding-here" }); // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger); // Assert var settingsFileContent = File.ReadAllText(result.FullPropertiesFilePath); Assert.IsTrue(settingsFileContent.Contains("sonar.sourceEncoding=test-encoding-here"), "Command line parameter 'sonar.sourceEncoding' is ignored."); }
private bool Execute(PostProcTestContext context, bool propertyWriteSucceeded, params string[] args) { var sonarProjectPropertiesValidator = new Mock <ISonarProjectPropertiesValidator>(); IEnumerable <string> expectedValue; sonarProjectPropertiesValidator .Setup(propValidator => propValidator.AreExistingSonarPropertiesFilesPresent(It.IsAny <string>(), It.IsAny <ICollection <ProjectData> >(), out expectedValue)).Returns(false); var proc = new MSBuildPostProcessor(context.Scanner, context.Logger, context.TargetsUninstaller.Object, context.TfsProcessor, sonarProjectPropertiesValidator.Object); var testDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, Guid.NewGuid().ToString()); var projectInfo = TestUtils.CreateProjectWithFiles(TestContext, "withFiles1", testDir); List <ProjectData> listOfProjects = new List <ProjectData>(); listOfProjects.Add(new ProjectData(ProjectInfo.Load(projectInfo))); IEnumerable <ProjectData> expectedListOfProjects = listOfProjects; var propertiesFileGenerator = Mock.Of <IPropertiesFileGenerator>(); Mock.Get(propertiesFileGenerator).Setup(m => m.TryWriteProperties(It.IsAny <PropertiesWriter>(), out expectedListOfProjects)).Returns(propertyWriteSucceeded); var projectInfoAnalysisResult = new ProjectInfoAnalysisResult(); projectInfoAnalysisResult.Projects.AddRange(listOfProjects); projectInfoAnalysisResult.RanToCompletion = true; projectInfoAnalysisResult.FullPropertiesFilePath = Path.Combine(testDir, "sonar-project.properties"); Mock.Get(propertiesFileGenerator).Setup(m => m.GenerateFile()).Returns(projectInfoAnalysisResult); proc.SetPropertiesFileGenerator(propertiesFileGenerator); var success = proc.Execute(args, context.Config, context.Settings); return(success); }
public void FileGen_DuplicateProjectIds() { // ProjectInfo files with duplicate ids should be ignored // Arrange - three files, all with the same Guid, one of which is excluded string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); Guid duplicateGuid = Guid.NewGuid(); CreateProjectInfoInSubDir(testDir, "duplicate1", duplicateGuid, ProjectType.Product, false, "c:\\abc\\duplicateProject1.proj"); // not excluded CreateProjectInfoInSubDir(testDir, "duplicate2", duplicateGuid, ProjectType.Test, false, "S:\\duplicateProject2.proj"); // not excluded CreateProjectInfoInSubDir(testDir, "excluded", duplicateGuid, ProjectType.Product, true, null); // excluded TestLogger logger = new TestLogger(); AnalysisConfig config = CreateValidConfig(testDir); // Act ProjectInfoAnalysisResult result = null; using (new AssertIgnoreScope()) // expecting the properties writer to assert { result = PropertiesFileGenerator.GenerateFile(config, logger); } // Assert AssertExpectedStatus("duplicate1", ProjectInfoValidity.DuplicateGuid, result); AssertExpectedStatus("duplicate2", ProjectInfoValidity.DuplicateGuid, result); AssertExpectedStatus("excluded", ProjectInfoValidity.ExcludeFlagSet, result); // Expecting excluded rather than duplicate AssertExpectedProjectCount(3, result); // No valid project info files -> file not generated AssertFailedToCreatePropertiesFiles(result, logger); logger.AssertWarningsLogged(2); // should be a warning for each project with a duplicate id logger.AssertSingleWarningExists(duplicateGuid.ToString(), "c:\\abc\\duplicateProject1.proj"); logger.AssertSingleWarningExists(duplicateGuid.ToString(), "S:\\duplicateProject2.proj"); }
public void SummaryReport_AllTypesOfProjects() { // Arrange var hostUrl = "http://mySonarQube:9000"; var result = new ProjectInfoAnalysisResult() { RanToCompletion = true }; var config = new AnalysisConfig() { SonarProjectKey = "", SonarQubeHostUrl = hostUrl }; AddProjectInfoToResult(result, ProjectInfoValidity.ExcludeFlagSet, type: ProjectType.Product, count: 4); AddProjectInfoToResult(result, ProjectInfoValidity.ExcludeFlagSet, type: ProjectType.Test, count: 1); AddProjectInfoToResult(result, ProjectInfoValidity.InvalidGuid, type: ProjectType.Product, count: 7); AddProjectInfoToResult(result, ProjectInfoValidity.InvalidGuid, type: ProjectType.Test, count: 8); AddProjectInfoToResult(result, ProjectInfoValidity.NoFilesToAnalyze, count: 11); AddProjectInfoToResult(result, ProjectInfoValidity.Valid, type: ProjectType.Product, count: 13); AddProjectInfoToResult(result, ProjectInfoValidity.Valid, type: ProjectType.Test, count: 17); AddProjectInfoToResult(result, ProjectInfoValidity.DuplicateGuid, type: ProjectType.Product, count: 5); AddProjectInfoToResult(result, ProjectInfoValidity.DuplicateGuid, type: ProjectType.Test, count: 3); // Act var summaryReportData = SummaryReportBuilder.CreateSummaryData(config, result); // Assert VerifySummaryReportData(summaryReportData, result, hostUrl, config); VerifySummaryProjectCounts( summaryReportData, expectedExcludedProjects: 5, // ExcludeFlagSet expectedInvalidProjects: 23, // InvalidGuid, DuplicateGuid expectedSkippedProjects: 11, // No files to analyze expectedProductProjects: 13, expectedTestProjects: 17); }
private static void AssertValidProjectsExist(ProjectInfoAnalysisResult actual) { IEnumerable <ProjectInfo> matches = actual.GetProjectsByStatus(ProjectInfoValidity.Valid); Assert.AreNotEqual(0, matches.Count(), "Expecting at least one valid ProjectInfo file to exist"); }
private static void AssertNoValidProjects(ProjectInfoAnalysisResult actual) { IEnumerable <ProjectInfo> matches = actual.GetProjectsByStatus(ProjectInfoValidity.Valid); Assert.AreEqual(0, matches.Count(), "Not expecting to find any valid ProjectInfo files"); }
private static void AssertExpectedStatus(string expectedProjectName, ProjectInfoValidity expectedStatus, ProjectInfoAnalysisResult actual) { IEnumerable <ProjectInfo> matches = actual.GetProjectsByStatus(expectedStatus).Where(p => p.ProjectName.Equals(expectedProjectName)); Assert.IsFalse(matches.Count() > 2, "ProjectName is reported more than once: {0}", expectedProjectName); Assert.AreEqual(1, matches.Count(), "ProjectInfo was not classified as expected. Project name: {0}, expected status: {1}", expectedProjectName, expectedStatus); }
public void GenerateReports(ITeamBuildSettings settings, AnalysisConfig config, ProjectInfoAnalysisResult result) { methodCalled.Should().BeFalse("Generate reports has already been called"); methodCalled = true; }
private static void AssertExpectedProjectCount(int expected, ProjectInfoAnalysisResult actual) { Assert.AreEqual(expected, actual.Projects.Count, "Unexpected number of projects in the result"); }
private static void AssertExpectedStatus(string expectedProjectName, ProjectInfoValidity expectedStatus, ProjectInfoAnalysisResult actual) { IEnumerable<ProjectInfo> matches = actual.GetProjectsByStatus(expectedStatus).Where(p => p.ProjectName.Equals(expectedProjectName)); Assert.IsFalse(matches.Count() > 2, "ProjectName is reported more than once: {0}", expectedProjectName); Assert.AreEqual(1, matches.Count(), "ProjectInfo was not classified as expected. Project name: {0}, expected status: {1}", expectedProjectName, expectedStatus); }
private static void AssertFailedToCreatePropertiesFiles(ProjectInfoAnalysisResult result, TestLogger logger) { Assert.IsNull(result.FullPropertiesFilePath, "Not expecting the sonar-runner properties file to have been set"); Assert.AreEqual(false, result.RanToCompletion, "Expecting the property file generation to have failed"); AssertNoValidProjects(result); logger.AssertErrorsLogged(); }
private void AssertPropertiesFilesCreated(ProjectInfoAnalysisResult result, TestLogger logger) { Assert.IsNotNull(result.FullPropertiesFilePath, "Expecting the sonar-runner properties file to have been set"); AssertValidProjectsExist(result); this.TestContext.AddResultFile(result.FullPropertiesFilePath); logger.AssertErrorsLogged(0); }
/// <summary> /// Generates summary reports for LegacyTeamBuild and for Build Vnext /// </summary> public void GenerateReports(ITeamBuildSettings settings, AnalysisConfig config, ProjectInfoAnalysisResult result, ILogger logger) { this.settings = settings ?? throw new ArgumentNullException("settings"); this.config = config ?? throw new ArgumentNullException("config"); this.result = result ?? throw new ArgumentNullException("result"); this.logger = logger ?? throw new ArgumentNullException("logger"); GenerateReports(); }
/// <summary> /// Generates summary reports for LegacyTeamBuild and for Build Vnext /// </summary> public void GenerateReports(TeamBuildSettings settings, AnalysisConfig config, ProjectInfoAnalysisResult result, ILogger logger) { if (settings == null) { throw new ArgumentNullException("settings"); } if (config == null) { throw new ArgumentNullException("config"); } if (result == null) { throw new ArgumentNullException("result"); } if (logger == null) { throw new ArgumentNullException("logger"); } this.settings = settings; this.config = config; this.result = result; this.logger = logger; this.GenerateReports(); }
private static IEnumerable <ProjectInfo> GetProjectsByStatus(ProjectInfoAnalysisResult result, ProjectInfoValidity status) { return(result.Projects.Where(p => p.Value == status).Select(p => p.Key)); }
public void GenerateReports(ITeamBuildSettings settings, AnalysisConfig config, ProjectInfoAnalysisResult result, ILogger logger) { Assert.IsFalse(methodCalled, "Generate reports has already been called"); this.methodCalled = true; }
/// <summary> /// Generates summary reports for LegacyTeamBuild and for Build Vnext /// </summary> public void GenerateReports(ITeamBuildSettings settings, AnalysisConfig config, ProjectInfoAnalysisResult result) { this.settings = settings ?? throw new ArgumentNullException(nameof(settings)); this.config = config ?? throw new ArgumentNullException(nameof(config)); this.result = result ?? throw new ArgumentNullException(nameof(result)); GenerateReports(); }
private static void AssertValidProjectsExist(ProjectInfoAnalysisResult actual) { IEnumerable<ProjectInfo> matches = actual.GetProjectsByStatus(ProjectInfoValidity.Valid); Assert.AreNotEqual(0, matches.Count(), "Expecting at least one valid ProjectInfo file to exist"); }
public void FileGen_AdditionalProperties() { // 0. Arrange string analysisRootDir = TestUtils.CreateTestSpecificFolder(this.TestContext); TestLogger logger = new TestLogger(); CreateProjectWithFiles("project1", analysisRootDir); AnalysisConfig config = CreateValidConfig(analysisRootDir); // Add additional properties config.LocalSettings = new AnalysisProperties(); config.LocalSettings.Add(new Property() { Id = "key1", Value = "value1" }); config.LocalSettings.Add(new Property() { Id = "key.2", Value = "value two" }); config.LocalSettings.Add(new Property() { Id = "key.3", Value = " " }); // Sensitive data should not be written config.LocalSettings.Add(new Property() { Id = SonarProperties.DbPassword, Value = "secret db pwd" }); config.LocalSettings.Add(new Property() { Id = SonarProperties.SonarPassword, Value = "secret pwd" }); // Server properties should not be added config.ServerSettings = new AnalysisProperties(); config.ServerSettings.Add(new Property() { Id = "server.key", Value = "should not be added" }); // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger); // Assert AssertExpectedProjectCount(1, result); // One valid project info file -> file created AssertPropertiesFilesCreated(result, logger); SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath); provider.AssertSettingExists("key1", "value1"); provider.AssertSettingExists("key.2", "value two"); provider.AssertSettingExists("key.3", " "); provider.AssertSettingDoesNotExist("server.key"); provider.AssertSettingDoesNotExist(SonarProperties.DbPassword); provider.AssertSettingDoesNotExist(SonarProperties.SonarPassword); }
private static void AssertNoValidProjects(ProjectInfoAnalysisResult actual) { IEnumerable<ProjectInfo> matches = actual.GetProjectsByStatus(ProjectInfoValidity.Valid); Assert.AreEqual(0, matches.Count(), "Not expecting to find any valid ProjectInfo files"); }
private static void AssertExpectedProjectCount(int expected, ProjectInfoAnalysisResult actual) { actual.Projects.Should().HaveCount(expected, "Unexpected number of projects in the result"); }
[TestMethod] //https://jira.codehaus.org/browse/SONARMSBRU-13: Analysis fails if a content file referenced in the MSBuild project does not exist public void FileGen_MissingFilesAreSkipped() { // Create project info with a managed file list and a content file list. // Each list refers to a file that does not exist on disk. // The missing files should not appear in the generated properties file. // Arrange string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext); string projectBaseDir = TestUtils.CreateTestSpecificFolder(TestContext, "Project1"); string projectFullPath = CreateEmptyFile(projectBaseDir, "project1.proj"); string existingManagedFile = CreateEmptyFile(projectBaseDir, "File1.cs"); string existingContentFile = CreateEmptyFile(projectBaseDir, "Content1.txt"); string missingManagedFile = Path.Combine(projectBaseDir, "MissingFile1.cs"); string missingContentFile = Path.Combine(projectBaseDir, "MissingContent1.txt"); ProjectInfo projectInfo = new ProjectInfo() { FullPath = projectFullPath, AnalysisResults = new List <AnalysisResult>(), IsExcluded = false, ProjectGuid = Guid.NewGuid(), ProjectName = "project1.proj", ProjectType = ProjectType.Product }; string analysisFileList = CreateFileList(projectBaseDir, "filesToAnalyze.txt", existingManagedFile, missingManagedFile, existingContentFile, missingContentFile); projectInfo.AddAnalyzerResult(AnalysisType.FilesToAnalyze, analysisFileList); string projectInfoDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "ProjectInfo1Dir"); string projectInfoFilePath = Path.Combine(projectInfoDir, FileConstants.ProjectInfoFileName); projectInfo.Save(projectInfoFilePath); TestLogger logger = new TestLogger(); AnalysisConfig config = new AnalysisConfig() { SonarProjectKey = "my_project_key", SonarProjectName = "my_project_name", SonarProjectVersion = "1.0", SonarOutputDir = testDir }; // Act ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger); string actual = File.ReadAllText(result.FullPropertiesFilePath); // Assert AssertFileIsReferenced(existingContentFile, actual); AssertFileIsReferenced(existingManagedFile, actual); AssertFileIsNotReferenced(missingContentFile, actual); AssertFileIsNotReferenced(missingManagedFile, actual); logger.AssertSingleWarningExists(missingManagedFile); logger.AssertSingleWarningExists(missingContentFile); }