Exemplo n.º 1
0
        private ProjectInfo ExecuteWriteProjectInfo(string projectFilePath, string rootOutputFolder, bool noWarningOrErrors = true)
        {
            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath,
                                                  // The "write" target depends on a couple of other targets having executed first to set properties appropriately
                                                  TargetConstants.SonarCategoriseProject,
                                                  TargetConstants.SonarCreateProjectSpecificDirs,
                                                  TargetConstants.SonarWriteFilesToAnalyze,
                                                  TargetConstants.SonarWriteProjectData);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.SonarCreateProjectSpecificDirs);
            result.AssertTargetSucceeded(TargetConstants.SonarWriteFilesToAnalyze);
            result.AssertTargetSucceeded(TargetConstants.SonarWriteProjectData);
            result.AssertTargetExecuted(TargetConstants.SonarWriteProjectData);

            if (noWarningOrErrors)
            {
                result.AssertNoWarningsOrErrors();
            }

            // Check expected project outputs
            Directory.EnumerateDirectories(rootOutputFolder).Should().HaveCount(1, "Only expecting one child directory to exist under the root analysis output folder");
            var projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectFilePath);

            return(projectInfo);
        }
Exemplo n.º 2
0
        public void E2E_FxCop_OutputFolderNotSet()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            // Don't set the output folder
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            // Clear all of the variables that could be used to look up the output path
            // (necessary so the test works correctly when run under TeamBuild on a machine
            // that has the integration targets installed)
            preImportProperties.SonarQubeOutputPath           = "";
            preImportProperties.TeamBuild2105BuildDirectory   = "";
            preImportProperties.TeamBuildLegacyBuildDirectory = "";

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // 1. No code analysis properties
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertTargetNotExecuted(TargetConstants.OverrideFxCopSettingsTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            AssertFxCopNotExecuted(logger);

            ProjectInfoAssertions.AssertNoProjectInfoFilesExists(rootOutputFolder);
        }
Exemplo n.º 3
0
        public void E2E_FxCop_TempFolderIsNotSet()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeOutputPath = rootOutputFolder;

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // 1. No code analysis properties
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertTargetNotExecuted(TargetConstants.OverrideFxCopSettingsTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            AssertFxCopNotExecuted(logger);

            ProjectInfoAssertions.AssertNoProjectInfoFilesExists(rootOutputFolder);
        }
Exemplo n.º 4
0
        public void WriteProjectInfoFile_FileCreated()
        {
            // Arrange
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            Guid projectGuid = Guid.NewGuid();

            WriteProjectInfoFile task = new WriteProjectInfoFile
            {
                FullProjectPath = "c:\\fullPath\\project.proj",
                ProjectLanguage = "cs",
                IsTest          = true,
                IsExcluded      = false,
                OutputFolder    = testFolder,
                ProjectGuid     = projectGuid.ToString("B"),
                ProjectName     = "MyProject"
            };

            task.ProjectLanguage = ProjectLanguages.CSharp;
            // No analysis results are supplied

            // Act
            ProjectInfo reloadedProjectInfo = ExecuteAndCheckSucceeds(task, testFolder);

            // Addition assertions
            ProjectInfoAssertions.AssertExpectedValues(
                "c:\\fullPath\\project.proj",
                ProjectLanguages.CSharp,
                ProjectType.Test,
                projectGuid,
                "MyProject",
                false, // IsExcluded
                reloadedProjectInfo);
        }
        /// <summary>
        /// Creates and builds a new Sonar-enabled project using the supplied descriptor.
        /// The method will check the build succeeded and that a single project output file was created.
        /// </summary>
        /// <returns>The full path of the project-specsific directory that was created during the build</returns>
        private string CreateAndBuildSonarProject(ProjectDescriptor descriptor, string rootOutputFolder, WellKnownProjectProperties preImportProperties)
        {
            ProjectRootElement projectRoot = BuildUtilities.CreateInitializedProjectRoot(this.TestContext, descriptor, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            // We expect the compiler to warn if there are no compiler inputs
            int expectedWarnings = (descriptor.ManagedSourceFiles == null || !descriptor.ManagedSourceFiles.Any()) ? 1 : 0;

            logger.AssertExpectedErrorCount(0);
            logger.AssertExpectedWarningCount(expectedWarnings);

            logger.AssertExpectedTargetOrdering(TargetConstants.CoreCompileTarget,
                                                TargetConstants.CalculateSonarQubeFileListsTarget,
                                                TargetConstants.DefaultBuildTarget,
                                                TargetConstants.WriteProjectDataTarget);

            // Check expected folder structure exists
            CheckRootOutputFolder(rootOutputFolder);

            // Check expected project outputs
            Assert.AreEqual(1, Directory.EnumerateDirectories(rootOutputFolder).Count(), "Only expecting one child directory to exist under the root analysis output folder");
            ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            return(Directory.EnumerateDirectories(rootOutputFolder).Single());
        }
Exemplo n.º 6
0
        /// <summary>
        /// Executes the WriteProjectInfoFile target in the the supplied project.
        /// The method will check the build succeeded and that a single project
        /// output file was created.
        /// </summary>
        /// <returns>The project info file that was created during the build</returns>
        private ProjectInfo ExecuteWriteProjectInfo(ProjectRootElement projectRoot, string rootOutputFolder, bool noWarningOrErrors = true)
        {
            projectRoot.Save();
            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger,
                                                             // The "write" target depends on a couple of other targets having executed first to set properties appropriately
                                                             TargetConstants.CategoriseProjectTarget,
                                                             TargetConstants.CalculateFilesToAnalyzeTarget,
                                                             TargetConstants.CreateProjectSpecificDirs,
                                                             TargetConstants.WriteProjectDataTarget);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.CalculateFilesToAnalyzeTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.CreateProjectSpecificDirs);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.WriteProjectDataTarget);

            logger.AssertTargetExecuted(TargetConstants.WriteProjectDataTarget);

            if (noWarningOrErrors)
            {
                logger.AssertNoWarningsOrErrors();
            }

            // Check expected project outputs
            Assert.AreEqual(1, Directory.EnumerateDirectories(rootOutputFolder).Count(), "Only expecting one child directory to exist under the root analysis output folder");
            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            return(projectInfo);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates and builds a new Sonar-enabled project using the supplied descriptor.
        /// The method will check the build succeeded and that a single project output file was created.
        /// </summary>
        /// <returns>The full path of the project-specific directory that was created during the build</returns>
        private string CreateAndBuildSonarProject(ProjectDescriptor descriptor, string rootOutputFolder, WellKnownProjectProperties preImportProperties)
        {
            var projectRoot = BuildUtilities.CreateInitializedProjectRoot(TestContext, descriptor, preImportProperties);

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

            TestContext.AddResultFile(result.FilePath);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.DefaultBuildTarget);

            // We expect the compiler to warn if there are no compiler inputs
            var expectedWarnings = (descriptor.ManagedSourceFiles.Any()) ? 0 : 1;

            result.AssertExpectedErrorCount(0);
            result.AssertExpectedWarningCount(expectedWarnings);

            result.AssertExpectedTargetOrdering(
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.DefaultBuildTarget,
                TargetConstants.CalculateFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            // Check expected folder structure exists
            CheckRootOutputFolder(rootOutputFolder);

            // Check expected project outputs
            Assert.AreEqual(1, Directory.EnumerateDirectories(rootOutputFolder).Count(), "Only expecting one child directory to exist under the root analysis output folder");
            ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, descriptor.FullFilePath);

            return(Directory.EnumerateDirectories(rootOutputFolder).Single());
        }
