Exemplo n.º 1
0
        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
            {
                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.");
        }
Exemplo n.º 2
0
        public void FileGen_ExcludedProjectsAreNotDuplicates()
        {
            // Excluded ProjectInfo files should be ignored when calculating duplicates

            // Arrange - two sub-directories, neither containing a ProjectInfo.xml
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            Guid duplicateGuid = Guid.NewGuid();

            CreateProjectInfoInSubDir(testDir, "excl1", duplicateGuid, ProjectType.Product, true, null);    // excluded
            CreateProjectInfoInSubDir(testDir, "excl2", duplicateGuid, ProjectType.Test, true, null);       // excluded
            CreateProjectInfoInSubDir(testDir, "notExcl", duplicateGuid, ProjectType.Product, false, null); // not excluded

            TestLogger     logger = new TestLogger();
            AnalysisConfig config = CreateValidConfig(testDir);

            // Act
            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);

            // Assert
            AssertExpectedStatus("excl1", ProjectInfoValidity.ExcludeFlagSet, result);
            AssertExpectedStatus("excl2", ProjectInfoValidity.ExcludeFlagSet, result);
            AssertExpectedStatus("notExcl", ProjectInfoValidity.NoFilesToAnalyze, result); // not "duplicate" since the duplicate guids are excluded
            AssertExpectedProjectCount(3, result);

            // One valid project info file -> file
            AssertFailedToCreatePropertiesFiles(result, logger);
            logger.AssertWarningsLogged(0); // not expecting any warnings
        }
Exemplo n.º 3
0
        public void FileGen_ValidFiles()
        {
            // Only non-excluded projects with files to analyse should be marked as valid

            // Arrange
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            CreateProjectInfoInSubDir(testDir, "withoutFiles", Guid.NewGuid(), ProjectType.Product, false, null); // not excluded
            CreateProjectWithFiles("withFiles1", testDir);
            CreateProjectWithFiles("withFiles2", testDir);

            TestLogger     logger = new TestLogger();
            AnalysisConfig config = CreateValidConfig(testDir);

            // Act
            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);

            // Assert
            AssertExpectedStatus("withoutFiles", ProjectInfoValidity.NoFilesToAnalyze, result);
            AssertExpectedStatus("withFiles1", ProjectInfoValidity.Valid, result);
            AssertExpectedStatus("withFiles2", ProjectInfoValidity.Valid, result);
            AssertExpectedProjectCount(3, result);

            // One valid project info file -> file created
            AssertPropertiesFilesCreated(result, logger);
        }
Exemplo n.º 4
0
        public void FileGen_FilesOutsideProjectPath()
        {
            // Files outside the project root should be ignored

            // Arrange
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            string projectDir  = TestUtils.EnsureTestSpecificFolder(this.TestContext, "project");
            string projectPath = Path.Combine(projectDir, "project.proj");
            string projectInfo = CreateProjectInfoInSubDir(testDir, "projectName", Guid.NewGuid(), ProjectType.Product, false, projectPath); // not excluded

            // Create a content file, but not under the project directory
            string contentFileList = CreateFile(projectDir, "contentList.txt", Path.Combine(testDir, "contentFile1.txt"));

            AddAnalysisResult(projectInfo, AnalysisType.FilesToAnalyze, contentFileList);

            TestLogger     logger = new TestLogger();
            AnalysisConfig config = CreateValidConfig(testDir);

            // Act
            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);

            // Assert
            AssertExpectedStatus("projectName", ProjectInfoValidity.NoFilesToAnalyze, result);
            AssertExpectedProjectCount(1, result);

            // No files -> project file not created
            AssertFailedToCreatePropertiesFiles(result, logger);
        }
Exemplo n.º 5
0
        public void FileGen_ValidFiles()
        {
            // Only non-excluded projects with files to analyze should be marked as valid

            // Arrange
            var testDir = TestUtils.CreateTestSpecificFolder(TestContext);

            CreateProjectInfoInSubDir(testDir, "withoutFiles", Guid.NewGuid(), ProjectType.Product, false, "c:\\abc\\withoutfile.proj", "UTF-8"); // not excluded
            CreateProjectWithFiles("withFiles1", testDir);
            CreateProjectWithFiles("withFiles2", testDir);

            var logger = new TestLogger();
            var config = CreateValidConfig(testDir);

            // Act
            var result = new PropertiesFileGenerator(config, logger).GenerateFile();

            // Assert
            AssertExpectedStatus("withoutFiles", ProjectInfoValidity.NoFilesToAnalyze, result);
            AssertExpectedStatus("withFiles1", ProjectInfoValidity.Valid, result);
            AssertExpectedStatus("withFiles2", ProjectInfoValidity.Valid, result);
            AssertExpectedProjectCount(3, result);

            // One valid project info file -> file created
            AssertPropertiesFilesCreated(result, logger);
        }
