public void FileGen_DuplicateProjectIds()
        {
            // ProjectInfo files with duplicate ids should be ignored

            // Arrange - three files, all with the same Guid, one of which is excluded
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            Guid duplicateGuid = Guid.NewGuid();
            CreateProjectInfoInSubDir(testDir, "duplicate1", duplicateGuid, ProjectType.Product, false, "c:\\abc\\duplicateProject1.proj"); // not excluded
            CreateProjectInfoInSubDir(testDir, "duplicate2", duplicateGuid, ProjectType.Test, false, "S:\\duplicateProject2.proj"); // not excluded
            CreateProjectInfoInSubDir(testDir, "excluded", duplicateGuid, ProjectType.Product, true, null); // excluded

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

            // Act
            ProjectInfoAnalysisResult result = null;
            using (new AssertIgnoreScope()) // expecting the properties writer to assert
            {
                result = PropertiesFileGenerator.GenerateFile(config, logger);
            }

            // Assert
            AssertExpectedStatus("duplicate1", ProjectInfoValidity.DuplicateGuid, result);
            AssertExpectedStatus("duplicate2", ProjectInfoValidity.DuplicateGuid, result);
            AssertExpectedStatus("excluded", ProjectInfoValidity.ExcludeFlagSet, result); // Expecting excluded rather than duplicate
            AssertExpectedProjectCount(3, result);

            // No valid project info files -> file not generated
            AssertFailedToCreatePropertiesFiles(result, logger);
            logger.AssertWarningsLogged(2); // should be a warning for each project with a duplicate id

            logger.AssertSingleWarningExists(duplicateGuid.ToString(), "c:\\abc\\duplicateProject1.proj");
            logger.AssertSingleWarningExists(duplicateGuid.ToString(), "S:\\duplicateProject2.proj");
        }
        public void BuildWrapper_OldCppPluginInstalled_FilesDownloaded()
        {
            // If an older version of the C++ plugin is installed then the embedded resource
            // won't exist. In that case we expect a warning message telling the user to upgrade.

            // Arrange
            string rootDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            TestLogger logger = new TestLogger();

            MockSonarQubeServer mockServer = new MockSonarQubeServer();
            mockServer.Data.InstalledPlugins.Add("cpp"); // plugin exists but no zip file

            BuildWrapperInstaller testSubject = new BuildWrapperInstaller(logger);

            // Act
            AnalysisProperties properties = testSubject.InstallBuildWrapper(mockServer, rootDir, "c:\\output\\");

            // Assert
            logger.AssertSingleWarningExists(SonarQube.TeamBuild.PreProcessor.Resources.BW_CppPluginUpgradeRequired);
            logger.AssertErrorsLogged(0);

            AssertNoFilesExist(rootDir);

            Assert.IsNotNull(properties, "Returned properties should not be null");
            Assert.AreEqual(0, properties.Count, "Not expecting any properties to be set");
        }
        public void TrxReader_InvalidTrxFile()
        {
            // Arrange
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string resultsDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "TestResults");
            string textFile = CreateTextFile(resultsDir, "dummy.trx", "this is not a trx file");
            TestLogger logger = new TestLogger();

            // Act
            string coverageFilePath = TrxFileReader.LocateCodeCoverageFile(testDir, logger);

            // Assert
            Assert.AreEqual(null, coverageFilePath);

            logger.AssertSingleWarningExists("dummy.trx"); // expecting a warning about the invalid file
            logger.AssertErrorsLogged(0); // should be a warning, not an error
        }
        public void TrxReader_MultipleTrxFiles()
        {
            // Arrange
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string resultsDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "TestResults");
            string trx1 = CreateTextFile(resultsDir, "mytrx1.trx", "<TestRun />");
            string trx2 = CreateTextFile(resultsDir, "mytrx2.trx", "<TestRun />");
            TestLogger logger = new TestLogger();

            // Act
            string coverageFilePath = TrxFileReader.LocateCodeCoverageFile(testDir, logger);

            // Assert
            Assert.AreEqual(null, coverageFilePath);

            logger.AssertSingleWarningExists(trx1, trx2); // expecting a warning referring the log files
            logger.AssertErrorsLogged(0);
        }
        public void ArgProc_SonarVerbose_IsBool()
        {
            TestLogger logger = new TestLogger();

            IBootstrapperSettings settings = CheckProcessingSucceeds(logger, "/d:sonar.host.url=foo", "begin", "/d:sonar.verbose=yes");
            Assert.AreEqual(VerbosityCalculator.DefaultLoggingVerbosity, settings.LoggingVerbosity, "Only expecting true or false");

            logger.AssertErrorsLogged(0);
            logger.AssertSingleWarningExists("yes");
        }
        public void ArgProc_BeginVerb()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string validUrl = "/d:sonar.host.url=http://foo";

            // 1. Minimal parameters -> valid
            IBootstrapperSettings settings = CheckProcessingSucceeds(logger, validUrl, "begin");
            AssertExpectedPhase(AnalysisPhase.PreProcessing, settings);
            logger.AssertWarningsLogged(0);
            AssertExpectedChildArguments(settings, validUrl);

            // 2. With additional parameters -> valid
            settings = CheckProcessingSucceeds(logger, validUrl, "begin", "ignored", "k=2");
            AssertExpectedPhase(AnalysisPhase.PreProcessing, settings);
            logger.AssertWarningsLogged(0);
            AssertExpectedChildArguments(settings, validUrl, "ignored", "k=2");

            // 3. Multiple occurrences -> error
            logger = CheckProcessingFails(validUrl, "begin", "begin");
            logger.AssertSingleErrorExists(ArgumentProcessor.BeginVerb);

            // 4. Missing -> valid with warning
            logger = new TestLogger();
            settings = CheckProcessingSucceeds(logger, validUrl);
            logger.AssertSingleWarningExists(ArgumentProcessor.BeginVerb);
            AssertExpectedChildArguments(settings, validUrl);

            // 5. Incorrect case -> treated as unrecognised argument
            // -> valid with 1 warning (no begin / end specified warning)
            logger = new TestLogger();
            settings = CheckProcessingSucceeds(logger, validUrl, "BEGIN"); // wrong case
            logger.AssertWarningsLogged(1);
            logger.AssertSingleWarningExists(ArgumentProcessor.BeginVerb);
            AssertExpectedChildArguments(settings, validUrl, "BEGIN");
        }
        public void FileGen_VSBootstrapperIsDisabled_OverrideUserSettings_DifferentValue()
        {
            // 0. Arrange
            TestLogger logger = new TestLogger();

            // Try to explicitly enable the setting
            Property bootstrapperProperty = new Property() { Id = PropertiesFileGenerator.VSBootstrapperPropertyKey, Value = "true" };

            // Act
            ProjectInfoAnalysisResult result = ExecuteAndCheckSucceeds("disableBootstrapperDiff", logger, bootstrapperProperty);

            // Assert
            SQPropertiesFileReader provider = new SQPropertiesFileReader(result.FullPropertiesFilePath);
            provider.AssertSettingExists(PropertiesFileGenerator.VSBootstrapperPropertyKey, "false");
            logger.AssertSingleWarningExists(PropertiesFileGenerator.VSBootstrapperPropertyKey);
        }
        public void FileGen_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);
        }
        public void TrxReader_TrxWithMultipleAttachments()
        {
            // Arrange
            string testDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string resultsDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "TestResults");
            string trxFile
                = CreateTextFile(resultsDir, "multiple_attachments.trx",
            @"<?xml version=""1.0"" encoding=""UTF-8""?>
            <TestRun id=""eb906034-f363-4bf0-ac6a-29fa47645f67""
            name=""LOCAL SERVICE@MACHINENAME 2015-05-06 08:38:39"" runUser=""NT AUTHORITY\LOCAL SERVICE""
            xmlns=""http://microsoft.com/schemas/VisualStudio/TeamTest/2010"">
              <ResultSummary outcome=""Completed"">
            <Counters total=""123"" executed=""123"" passed=""123"" failed=""0"" error=""0"" timeout=""0"" aborted=""0"" inconclusive=""0"" passedButRunAborted=""0"" notRunnable=""0"" notExecuted=""0"" disconnected=""0"" warning=""0"" completed=""0"" inProgress=""0"" pending=""0"" />
            <RunInfos />
            <CollectorDataEntries>
              <Collector agentName=""MACHINENAME"" uri=""datacollector://microsoft/CodeCoverage/2.0"" collectorDisplayName=""Code Coverage"">
            <UriAttachments>
              <UriAttachment>
            <A href=""MACHINENAME\AAA.coverage"">
            </A>
              </UriAttachment>
            </UriAttachments>
              </Collector>
              <Collector agentName=""MACHINENAME"" uri=""datacollector://microsoft/CodeCoverage/2.0"" collectorDisplayName=""Code Coverage"">
            <UriAttachments>
              <UriAttachment>
            <A href=""XXX.coverage"">
            </A>
              </UriAttachment>
            </UriAttachments>
              </Collector>
            </CollectorDataEntries>
              </ResultSummary>
            </TestRun>
            ");
            TestLogger logger = new TestLogger();

            // Act
            string coverageFilePath = TrxFileReader.LocateCodeCoverageFile(testDir, logger);

            // Assert
            Assert.AreEqual(null, coverageFilePath);

            logger.AssertSingleWarningExists(@"MACHINENAME\AAA.coverage", @"XXX.coverage"); // the warning should refer to both of the coverage files
            logger.AssertErrorsLogged(0);
        }