Exemplo n.º 8
0
        public void E2E_FxCop_OutputFolderSet_SonarRulesetNotSpecified()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            // Set the output folder but not the config folder
            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.SonarQubeConfigPath = rootInputFolder;
            preImportProperties.RunCodeAnalysis     = "TRUE";
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertTargetExecuted(TargetConstants.OverrideFxCopSettingsTarget); // output folder is set so this should be executed
            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            AssertFxCopNotExecuted(logger);
            Assert.IsFalse(File.Exists(fxCopLogFile), "FxCop log file should not have been produced");

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultDoesNotExists(projectInfo, AnalysisType.FxCop.ToString());
        }
Exemplo n.º 9
0
        public void WriteProjectInfoFile_UseSolutionProjectGuid()
        {
            // Arrange
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            Guid projectGuid = Guid.NewGuid();

            WriteProjectInfoFile task = new WriteProjectInfoFile
            {
                FullProjectPath = "c:\\fullPath\\project.proj",
                SolutionConfigurationContents = @"<SolutionConfiguration>
                <ProjectConfiguration Project=""{FOO}"" AbsolutePath=""c:\fullPath\foo.proj"" BuildProjectInSolution=""True""> Debug | AnyCPU </ProjectConfiguration>
                <ProjectConfiguration Project=""{" + projectGuid + @"}"" AbsolutePath=""c:\fullPath\project.proj"" BuildProjectInSolution=""True""> Debug | AnyCPU </ProjectConfiguration>
               </SolutionConfiguration >",
                IsTest          = true,
                OutputFolder    = testFolder,
                ProjectName     = "ProjectWithoutProjectGuid",
                ProjectLanguage = "C#"
            };

            // Act
            ProjectInfo reloadedProjectInfo = ExecuteAndCheckSucceeds(task, testFolder);

            // Addition assertions
            ProjectInfoAssertions.AssertExpectedValues(
                "c:\\fullPath\\project.proj",
                ProjectLanguages.CSharp,
                ProjectType.Test,
                projectGuid,
                "ProjectWithoutProjectGuid",
                false, // IsExcluded
                reloadedProjectInfo);
        }
        public void E2E_FxCop_AllConditionsMet_VB()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.RunCodeAnalysis     = "false";
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.CodeAnalysisRuleset = "specifiedInProject.ruleset";

            preImportProperties[TargetProperties.SonarQubeConfigPath] = rootInputFolder;
            CreateValidFxCopRuleset(rootInputFolder, string.Format(TargetProperties.SonarQubeRulesetFormat, "vbnet"));

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties, isVBProject: true);

            string itemPath = TestUtils.CreateTextFile(rootInputFolder, "my.vb",
                                                       @"Public Class Class1

  Public Sub DoStuff()
  End Sub

End Class");

            projectRoot.AddItem(TargetProperties.ItemType_Compile, itemPath);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.DetectFxCopRulesetTarget,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideFxCopSettingsTarget,
                TargetConstants.FxCopTarget,
                TargetConstants.SetFxCopResultsTarget,
                TargetConstants.DefaultBuildTarget,
                TargetConstants.CalculateFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            AssertAllFxCopTargetsExecuted(logger);
            Assert.IsTrue(File.Exists(fxCopLogFile), "FxCop log file should have been produced");

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultExists(projectInfo, AnalysisType.FxCop.ToString(), fxCopLogFile);
        }