Exemplo n.º 6
0
        public void FileGen_NoProjectInfoFiles()
        {
            // Properties file should not be generated if there are no project info files.

            // Arrange - two sub-directories, neither containing a ProjectInfo.xml
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string subDir1 = TestUtils.EnsureTestSpecificFolder(this.TestContext, "dir1");
            string subDir2 = TestUtils.EnsureTestSpecificFolder(this.TestContext, "dir2");

            CreateEmptyFile(subDir1, "file1.txt");
            CreateEmptyFile(subDir2, "file2.txt");

            TestLogger     logger = new TestLogger();
            AnalysisConfig config = new AnalysisConfig()
            {
                SonarOutputDir = testDir
            };

            // Act
            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);

            // Assert
            AssertFailedToCreatePropertiesFiles(result, logger);
            AssertExpectedProjectCount(0, result);
        }
Exemplo n.º 7
0
        public void FileGen_TFS_Coverage_Trx_Are_Written()
        {
            // Arrange
            var testDir = TestUtils.CreateTestSpecificFolder(TestContext);

            CreateProjectWithFiles("withFiles1", testDir);

            var logger = new TestLogger();
            var config = CreateValidConfig(testDir);

            config.LocalSettings = new AnalysisProperties
            {
                new Property {
                    Id = SonarProperties.VsCoverageXmlReportsPaths, Value = "coverage-path"
                },
                new Property {
                    Id = SonarProperties.VsTestReportsPaths, Value = "trx-path"
                },
            };

            // Act
            var result = new PropertiesFileGenerator(config, logger).GenerateFile();

            // Assert
            var settingsFileContent = File.ReadAllText(result.FullPropertiesFilePath);

            Assert.IsTrue(settingsFileContent.Contains("sonar.cs.vscoveragexml.reportsPaths=coverage-path"));
            Assert.IsTrue(settingsFileContent.Contains("sonar.cs.vstest.reportsPaths=trx-path"));
        }
Exemplo n.º 8
0
        public void Different_Files_Per_Target_Are_Merged()
        {
            var guid = Guid.NewGuid();

            /*  Solution1/
             *      .sonarqube/
             *          conf/
             *          out/
             *              Project1_Debug/
             *                  ProjectInfo.xml
             *                  FilesToAnalyze.txt (file1.cs)
             *              Project1_Release/
             *                  ProjectInfo.xml
             *                  FilesToAnalyze.txt (file2.cs)
             *      Project1/
             *          file1.cs // included in Debug build
             *          file2.cs // included in Release build
             */

            // Arrange
            var solutionDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Solution1");

            var projectRoot = CreateProject(solutionDir, out List <string> files);

            var outDir = Path.Combine(solutionDir, ".sonarqube", "out");

            Directory.CreateDirectory(outDir);

            // Create two out folders for each configuration, the included files are different
            CreateProjectInfoAndFilesToAnalyze(guid, "Debug", files.Take(1), projectRoot, outDir);
            CreateProjectInfoAndFilesToAnalyze(guid, "Release", files.Skip(1), projectRoot, outDir);

            var logger = new TestLogger();
            var config = new AnalysisConfig()
            {
                SonarProjectKey     = guid.ToString(),
                SonarProjectName    = "project 1",
                SonarOutputDir      = outDir,
                SonarProjectVersion = "1.0",
            };

            var generator = new PropertiesFileGenerator(config, logger);

            // Act
            var result = generator.GenerateFile();

            // Assert
            AssertExpectedProjectCount(1, result);

            // One valid project info file -> file created
            AssertPropertiesFilesCreated(result, logger);
            var propertiesFileContent = File.ReadAllText(result.FullPropertiesFilePath);

            AssertFileIsReferenced(files[0], propertiesFileContent);
            AssertFileIsReferenced(files[1], propertiesFileContent);
        }