Exemplo n.º 11
0
        public void E2E_FxCop_NoFilesToAnalyse()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.RunCodeAnalysis     = "false";
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.CodeAnalysisRuleset = "specifiedInProject.ruleset";

            preImportProperties[TargetProperties.SonarQubeConfigPath] = rootInputFolder;
            CreateValidFxCopRuleset(rootInputFolder, string.Format(TargetProperties.SonarQubeRulesetFormat, "cs"));

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            // Add some files to the project
            string itemPath = CreateTextFile(rootInputFolder, "content1.txt", "aaaa");

            projectRoot.AddItem("Content", itemPath);

            itemPath = CreateTextFile(rootInputFolder, "code1.cs", "class myclassXXX{} // wrong item type");
            projectRoot.AddItem("CompileXXX", itemPath);

            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideFxCopSettingsTarget,

                TargetConstants.FxCopTarget,
                TargetConstants.SetFxCopResultsTarget, // should set the FxCop results after the platform "run Fx Cop" target

                TargetConstants.DefaultBuildTarget,
                TargetConstants.CalculateFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            logger.AssertTargetExecuted(TargetConstants.SetFxCopResultsTarget);

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultDoesNotExists(projectInfo, AnalysisType.FxCop.ToString());
        }
Exemplo n.º 12
0
        public void E2E_FxCop_TestProject_TestProjectTypeGuid()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.CodeAnalysisRuleset = "specifiedInProject.ruleset";

            preImportProperties.ProjectTypeGuids = "X;" + TargetConstants.MsTestProjectTypeGuid.ToUpperInvariant() + ";Y";

            preImportProperties[TargetProperties.SonarQubeConfigPath] = rootInputFolder;
            CreateValidFxCopRuleset(rootInputFolder, string.Format(TargetProperties.SonarQubeRulesetFormat, "cs"));

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            // Add a file to the project
            string itemPath = CreateTextFile(rootInputFolder, "code1.cs", "class myclassXXX{}");

            projectRoot.AddItem(TargetProperties.ItemType_Compile, itemPath);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideFxCopSettingsTarget,
                TargetConstants.FxCopTarget,
                TargetConstants.DefaultBuildTarget,
                TargetConstants.CalculateFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            // We expect the FxCop target to be executed...
            logger.AssertTargetExecuted(TargetConstants.FxCopTarget);
            // ... but we don't expect the FxCop *task* to have executed
            logger.AssertTaskNotExecuted(TargetConstants.FxCopTask);

            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultDoesNotExists(projectInfo, AnalysisType.FxCop.ToString());
        }
Exemplo n.º 13
0
        public void E2E_FxCop_AllConditionsMet()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.RunCodeAnalysis     = "false";
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.CodeAnalysisRuleset = "specifiedInProject.ruleset";

            // we expect these values to be overridden
            preImportProperties.TreatWarningsAsErrors = "true";
            preImportProperties.WarningsAsErrors      = "CS0111;CS0222";
            preImportProperties.WarningLevel          = "3";

            preImportProperties[TargetProperties.SonarQubeConfigPath] = rootInputFolder;
            CreateValidFxCopRuleset(rootInputFolder, string.Format(TargetProperties.SonarQubeRulesetFormat, "cs"));

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            string itemPath = TestUtils.CreateTextFile(rootInputFolder, "my.cs", "class myclass{}");

            projectRoot.AddItem(TargetProperties.ItemType_Compile, itemPath);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.DetectFxCopRulesetTarget,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideFxCopSettingsTarget,
                TargetConstants.FxCopTarget,
                TargetConstants.SetFxCopResultsTarget,
                TargetConstants.DefaultBuildTarget);

            AssertAllFxCopTargetsExecuted(logger);
            Assert.IsTrue(File.Exists(fxCopLogFile), "FxCop log file should have been produced");
            BuildAssertions.AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultExists(projectInfo, AnalysisType.FxCop.ToString(), fxCopLogFile);
        }
        private void SaveAndReloadProjectInfo(ProjectInfo original, string outputFileName)
        {
            File.Exists(outputFileName).Should().BeFalse("Test error: file should not exist at the start of the test. File: {0}", outputFileName);
            original.Save(outputFileName);
            File.Exists(outputFileName).Should().BeTrue("Failed to create the output file. File: {0}", outputFileName);
            TestContext.AddResultFile(outputFileName);

            var reloadedProjectInfo = ProjectInfo.Load(outputFileName);

            reloadedProjectInfo.Should().NotBeNull("Reloaded project info should not be null");

            ProjectInfoAssertions.AssertExpectedValues(original, reloadedProjectInfo);
        }
Exemplo n.º 15
0
        public void WriteProjectInfo_BareProject()
        {
            // Checks the WriteProjectInfo target handles non-VB/C# project types
            // that don't import the standard targets or set the expected properties

            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            BuildLogger logger = new BuildLogger();

            string sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(this.TestContext);
            string projectFilePath = Path.Combine(rootInputFolder, "project.txt");
            Guid   projectGuid     = Guid.NewGuid();

            string             projectXml  = @"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <ProjectGuid>{0}</ProjectGuid>

    <SonarQubeTempPath>{1}</SonarQubeTempPath>
    <SonarQubeOutputPath>{1}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{2}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <Import Project='{3}' />
</Project>
";
            ProjectRootElement projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, this.TestContext, projectXml,
                                                                                      projectGuid.ToString(),
                                                                                      rootOutputFolder,
                                                                                      typeof(WriteProjectInfoFile).Assembly.Location,
                                                                                      sqTargetFile);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger,
                                                             TargetConstants.WriteProjectDataTarget);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.WriteProjectDataTarget);

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            Assert.AreEqual(projectGuid, projectInfo.ProjectGuid, "Unexpected project guid");
            Assert.IsNull(projectInfo.ProjectLanguage, "Expecting the project language to be null");
            Assert.IsFalse(projectInfo.IsExcluded, "Project should not be marked as excluded");
            Assert.AreEqual(ProjectType.Product, projectInfo.ProjectType, "Project should be marked as a product project");
            Assert.AreEqual(0, projectInfo.AnalysisResults.Count, "Not expecting any analysis results to have been created");
        }
        private ProjectInfo SaveAndReloadProjectInfo(ProjectInfo original, string outputFileName)
        {
            Assert.IsFalse(File.Exists(outputFileName), "Test error: file should not exist at the start of the test. File: {0}", outputFileName);
            original.Save(outputFileName);
            Assert.IsTrue(File.Exists(outputFileName), "Failed to create the output file. File: {0}", outputFileName);
            this.TestContext.AddResultFile(outputFileName);

            ProjectInfo reloadedProjectInfo = ProjectInfo.Load(outputFileName);

            Assert.IsNotNull(reloadedProjectInfo, "Reloaded project info should not be null");

            ProjectInfoAssertions.AssertExpectedValues(original, reloadedProjectInfo);
            return(reloadedProjectInfo);
        }
Exemplo n.º 17
0
        public void E2E_InvalidGuid()
        {
            // Projects with invalid guids should have a warning emitted. The project info
            // should not be generated.

            // Arrange
            var rootInputFolder  = TestUtils.CreateTestSpecificFolder(TestContext, "Inputs");
            var rootOutputFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Outputs");

            var preImportProperties = CreateDefaultAnalysisProperties(rootInputFolder, rootOutputFolder);

            var descriptor = new ProjectDescriptor()
            {
                // No guid property
                IsTestProject       = false,
                ParentDirectoryPath = rootInputFolder,
                ProjectFolderName   = "MyProjectDir",
                ProjectFileName     = "MissingProjectGuidProject.proj"
            };

            AddEmptyAnalysedCodeFile(descriptor, rootInputFolder);

            var projectRoot = BuildUtilities.CreateInitializedProjectRoot(TestContext, descriptor, preImportProperties);

            projectRoot.AddProperty("ProjectGuid", "Invalid guid");

            string projectFilePath = Path.Combine(rootInputFolder,
                                                  descriptor.ProjectFolderName, descriptor.ProjectFileName);

            projectRoot.Save(projectFilePath);
            TestContext.AddResultFile(projectFilePath);

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

            // Assert
            buildLog.AssertTargetSucceeded(TargetConstants.DefaultBuildTarget); // Build should succeed with warnings
            ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectFilePath);

            buildLog.AssertExpectedErrorCount(0);
            buildLog.AssertExpectedWarningCount(1);

            var warning = buildLog.Warnings[0];

            Assert.IsTrue(warning.Contains(descriptor.FullFilePath),
                          "Expecting the warning to contain the full path to the bad project file");
        }
        public void E2E_FxCop_AllConditionsMet()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.RunSonarQubeAnalysis = "true";
            preImportProperties.SonarQubeOutputPath  = rootOutputFolder;
            preImportProperties.RunCodeAnalysis      = "false";
            preImportProperties.CodeAnalysisLogFile  = fxCopLogFile;
            preImportProperties.CodeAnalysisRuleset  = "specifiedInProject.ruleset";

            preImportProperties[TargetProperties.SonarQubeConfigPath] = rootInputFolder;
            CreateValidFxCopRuleset(rootInputFolder, TargetProperties.SonarQubeRulesetName);

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            string itemPath = CreateTextFile(rootInputFolder, "my.cs", "class myclass{}");

            projectRoot.AddItem("Compile", itemPath);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(TargetConstants.CoreCompileTarget,
                                                TargetConstants.CalculateSonarQubeFileListsTarget,
                                                TargetConstants.OverrideFxCopSettingsTarget,
                                                TargetConstants.FxCopTarget,
                                                TargetConstants.SetFxCopResultsTarget,
                                                TargetConstants.DefaultBuildTarget);

            AssertAllFxCopTargetsExecuted(logger);
            Assert.IsTrue(File.Exists(fxCopLogFile), "FxCop log file should have been produced");

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultExists(projectInfo, AnalysisType.FxCop.ToString(), fxCopLogFile);
        }