Exemplo n.º 9
0
        public void All_Targets_Ignored_Compilations_Are_Not_Included()
        {
            var guid = Guid.NewGuid();

            /*  Solution1/
             *      .sonarqube/
             *          conf/
             *          out/
             *              Project1_Debug/
             *                  ProjectInfo.xml
             *                  FilesToAnalyze.txt (file1.cs)
             *              Project1_Release/ // ignored, file2.cs should not be included in the properties file
             *                  ProjectInfo.xml
             *                  FilesToAnalyze.txt (file2.cs)
             *      Project1/
             *          file1.cs // included in Debug
             *          file2.cs // included in Release
             */

            // Arrange
            var solutionDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Solution1");

            var projectRoot = CreateProject(solutionDir, out List <string> files);

            var outDir = Path.Combine(solutionDir, ".sonarqube", "out");

            Directory.CreateDirectory(outDir);

            // Create two out folders for each configuration, the included files are different
            CreateProjectInfoAndFilesToAnalyze(guid, "Debug", files.Take(1), projectRoot, outDir, ignored: true);
            CreateProjectInfoAndFilesToAnalyze(guid, "Release", files.Skip(1), projectRoot, outDir, ignored: true);

            var logger = new TestLogger();
            var config = new AnalysisConfig()
            {
                SonarProjectKey     = guid.ToString(),
                SonarProjectName    = "project 1",
                SonarOutputDir      = outDir,
                SonarProjectVersion = "1.0",
            };

            var generator = new PropertiesFileGenerator(config, logger);

            // Act
            var result = generator.GenerateFile();

            // Assert
            AssertExpectedProjectCount(1, result);

            // No valid project info files -> properties not created
            AssertPropertiesFilesNotCreated(result, logger);
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        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);
        }
Exemplo n.º 12
0
        private void VerifyProjectBaseDir(string expectedValue, string teamBuildValue, string userValue, string[] projectPaths)
        {
            AnalysisConfig   config = new AnalysisConfig();
            PropertiesWriter writer = new PropertiesWriter(config);

            config.SonarOutputDir = TestSonarqubeOutputDir;

            config.SourcesDirectory = teamBuildValue;
            config.SetConfigValue(SonarProperties.ProjectBaseDir, userValue);

            TestLogger logger = new TestLogger();

            // Act
            string result = PropertiesFileGenerator.ComputeRootProjectBaseDir(config, projectPaths.Select(p => new ProjectInfo {
                FullPath = p, ProjectLanguage = ProjectLanguages.CSharp
            }));

            result.Should().Be(expectedValue);
        }
Exemplo n.º 13
0
        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);
        }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        public void FileGen_SharedFiles()
        {
            // Shared files should be attached to the root project

            // Arrange
            var testDir = TestUtils.CreateTestSpecificFolder(TestContext);

            var project1Dir  = TestUtils.EnsureTestSpecificFolder(TestContext, "project1");
            var project1Path = Path.Combine(project1Dir, "project1.proj");
            var project1Info = CreateProjectInfoInSubDir(testDir, "projectName1", Guid.NewGuid(), ProjectType.Product, false, project1Path, "UTF-8"); // not excluded
            var sharedFile   = Path.Combine(testDir, "contentFile.txt");

            CreateEmptyFile(testDir, "contentFile.txt");

            // Reference shared file, but not under the project directory
            var contentFileList1 = CreateFile(project1Dir, "contentList.txt", sharedFile);

            AddAnalysisResult(project1Info, AnalysisType.FilesToAnalyze, contentFileList1);

            var project2Dir  = TestUtils.EnsureTestSpecificFolder(TestContext, "project2");
            var project2Path = Path.Combine(project2Dir, "project2.proj");
            var project2Info = CreateProjectInfoInSubDir(testDir, "projectName2", Guid.NewGuid(), ProjectType.Product, false, project2Path, "UTF-8"); // not excluded

            // Reference shared file, but not under the project directory
            var contentFileList2 = CreateFile(project2Dir, "contentList.txt", sharedFile);

            AddAnalysisResult(project2Info, AnalysisType.FilesToAnalyze, contentFileList2);

            var logger = new TestLogger();
            var config = CreateValidConfig(testDir);

            // Act
            var result = new PropertiesFileGenerator(config, logger).GenerateFile();

            // Assert
            var provider = new SQPropertiesFileReader(result.FullPropertiesFilePath);

            provider.AssertSettingExists("sonar.projectBaseDir", testDir);
            provider.AssertSettingExists("sonar.sources", sharedFile);
        }
Exemplo n.º 17
0
        /// <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);
        }