Exemplo n.º 19
0
        public void WriteProjectInfo_UnrecognisedLanguage()
        {
            // Checks the WriteProjectInfo target handles projects with unrecognised languages

            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            BuildLogger logger = new BuildLogger();

            string sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(this.TestContext);
            string projectFilePath = Path.Combine(rootInputFolder, "unrecognisedLanguage.proj.txt");

            string             projectXml  = @"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <Language>my.special.language</Language>
    <ProjectGuid>670DAF47-CBD4-4735-B7A3-42C0A02B1CB9</ProjectGuid>

    <SonarQubeTempPath>{0}</SonarQubeTempPath>
    <SonarQubeOutputPath>{0}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{1}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <Import Project='{2}' />
</Project>
";
            ProjectRootElement projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, this.TestContext, projectXml,
                                                                                      rootOutputFolder,
                                                                                      typeof(WriteProjectInfoFile).Assembly.Location,
                                                                                      sqTargetFile);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger,
                                                             TargetConstants.WriteProjectDataTarget);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.WriteProjectDataTarget);

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            Assert.AreEqual("my.special.language", projectInfo.ProjectLanguage, "Unexpected project language");
            Assert.AreEqual(0, projectInfo.AnalysisResults.Count, "Not expecting any analysis results to have been created");
        }
Exemplo n.º 20
0
        public void WriteProjectInfo_BareProject()
        {
            // Checks the WriteProjectInfo target handles non-VB/C# project types
            // that don't import the standard targets or set the expected properties

            // Arrange
            var rootInputFolder  = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Inputs");
            var rootOutputFolder = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Outputs");

            var sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(TestContext);
            var projectFilePath = Path.Combine(rootInputFolder, "project.txt");
            var projectGuid     = Guid.NewGuid();

            var projectXml  = $@"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <ProjectGuid>{projectGuid}</ProjectGuid>

    <SonarQubeTempPath>{rootOutputFolder}</SonarQubeTempPath>
    <SonarQubeBuildTasksAssemblyFile>{typeof(WriteProjectInfoFile).Assembly.Location}</SonarQubeBuildTasksAssemblyFile>
    <SonarQubeOutputPath>{rootOutputFolder}</SonarQubeOutputPath>
  </PropertyGroup>

  <Import Project='{sqTargetFile}' />
</Project>
";
            var projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, TestContext, projectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.SonarWriteProjectData);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.SonarWriteProjectData);

            var projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            projectInfo.ProjectGuid.Should().Be(projectGuid, "Unexpected project guid");
            projectInfo.ProjectLanguage.Should().BeNull("Expecting the project language to be null");
            projectInfo.IsExcluded.Should().BeFalse("Project should not be marked as excluded");
            projectInfo.ProjectType.Should().Be(ProjectType.Product, "Project should be marked as a product project");
            projectInfo.AnalysisResults.Should().BeEmpty("Not expecting any analysis results to have been created");
        }
        public void E2E_MissingProjectGuid()
        {
            // Projects with missing guids should have a warning emitted. The project info
            // should not be generated.

            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            WellKnownProjectProperties preImportProperties = CreateDefaultAnalysisProperties(rootInputFolder, rootOutputFolder);

            preImportProperties["SonarConfigPath"] = rootInputFolder;

            ProjectDescriptor descriptor = new ProjectDescriptor()
            {
                // No guid property
                IsTestProject       = false,
                ParentDirectoryPath = rootInputFolder,
                ProjectFolderName   = "MyProjectDir",
                ProjectFileName     = "MissingProjectGuidProject.proj"
            };

            AddEmptyCodeFile(descriptor, rootInputFolder);

            ProjectRootElement projectRoot = BuildUtilities.CreateInitializedProjectRoot(this.TestContext, descriptor, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget); // Build should succeed with warnings
            ProjectInfoAssertions.AssertNoProjectInfoFilesExists(rootOutputFolder);

            logger.AssertExpectedErrorCount(0);
            logger.AssertExpectedWarningCount(1);

            BuildWarningEventArgs warning = logger.Warnings[0];

            Assert.IsTrue(warning.Message.Contains(descriptor.FullFilePath),
                          "Expecting the warning to contain the full path to the bad project file");
        }
        /// <summary>
        /// Executes the WriteProjectInfoFile target in the the supplied project.
        /// The method will check the build succeeded and that a single project
        /// output file was created.
        /// </summary>
        /// <returns>The project info file that was created during the build</returns>
        private ProjectInfo ExecuteWriteProjectInfo(ProjectRootElement projectRoot, string rootOutputFolder)
        {
            projectRoot.Save();
            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.CalculateSonarQubeFileListsTarget, TargetConstants.WriteProjectDataTarget);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.CalculateSonarQubeFileListsTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.WriteProjectDataTarget);

            logger.AssertNoWarningsOrErrors();
            logger.AssertTargetExecuted(TargetConstants.WriteProjectDataTarget);

            // Check expected project outputs
            Assert.AreEqual(1, Directory.EnumerateDirectories(rootOutputFolder).Count(), "Only expecting one child directory to exist under the root analysis output folder");
            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            return(projectInfo);
        }
Exemplo n.º 23
0
        public void WriteProjectInfo_UnrecognisedLanguage()
        {
            // Checks the WriteProjectInfo target handles projects with unrecognized languages

            // Arrange
            var rootInputFolder  = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Inputs");
            var rootOutputFolder = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Outputs");

            var sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(TestContext);
            var projectFilePath = Path.Combine(rootInputFolder, "unrecognisedLanguage.proj.txt");

            var projectXml  = $@"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <Language>my.special.language</Language>
    <ProjectGuid>670DAF47-CBD4-4735-B7A3-42C0A02B1CB9</ProjectGuid>

    <SonarQubeTempPath>{rootOutputFolder}</SonarQubeTempPath>
    <SonarQubeOutputPath>{rootOutputFolder}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{typeof(WriteProjectInfoFile).Assembly.Location}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <Import Project='{sqTargetFile}' />
</Project>
";
            var projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, TestContext, projectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.SonarWriteProjectData);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.SonarWriteProjectData);

            var projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            projectInfo.ProjectLanguage.Should().Be("my.special.language", "Unexpected project language");
            projectInfo.AnalysisResults.Should().BeEmpty("Not expecting any analysis results to have been created");
        }
Exemplo n.º 24
0
        public void Razor_RazorSpecificOutputAndProjectInfo_AreCopiedToCorrectFolders()
        {
            // Arrange
            var root = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var projectSpecificOutDir          = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "0");
            var temporaryProjectSpecificOutDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, @"0.tmp");
            var razorSpecificOutDir            = Path.Combine(root, "0.Razor");

            TestUtils.CreateEmptyFile(temporaryProjectSpecificOutDir, "Issues.FromMainBuild.json");
            TestUtils.CreateEmptyFile(projectSpecificOutDir, "Issues.FromRazorBuild.json");
            var razorIssuesPath = Path.Combine(razorSpecificOutDir, "Issues.FromRazorBuild.json");

            var projectSnippet = $@"
<PropertyGroup>
  <SonarTemporaryProjectSpecificOutDir>{temporaryProjectSpecificOutDir}</SonarTemporaryProjectSpecificOutDir>
  <ProjectSpecificOutDir>{projectSpecificOutDir}</ProjectSpecificOutDir>
  <RazorSonarErrorLogName>Issues.FromRazorBuild.json</RazorSonarErrorLogName>
</PropertyGroup>

<ItemGroup>
  <RazorCompile Include='SomeRandomValue'>
  </RazorCompile>
</ItemGroup>
";

            var filePath = CreateProjectFile(null, projectSnippet);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, filePath, TargetConstants.SonarFinishRazorProjectCodeAnalysis);

            // Assert
            var razorProjectInfo = ProjectInfoAssertions.AssertProjectInfoExists(root, filePath);

            result.AssertTargetExecuted(TargetConstants.SonarFinishRazorProjectCodeAnalysis);
            razorProjectInfo.AnalysisSettings.Single(x => x.Id.Equals("sonar.cs.analyzer.projectOutPaths")).Value.Should().Be(razorSpecificOutDir);
            razorProjectInfo.AnalysisSettings.Single(x => x.Id.Equals("sonar.cs.roslyn.reportFilePaths")).Value.Should().Be(razorIssuesPath);
            Directory.Exists(temporaryProjectSpecificOutDir).Should().BeFalse();
            File.Exists(Path.Combine(projectSpecificOutDir, "Issues.FromMainBuild.json")).Should().BeTrue();
            File.Exists(Path.Combine(razorSpecificOutDir, "Issues.FromRazorBuild.json")).Should().BeTrue();
        }
Exemplo n.º 25
0
        public void E2E_FxCop_OutputFolderSet_SonarRulesetNotFound()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            // Set the output folder and config path
            // Don't create a ruleset file on disc
            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.RunCodeAnalysis     = "true";           // our targets should override this value
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.SonarQubeConfigPath = rootInputFolder;
            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertTargetExecuted(TargetConstants.OverrideFxCopSettingsTarget);  // output folder is set so this should be executed
            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            // We expect the core FxCop *target* to have been started, but it should then be skipped
            // executing the FxCop *task* because the condition on the target is false
            // -> the FxCop output file should not be produced
            AssertFxCopNotExecuted(logger);

            Assert.IsFalse(File.Exists(fxCopLogFile), "FxCop log file should not have been produced");

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultDoesNotExists(projectInfo, AnalysisType.FxCop.ToString());
        }
Exemplo n.º 26
0
        public void Razor_RazorSpecificOutputAndProjectInfo_PreserveUserDefinedErrorLogValue()
        {
            // Arrange
            var root = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var projectSpecificOutDir          = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "0");
            var temporaryProjectSpecificOutDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, @"0.tmp");
            var razorSpecificOutDir            = Path.Combine(root, "0.Razor");
            var userDefinedErrorLog            = TestUtils.CreateEmptyFile(TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "User"), "UserDefined.FromRazorBuild.json");

            var projectSnippet = $@"
<PropertyGroup>
  <!-- This value is considered to be set by user when $(RazorSonarErrorLogName) is empty -->
  <RazorSonarErrorLog>{userDefinedErrorLog}</RazorSonarErrorLog>
  <SonarTemporaryProjectSpecificOutDir>{temporaryProjectSpecificOutDir}</SonarTemporaryProjectSpecificOutDir>
  <ProjectSpecificOutDir>{projectSpecificOutDir}</ProjectSpecificOutDir>
</PropertyGroup>