Exemplo n.º 18
0
        public void E2E_ExcludedProjects()
        {
            // Project info should still be written for files with $(SonarQubeExclude) set to true
            // Arrange
            var context = CreateContext();
            var userDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "User");

            // Mix of analyzable and non-analyzable files
            var foo1            = context.CreateInputFile("foo1.txt");
            var code1           = context.CreateInputFile("code1.txt");
            var projectXml      = $@"
<PropertyGroup>
  <SonarQubeExclude>true</SonarQubeExclude>
  <ErrorLog>{userDir}\UserDefined.json</ErrorLog>
</PropertyGroup>

<ItemGroup>
  <Foo Include='{foo1}' />
  <Compile Include='{code1}' />
</ItemGroup>
";
            var projectFilePath = context.CreateProjectFile(projectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.DefaultBuild); // Build should succeed with warnings
            // Do not override user-provided value
            File.Exists(userDir + @"\UserDefined.json").Should().BeTrue();

            var actualStructure = context.ValidateAndLoadProjectStructure(checkAndLoadConfigFile: false);

            actualStructure.ProjectInfo.IsExcluded.Should().BeTrue();
            actualStructure.AssertConfigFileDoesNotExist(ExpectedProjectConfigFileName);
            actualStructure.AssertExpectedFileList("\\code1.txt");
            actualStructure.ProjectInfo.AnalysisSettings.Where(x => PropertiesFileGenerator.IsReportFilePaths(x.Id)).Should().BeEmpty();
        }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 20
0
        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");
        }
Exemplo n.º 21
0
        public void E2E_CustomErrorLogPath()
        {
            // Arrange
            var context         = CreateContext();
            var userDir         = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "User");
            var customErrorLog  = Path.Combine(userDir, "UserDefined.json");
            var projectXml      = $@"
<PropertyGroup>
  <ErrorLog>{customErrorLog}</ErrorLog>
</PropertyGroup>
";
            var projectFilePath = context.CreateProjectFile(projectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.DefaultBuild); // Build should succeed with warnings

            var actualStructure = context.ValidateAndLoadProjectStructure();

            actualStructure.ProjectInfo.ProjectType.Should().Be(ProjectType.Product);
            actualStructure.ProjectInfo.AnalysisSettings.Single(x => PropertiesFileGenerator.IsReportFilePaths(x.Id)).Value.Should().Be(customErrorLog);
        }
Exemplo n.º 22
0
        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);
        }
Exemplo n.º 23
0
        [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);
        }
Exemplo n.º 24
0
        public void ProjectData_Orders_AnalyzerOutPaths()
        {
            var guid = Guid.NewGuid();

            var projectInfos = new[]
            {
                new ProjectInfo
                {
                    ProjectGuid      = guid,
                    Configuration    = "Release",
                    Platform         = "anyCpu",
                    TargetFramework  = "netstandard2.0",
                    AnalysisSettings = new AnalysisProperties
                    {
                        new Property {
                            Id = ".analyzer.projectOutPath", Value = "1"
                        }
                    },
                },
                new ProjectInfo
                {
                    ProjectGuid      = guid,
                    Configuration    = "Debug",
                    Platform         = "anyCpu",
                    TargetFramework  = "netstandard2.0",
                    AnalysisSettings = new AnalysisProperties
                    {
                        new Property {
                            Id = ".analyzer.projectOutPath", Value = "2"
                        }
                    },
                },
                new ProjectInfo
                {
                    ProjectGuid      = guid,
                    Configuration    = "Debug",
                    Platform         = "x86",
                    TargetFramework  = "net46",
                    AnalysisSettings = new AnalysisProperties
                    {
                        new Property {
                            Id = ".analyzer.projectOutPath", Value = "3"
                        }
                    },
                },
                new ProjectInfo
                {
                    ProjectGuid      = guid,
                    Configuration    = "Debug",
                    Platform         = "x86",
                    TargetFramework  = "netstandard2.0",
                    AnalysisSettings = new AnalysisProperties
                    {
                        new Property {
                            Id = ".analyzer.projectOutPath", Value = "4"
                        }
                    },
                },
            };

            var analysisRootDir         = TestUtils.CreateTestSpecificFolder(TestContext, "project");
            var propertiesFileGenerator = new PropertiesFileGenerator(CreateValidConfig(analysisRootDir), new TestLogger());
            var result = propertiesFileGenerator.ToProjectData(projectInfos.GroupBy(p => p.ProjectGuid).First());

            CollectionAssert.AreEqual(new[] { "2", "3", "4", "1" }, result.AnalyzerOutPaths.ToList());
        }