<ItemGroup>
  <RazorCompile Include='SomeRandomValue'>
  </RazorCompile>
</ItemGroup>
";

            var filePath = CreateProjectFile(null, projectSnippet);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, filePath, TargetConstants.SonarFinishRazorProjectCodeAnalysis);

            // Assert
            var actualProjectInfo = ProjectInfoAssertions.AssertProjectInfoExists(root, filePath);

            result.AssertTargetExecuted(TargetConstants.SonarFinishRazorProjectCodeAnalysis);
            actualProjectInfo.AnalysisSettings.Single(x => x.Id.Equals("sonar.cs.analyzer.projectOutPaths")).Value.Should().Be(razorSpecificOutDir);
            actualProjectInfo.AnalysisSettings.Single(x => x.Id.Equals("sonar.cs.roslyn.reportFilePaths")).Value.Should().Be(userDefinedErrorLog);
            Directory.Exists(temporaryProjectSpecificOutDir).Should().BeFalse();
            File.Exists(userDefinedErrorLog).Should().BeTrue();
        }
Exemplo n.º 27
0
        public void E2E_BareProject_CorrectlyCategorised()
        {
            // Checks that projects that don't include the standard managed targets are still
            // processed correctly e.g. can be excluded, marked as test projects etc

            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            BuildLogger logger = new BuildLogger();

            string sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(this.TestContext);
            string projectFilePath = Path.Combine(rootInputFolder, "project.txt");
            Guid   projectGuid     = Guid.NewGuid();

            string             projectXml  = @"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <SonarQubeExclude>true</SonarQubeExclude>
    <Language>my.language</Language>
    <ProjectTypeGuids>{4}</ProjectTypeGuids>

    <ProjectGuid>{0}</ProjectGuid>

    <SonarQubeTempPath>{1}</SonarQubeTempPath>
    <SonarQubeOutputPath>{1}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{2}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <ItemGroup>
    <!-- no recognised content -->
  </ItemGroup>

  <Import Project='{3}' />

  <Target Name='Build'>
    <Message Importance='high' Text='In dummy build target' />
  </Target>

</Project>
";
            ProjectRootElement projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, this.TestContext, projectXml,
                                                                                      projectGuid.ToString(),
                                                                                      rootOutputFolder,
                                                                                      typeof(WriteProjectInfoFile).Assembly.Location,
                                                                                      sqTargetFile,
                                                                                      TargetConstants.MsTestProjectTypeGuid
                                                                                      );

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger,
                                                             TargetConstants.DefaultBuildTarget);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.DefaultBuildTarget,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.CalculateFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            // Check the project info
            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            Assert.IsTrue(projectInfo.IsExcluded, "Expecting the project to be marked as excluded");
            Assert.AreEqual("my.language", projectInfo.ProjectLanguage, "Unexpected project language");
            Assert.AreEqual(ProjectType.Test, projectInfo.ProjectType, "Project should be marked as a test project");
            Assert.AreEqual(0, projectInfo.AnalysisResults.Count, "Unexpected number of analysis results created");
        }
Exemplo n.º 28
0
        public void E2E_BareProject_FilesToAnalyze()
        {
            // Checks the integration targets handle non-VB/C# project types
            // that don't import the standard targets or set the expected properties
            // The project info should be created as normal and the correct files to analyze detected.

            // Arrange
            var context = CreateContext();

            var sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(TestContext);
            var projectFilePath = Path.Combine(context.InputFolder, "project.txt");
            var projectGuid     = Guid.NewGuid();

            var codeFile       = context.CreateInputFile("code.cpp");
            var contentFile    = context.CreateInputFile("code.js");
            var unanalysedFile = context.CreateInputFile("text.shouldnotbeanalysed");
            var excludedFile   = context.CreateInputFile("excluded.cpp");

            var projectXml  = $@"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <ProjectGuid>{projectGuid}</ProjectGuid>

    <SonarQubeTempPath>{context.OutputFolder}</SonarQubeTempPath>
    <SonarQubeOutputPath>{context.OutputFolder}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{typeof(WriteProjectInfoFile).Assembly.Location}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <ItemGroup>
    <ClCompile Include='{codeFile}' />
    <Content Include='{contentFile}' />
    <ShouldBeIgnored Include='{unanalysedFile}' />
    <ClCompile Include='{excludedFile}'>
      <SonarQubeExclude>true</SonarQubeExclude>
    </ClCompile>
  </ItemGroup>

  <Import Project='{sqTargetFile}' />

  <Target Name='CoreCompile' BeforeTargets=""Build"">
    <Message Importance='high' Text='In dummy core compile target' />
  </Target>

  <Target Name='Build'>
    <Message Importance='high' Text='In dummy build target' />
  </Target>

</Project>
";
            var projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, TestContext, projectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.DefaultBuild);

            // Assert
            result.BuildSucceeded.Should().BeTrue();

            result.AssertTargetOrdering(
                TargetConstants.SonarCategoriseProject,
                TargetConstants.SonarWriteFilesToAnalyze,
                TargetConstants.CoreCompile,
                TargetConstants.DefaultBuild,
                TargetConstants.InvokeSonarWriteProjectData_NonRazorProject,
                TargetConstants.SonarWriteProjectData);

            // Check the content of the project info xml
            var projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(context.OutputFolder, projectRoot.FullPath);

            projectInfo.ProjectGuid.Should().Be(projectGuid, "Unexpected project guid");
            projectInfo.ProjectLanguage.Should().BeNull("Expecting the project language to be null");
            projectInfo.IsExcluded.Should().BeFalse("Project should not be marked as excluded");
            projectInfo.ProjectType.Should().Be(ProjectType.Product, "Project should be marked as a product project");
            projectInfo.AnalysisResults.Should().HaveCount(1, "Unexpected number of analysis results created");

            // Check the correct list of files to analyze were returned
            var filesToAnalyze       = ProjectInfoAssertions.AssertAnalysisResultExists(projectInfo, AnalysisType.FilesToAnalyze.ToString());
            var actualFilesToAnalyze = File.ReadAllLines(filesToAnalyze.Location);

            actualFilesToAnalyze.Should().BeEquivalentTo(new string[] { codeFile, contentFile }, "Unexpected list of files to analyze");
        }
Exemplo n.º 29
0
        public void E2E_BareProject_CorrectlyCategorised()
        {
            // Checks that projects that don't include the standard managed targets are still
            // processed correctly e.g. can be excluded, marked as test projects etc

            // Arrange
            var rootInputFolder  = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Inputs");
            var rootOutputFolder = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Outputs");

            var sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(TestContext);
            var projectFilePath = Path.Combine(rootInputFolder, "project.txt");
            var projectGuid     = Guid.NewGuid();

            var projectXml  = $@"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <SonarQubeExclude>true</SonarQubeExclude>
    <Language>my.language</Language>
    <ProjectTypeGuids>{TargetConstants.MsTestProjectTypeGuid}</ProjectTypeGuids>

    <ProjectGuid>{projectGuid}</ProjectGuid>

    <SonarQubeTempPath>{rootOutputFolder}</SonarQubeTempPath>
    <SonarQubeOutputPath>{rootOutputFolder}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{typeof(WriteProjectInfoFile).Assembly.Location}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <ItemGroup>
    <!-- no recognized content -->
  </ItemGroup>

  <Import Project='{sqTargetFile}' />

  <Target Name='CoreCompile' BeforeTargets=""Build"">
    <Message Importance='high' Text='In dummy core compile target' />
  </Target>

  <Target Name='Build'>
    <Message Importance='high' Text='In dummy build target' />
  </Target>

</Project>
";
            var projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, TestContext, projectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.DefaultBuild);

            // Assert
            result.BuildSucceeded.Should().BeTrue();

            result.AssertTargetOrdering(
                TargetConstants.SonarCategoriseProject,
                TargetConstants.SonarWriteFilesToAnalyze,
                TargetConstants.CoreCompile,
                TargetConstants.DefaultBuild,
                TargetConstants.InvokeSonarWriteProjectData_NonRazorProject,
                TargetConstants.SonarWriteProjectData);

            // Check the project info
            var projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            projectInfo.IsExcluded.Should().BeTrue("Expecting the project to be marked as excluded");
            projectInfo.ProjectLanguage.Should().Be("my.language", "Unexpected project language");
            projectInfo.ProjectType.Should().Be(ProjectType.Test, "Project should be marked as a test project");
            projectInfo.AnalysisResults.Should().BeEmpty("Unexpected number of analysis results created");
        }
Exemplo n.º 30
0
        public void E2E_FxCop_TestProject_TestProjectByName()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.CodeAnalysisRuleset = "specifiedInProject.ruleset";

            preImportProperties.SonarQubeConfigPath = rootInputFolder;

            preImportProperties[TargetProperties.SonarQubeConfigPath] = rootInputFolder;
            CreateValidFxCopRuleset(rootInputFolder, string.Format(TargetProperties.SonarQubeRulesetFormat, "cs"));

            // Create a config file in the config folder containing a reg ex to identify tests projects
            AnalysisConfig config = new AnalysisConfig();

            config.LocalSettings = new AnalysisProperties();
            config.LocalSettings.Add(new Property()
            {
                Id = IsTestFileByName.TestRegExSettingId, Value = ".testp."
            });

            string configFullPath = Path.Combine(rootInputFolder, FileConstants.ConfigFileName);

            config.Save(configFullPath);

            // Create a project with a file name that will match the reg ex
            ProjectDescriptor  descriptor  = BuildUtilities.CreateValidProjectDescriptor(rootInputFolder, "MyTestProject.proj");
            ProjectRootElement projectRoot = BuildUtilities.CreateInitializedProjectRoot(this.TestContext, descriptor, preImportProperties);


            // Add a file to the project
            string itemPath = CreateTextFile(rootInputFolder, "code1.cs", "class myclassXXX{}");

            projectRoot.AddItem(TargetProperties.ItemType_Compile, itemPath);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideFxCopSettingsTarget,
                TargetConstants.FxCopTarget,
                TargetConstants.DefaultBuildTarget,
                TargetConstants.CalculateFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            // We expect the FxCop target to be executed...
            logger.AssertTargetExecuted(TargetConstants.FxCopTarget);
            // ... but we don't expect the FxCop *task* to have executed
            logger.AssertTaskNotExecuted(TargetConstants.FxCopTask);

            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultDoesNotExists(projectInfo, AnalysisType.FxCop.ToString());
        }