public void Generate_NoAnalyzersFoundInPackage_GenerateFails()
        {
            // Arrange
            string outputDir = TestUtils.CreateTestDirectory(TestContext, ".out");

            TestLogger logger = new TestLogger();

            // Create a fake remote repo containing a package that does not contain analyzers
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(TestContext);

            remoteRepoBuilder.CreatePackage("no.analyzers.id", "0.9", TestUtils.CreateTextFile("dummy.txt", outputDir), License.NotRequired /* no dependencies */);

            NuGetPackageHandler     nuGetHandler = new NuGetPackageHandler(remoteRepoBuilder.FakeRemoteRepo, GetLocalNuGetDownloadDir(), logger);
            AnalyzerPluginGenerator apg          = new AnalyzerPluginGenerator(nuGetHandler, logger);
            ProcessedArgs           args         = CreateArgs("no.analyzers.id", "0.9", "cs", false, false, outputDir);

            // Act
            bool result = apg.Generate(args);

            // Assert
            result.Should().BeFalse("Expecting generation to fail");
            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "no.analyzers.id"));
            logger.AssertSingleWarningExists(UIResources.APG_NoAnalyzersInTargetSuggestRecurse);
            logger.AssertWarningsLogged(2);
            AssertRuleTemplateDoesNotExist(outputDir);
        }
        public void Generate_LicenseAcceptanceNotRequestedIfNoAnalysers()
        {
            // No point in asking the user to accept licenses for packages that don't contain analyzers

            // Arrange
            string outputDir        = TestUtils.CreateTestDirectory(TestContext, ".out");
            string dummyContentFile = TestUtils.CreateTextFile("dummy.txt", outputDir, "non-analyzer content file");

            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(TestContext);

            // Parent only: requires license
            remoteRepoBuilder.CreatePackage("non-analyzer.requireAccept.id", "1.0", dummyContentFile, License.Required);

            TestLogger logger           = new TestLogger();
            AnalyzerPluginGenerator apg = CreateTestSubjectWithFakeRemoteRepo(remoteRepoBuilder, logger);

            // 1. User does not accept, but no analyzers so no license prompt -> fails due absence of analyzers
            ProcessedArgs args = CreateArgs("non-analyzer.requireAccept.id", "1.0", "cs", false /* accept licenses */,
                                            false, outputDir);
            bool result = apg.Generate(args);

            result.Should().BeFalse("Expecting generator to fail");

            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "non-analyzer.requireAccept.id"));
            logger.AssertSingleWarningExists(UIResources.APG_NoAnalyzersInTargetSuggestRecurse);
            logger.AssertWarningsLogged(2);
            logger.AssertErrorsLogged(0);
        }
        public void Generate_LicenseAcceptanceNotRequired_NoAnalyzersInTarget()
        {
            // If there are:
            // No required licenses
            // No analyzers in the targeted package, but analyzers in the dependencies
            // We should fail due to the absence of analyzers if we are only generating a plugin for the targeted package
            // We should succeed if we are generating plugins for the targeted package and its dependencies

            // Arrange
            string            outputDir         = TestUtils.CreateTestDirectory(TestContext, ".out");
            string            dummyContentFile  = TestUtils.CreateTextFile("dummy.txt", outputDir, "non-analyzer content file");
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(TestContext);

            // Multi-level dependencies: no package requires license acceptence
            // Parent has no analyzers, but dependencies do
            IPackage grandchild = CreatePackageWithAnalyzer(remoteRepoBuilder, "grandchild.id", "1.2", License.NotRequired /* no dependencies */);
            IPackage child      = CreatePackageWithAnalyzer(remoteRepoBuilder, "child.id", "1.1", License.NotRequired, grandchild);

            remoteRepoBuilder.CreatePackage("parent.id", "1.0", dummyContentFile, License.NotRequired, child);

            TestLogger logger           = new TestLogger();
            AnalyzerPluginGenerator apg = CreateTestSubjectWithFakeRemoteRepo(remoteRepoBuilder, logger);

            // 1. a) Only target package. Acceptance not required -> fails due to absence of analyzers
            ProcessedArgs args = CreateArgs("parent.id", "1.0", "cs", false /* accept licenses */,
                                            false, outputDir);
            bool result = apg.Generate(args);

            result.Should().BeFalse("Expecting generator to fail");

            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "parent.id"));
            logger.AssertSingleWarningExists(UIResources.APG_NoAnalyzersInTargetSuggestRecurse);
            logger.AssertWarningsLogged(2);
            logger.AssertErrorsLogged(0);

            // 1. b) Target package and dependencies. Acceptance not required -> succeeds if generate dependencies = true
            logger.Reset();
            args = CreateArgs("parent.id", "1.0", "cs", false /* accept licenses */,
                              true /* generate plugins for dependencies */, outputDir);
            result = apg.Generate(args);
            result.Should().BeTrue("Generator should succeed if there are no licenses to accept");

            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "parent.id"));
            logger.AssertWarningNotLogged("child.id");
            logger.AssertWarningNotLogged("grandchild.id");
            logger.AssertWarningsLogged(2);
            logger.AssertErrorsLogged(0);
        }
Ejemplo n.º 4
0
        public void Generate_SqaleFileNotSpecified_TemplateFileCreated()
        {
            // Arrange
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");

            TestLogger        logger            = new TestLogger();
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(this.TestContext);
            IPackage          child1            = CreatePackageWithAnalyzer(remoteRepoBuilder, "child1.requiredAccept.id", "2.1", License.NotRequired);
            IPackage          child2            = CreatePackageWithAnalyzer(remoteRepoBuilder, "child2.id", "2.2", License.NotRequired);
            IPackage          parent            = CreatePackageWithAnalyzer(remoteRepoBuilder, "parent.id", "1.0", License.NotRequired, child1, child2);

            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(remoteRepoBuilder.FakeRemoteRepo, GetLocalNuGetDownloadDir(), logger);

            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);

            // 1. Generate a plugin for the target package only. Expecting a plugin and a template SQALE file.
            ProcessedArgs args   = CreateArgs("parent.id", "1.0", "cs", null, false, false, outputDir);
            bool          result = apg.Generate(args);

            Assert.IsTrue(result, "Expecting generation to have succeeded");
            AssertSqaleFileExistsForPackage(logger, outputDir, parent);

            // 2. Generate a plugin for target package and all dependencies. Expecting three plugins and associated SQALE files.
            logger.Reset();
            args   = CreateArgs("parent.id", "1.0", "cs", null, false, true /* /recurse = true */, outputDir);
            result = apg.Generate(args);

            Assert.IsTrue(result, "Expecting generation to have succeeded");
            logger.AssertSingleWarningExists(UIResources.APG_RecurseEnabled_SQALENotEnabled);
            AssertSqaleFileExistsForPackage(logger, outputDir, parent);
            AssertSqaleFileExistsForPackage(logger, outputDir, child1);
            AssertSqaleFileExistsForPackage(logger, outputDir, child2);
        }
        public void GetDependencies_DependenciesNotInstalledLocally_Warning()
        {
            // Arrange
            string            targetNuGetRoot   = TestUtils.CreateTestDirectory(TestContext, ".nuget.target");
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(TestContext);
            string            dummyContentFile  = CreateDummyContentFile();

            IEnumerable <IPackage> actualDependencies;

            // Build a dependency graph: "main" depends on "dependency"
            IPackage dependencyPackage = remoteRepoBuilder.CreatePackage("dependency.package.id", "1.2", dummyContentFile, RemoteRepoBuilder.License.Required /* no dependencies */);
            IPackage mainPackage       = remoteRepoBuilder.CreatePackage("a", "2.0", dummyContentFile, RemoteRepoBuilder.License.NotRequired, dependencyPackage);

            // 1. Dependencies have not been installed locally -> warning but no error
            TestLogger          logger      = new TestLogger();
            NuGetPackageHandler testSubject = new NuGetPackageHandler(remoteRepoBuilder.FakeRemoteRepo, targetNuGetRoot, logger);

            actualDependencies = testSubject.GetInstalledDependencies(mainPackage);
            AssertExpectedPackageIds(actualDependencies /* no dependencies resolved*/);

            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(1);
            logger.AssertSingleWarningExists("dependency.package.id");

            // 2. Now install the package -> dependencies should resolve ok
            logger      = new TestLogger();
            testSubject = new NuGetPackageHandler(remoteRepoBuilder.FakeRemoteRepo, targetNuGetRoot, logger);

            testSubject.FetchPackage(mainPackage.Id, mainPackage.Version);
            actualDependencies = testSubject.GetInstalledDependencies(mainPackage);
            AssertExpectedPackageIds(actualDependencies, "dependency.package.id");

            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(0);
        }
Ejemplo n.º 6
0
        public void ArgProc_SonarVerbose_IsBool()
        {
            var logger = new TestLogger();

            var 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 Generate_LicenseAcceptanceRequiredByDependency()
        {
            // Arrange
            string            outputDir         = TestUtils.CreateTestDirectory(TestContext, ".out");
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(TestContext);

            // Parent and child: only child requires license
            IPackage child = CreatePackageWithAnalyzer(remoteRepoBuilder, "child.requiredAccept.id", "2.0", License.Required);

            CreatePackageWithAnalyzer(remoteRepoBuilder, "parent.id", "1.0", License.NotRequired, child);

            TestLogger logger           = new TestLogger();
            AnalyzerPluginGenerator apg = CreateTestSubjectWithFakeRemoteRepo(remoteRepoBuilder, logger);

            // 1. User does not accept -> fails with error
            ProcessedArgs args = CreateArgs("parent.id", "1.0", "cs", false /* accept licenses */,
                                            false, outputDir);
            bool result = apg.Generate(args);

            result.Should().BeFalse("Generator should fail because license has not been accepted");

            logger.AssertSingleErrorExists("parent.id", "1.0");                 // error listing the main package
            logger.AssertSingleWarningExists("child.requiredAccept.id", "2.0"); // warning for each licensed package
            logger.AssertWarningsLogged(1);

            // 2. User accepts -> succeeds with warnings
            logger.Reset();
            args = CreateArgs("parent.id", "1.0", "cs", true /* accept licenses */,
                              false, outputDir);
            result = apg.Generate(args);
            result.Should().BeTrue("Generator should succeed if licenses are accepted");

            logger.AssertSingleWarningExists(UIResources.APG_NGAcceptedPackageLicenses); // warning that licenses have been accepted
            logger.AssertSingleWarningExists("child.requiredAccept.id", "2.0");          // warning for each licensed package
            logger.AssertWarningsLogged(2);
            logger.AssertErrorsLogged(0);
        }
Ejemplo n.º 8
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");
        }
Ejemplo n.º 9
0
        public void TrxReader_TrxWithMultipleAttachments()
        {
            // Arrange
            string testDir    = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string resultsDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "TestResults");

            TestUtils.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);
        }
Ejemplo n.º 10
0
        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
        }
Ejemplo n.º 11
0
        public void TrxReader_MultipleTrxFiles()
        {
            // Arrange
            string     testDir    = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string     resultsDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "TestResults");
            string     trx1       = TestUtils.CreateTextFile(resultsDir, "mytrx1.trx", "<TestRun />");
            string     trx2       = TestUtils.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 TrxReader_InvalidTrxFile()
        {
            // Arrange
            var testDir    = TestUtils.CreateTestSpecificFolder(TestContext);
            var resultsDir = TestUtils.CreateTestSpecificFolder(TestContext, "TestResults");

            TestUtils.CreateTextFile(resultsDir, "dummy.trx", "this is not a trx file");
            var logger = new TestLogger();

            // Act
            var coverageFilePath = new TrxFileReader(logger).LocateCodeCoverageFile(testDir);

            // Assert
            coverageFilePath.Should().BeNull();

            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
            var testDir    = TestUtils.CreateTestSpecificFolder(TestContext);
            var resultsDir = TestUtils.CreateTestSpecificFolder(TestContext, "TestResults");
            var trx1       = TestUtils.CreateTextFile(resultsDir, "mytrx1.trx", "<TestRun />");
            var trx2       = TestUtils.CreateTextFile(resultsDir, "mytrx2.trx", "<TestRun />");
            var logger     = new TestLogger();

            // Act
            var coverageFilePath = new TrxFileReader(logger).LocateCodeCoverageFile(testDir);

            // Assert
            coverageFilePath.Should().BeNull();

            logger.AssertSingleWarningExists(trx1, trx2); // expecting a warning referring the log files
            logger.AssertErrorsLogged(0);
        }
Ejemplo n.º 14
0
        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 Generate_LicenseAcceptanceRequired_ByParentAndDependencies()
        {
            // Arrange
            string            outputDir         = TestUtils.CreateTestDirectory(TestContext, ".out");
            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(TestContext);

            // Multi-level: parent and some but not all dependencies require license acceptance
            IPackage grandchild1 = CreatePackageWithAnalyzer(remoteRepoBuilder, "grandchild1.requiredAccept.id", "3.0", License.Required);
            IPackage child1      = CreatePackageWithAnalyzer(remoteRepoBuilder, "child1.requiredAccept.id", "2.1", License.Required);
            IPackage child2      = CreatePackageWithAnalyzer(remoteRepoBuilder, "child2.id", "2.2", License.NotRequired, grandchild1);

            CreatePackageWithAnalyzer(remoteRepoBuilder, "parent.requiredAccept.id", "1.0", License.Required, child1, child2);

            TestLogger logger           = new TestLogger();
            AnalyzerPluginGenerator apg = CreateTestSubjectWithFakeRemoteRepo(remoteRepoBuilder, logger);

            // 1. a) Only target package. User does not accept -> fails with error
            ProcessedArgs args = CreateArgs("parent.requiredAccept.id", "1.0", "cs", false /* accept licenses */,
                                            false, outputDir);
            bool result = apg.Generate(args);

            result.Should().BeFalse("Generator should fail because license has not been accepted");

            logger.AssertSingleErrorExists("parent.requiredAccept.id", "1.0");        // error referring to the main package

            logger.AssertSingleWarningExists("grandchild1.requiredAccept.id", "3.0"); // warning for each licensed package
            logger.AssertSingleWarningExists("child1.requiredAccept.id", "2.1");
            logger.AssertSingleWarningExists("parent.requiredAccept.id", "1.0");

            // 2. User accepts -> succeeds with warnings
            logger.Reset();
            args = CreateArgs("parent.requiredAccept.id", "1.0", "cs", true /* accept licenses */,
                              false, outputDir);
            result = apg.Generate(args);
            result.Should().BeTrue("Generator should succeed if licenses are accepted");

            logger.AssertSingleWarningExists(UIResources.APG_NGAcceptedPackageLicenses); // warning that licenses have been accepted
            logger.AssertSingleWarningExists("grandchild1.requiredAccept.id", "3.0");    // warning for each licensed package
            logger.AssertSingleWarningExists("child1.requiredAccept.id", "2.1");
            logger.AssertSingleWarningExists("parent.requiredAccept.id", "1.0");
            logger.AssertWarningsLogged(4);
        }
        public void Generate_RulesFileNotSpecified_TemplateFileCreated()
        {
            // Arrange
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");

            var logger            = new TestLogger();
            var remoteRepoBuilder = new RemoteRepoBuilder(this.TestContext);
            var child1            = CreatePackageWithAnalyzer(remoteRepoBuilder, "child1.requiredAccept.id", "2.1", License.NotRequired);
            var child2            = CreatePackageWithAnalyzer(remoteRepoBuilder, "child2.id", "2.2", License.NotRequired);
            var parent            = CreatePackageWithAnalyzer(remoteRepoBuilder, "parent.id", "1.0", License.NotRequired, child1, child2);

            var nuGetHandler = new NuGetPackageHandler(remoteRepoBuilder.FakeRemoteRepo, GetLocalNuGetDownloadDir(), logger);

            var testSubject = new AnalyzerPluginGenerator(nuGetHandler, logger);

            // 1. Generate a plugin for the target package only. Expecting a plugin and a template rule file.
            var args = new ProcessedArgsBuilder("parent.id", outputDir)
                       .SetLanguage("cs")
                       .SetPackageVersion("1.0")
                       .SetRecurseDependencies(true)
                       .Build();
            bool result = testSubject.Generate(args);

            result.Should().BeTrue();

            AssertRuleTemplateFileExistsForPackage(logger, outputDir, parent);

            // 2. Generate a plugin for target package and all dependencies. Expecting three plugins and associated rule files.
            logger.Reset();
            args   = CreateArgs("parent.id", "1.0", "cs", false, true /* /recurse = true */, outputDir);
            result = testSubject.Generate(args);
            result.Should().BeTrue();

            logger.AssertSingleWarningExists(UIResources.APG_RecurseEnabled_RuleCustomizationNotEnabled);
            AssertRuleTemplateFileExistsForPackage(logger, outputDir, parent);
            AssertRuleTemplateFileExistsForPackage(logger, outputDir, child1);
            AssertRuleTemplateFileExistsForPackage(logger, outputDir, child2);
        }
Ejemplo n.º 17
0
        public void ArgProc_BeginVerb()
        {
            // Arrange
            var logger   = new TestLogger();
            var validUrl = "/d:sonar.host.url=http://foo";

            // 1. Minimal parameters -> valid
            var 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 unrecognized 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 RepoFactory_FailingRepo_ErrorLoggedAndSuppressed()
        {
            // Arrange
            TestLogger logger = new TestLogger();

            string configXml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageSources>
    <add key=""remote_bad"" value=""http://bad.remote.unreachable.repo"" />
  </packageSources>
</configuration>";

            Settings settings = CreateSettingsFromXml(configXml);

            // Act
            IPackageRepository actualRepo     = NuGetRepositoryFactory.CreateRepository(settings, logger);
            IPackage           locatedPackage = actualRepo.FindPackage("dummy.package.id"); // trying to use the bad repo should fail

            // Assert
            Assert.IsNull(locatedPackage, "Should have failed to locate a package");
            logger.AssertSingleWarningExists(NuGetLoggerAdapter.LogMessagePrefix, "http://bad.remote.unreachable.repo");
            logger.AssertWarningsLogged(1);
            logger.AssertErrorsLogged(0);
        }
        public void Generate_LicenseAcceptanceRequired_NoAnalysersInTarget()
        {
            // If there are:
            // Required licenses
            // No analyzers in the targeted package, but analyzers in the dependencies
            // We should fail due to the absence of analyzers if we are only generating a plugin for the targeted package
            // We should fail with an error due to licenses if we are generating plugins for the targeted package and dependencies

            // Arrange
            string outputDir        = TestUtils.CreateTestDirectory(TestContext, ".out");
            string dummyContentFile = TestUtils.CreateTextFile("dummy.txt", outputDir, "non-analyzer content file");

            RemoteRepoBuilder remoteRepoBuilder = new RemoteRepoBuilder(TestContext);

            // Multi-level: parent and some but not all dependencies require license acceptance
            // Parent has no analyzers, but dependencies do
            IPackage child1 = CreatePackageWithAnalyzer(remoteRepoBuilder, "child1.requiredAccept.id", "2.1", License.Required);
            IPackage child2 = CreatePackageWithAnalyzer(remoteRepoBuilder, "child2.id", "2.2", License.NotRequired);

            remoteRepoBuilder.CreatePackage("non-analyzer.parent.requireAccept.id", "1.0", dummyContentFile, License.Required, child1, child2);

            TestLogger logger           = new TestLogger();
            AnalyzerPluginGenerator apg = CreateTestSubjectWithFakeRemoteRepo(remoteRepoBuilder, logger);

            // 1. a) Only target package. User does not accept, but no analyzers so no license prompt -> fails due to absence of analyzers
            ProcessedArgs args = CreateArgs("non-analyzer.parent.requireAccept.id", "1.0", "cs", false /* accept licenses */,
                                            false, outputDir);
            bool result = apg.Generate(args);

            result.Should().BeFalse("Expecting generator to fail");

            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "non-analyzer.parent.requireAccept.id"));
            logger.AssertSingleWarningExists(UIResources.APG_NoAnalyzersInTargetSuggestRecurse);
            logger.AssertWarningsLogged(2);
            logger.AssertErrorsLogged(0);

            // 1. b) Target package and dependencies. User does not accept.
            // No analyzers in the target package, but analyzers in the dependencies -> fails with error
            logger.Reset();
            args = CreateArgs("non-analyzer.parent.requireAccept.id", "1.0", "cs", false /* accept licenses */,
                              true /* generate plugins for dependencies */, outputDir);
            result = apg.Generate(args);
            result.Should().BeFalse("Generator should fail because license has not been accepted");

            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "non-analyzer.parent.requireAccept.id"));
            logger.AssertSingleWarningExists("non-analyzer.parent.requireAccept.id", "1.0"); // warning for each licensed package
            logger.AssertSingleWarningExists(child1.Id, child1.Version.ToString());
            logger.AssertWarningsLogged(3);
            logger.AssertSingleErrorExists("non-analyzer.parent.requireAccept.id", "1.0"); // error listing the main package
            logger.AssertErrorsLogged(1);

            // 2. b) Target package and dependencies. User accepts.
            // No analyzers in the target package, but analyzers in the dependencies -> succeeds with warnings
            logger.Reset();
            args = CreateArgs("non-analyzer.parent.requireAccept.id", "1.0", "cs", true /* accept licenses */,
                              true /* generate plugins for dependencies */, outputDir);
            result = apg.Generate(args);
            result.Should().BeTrue("Generator should succeed if licenses are accepted");

            logger.AssertSingleWarningExists(String.Format(UIResources.APG_NoAnalyzersFound, "non-analyzer.parent.requireAccept.id"));
            logger.AssertSingleWarningExists(UIResources.APG_NGAcceptedPackageLicenses);     // warning that licenses have been accepted
            logger.AssertSingleWarningExists("non-analyzer.parent.requireAccept.id", "1.0"); // warning for each licensed package
            logger.AssertSingleWarningExists(child1.Id, child1.Version.ToString());
            logger.AssertWarningsLogged(5);
            logger.AssertErrorsLogged(0);
        }
Ejemplo n.º 20
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);
        }
        public void Exe__Version0_9Compatibility()
        {
            // Tests compatibility with the bootstrapper API used in v0.9
            // The pre-processor should be called if any arguments are passed.
            // The post-processor should be called if no arguments are passed.

            // Default settings:
            // There must be a default settings file next to the bootstrapper exe to supply
            // the necessary settings, and the bootstrapper should pass this settings path
            // to the pre-processor (since the pre-process is downloaded to a different
            // directory).

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

            using (InitializeNonTeamBuildEnvironment(rootDir))
            {
                string binDir = CalculateBinDir(rootDir);
                MockBuildAgentUpdater mockUpdater = CreateValidUpdater(binDir, "http://host");

                mockUpdater.Updating += (sender, args) =>
                {
                    Assert.IsTrue(Directory.Exists(args.TargetDir), "Expecting the target directory to have been created");
                    DummyExeHelper.CreateDummyPreProcessor(args.TargetDir, 0 /* post-proc succeeds */);
                    DummyExeHelper.CreateDummyPostProcessor(args.TargetDir, 0 /* post-proc succeeds */);
                };

                // Create a default properties file next to the exe
                AnalysisProperties defaultProperties = new AnalysisProperties();
                defaultProperties.Add(new Property()
                {
                    Id = SonarProperties.HostUrl, Value = "http://host"
                });
                string defaultPropertiesFilePath = CreateDefaultPropertiesFile(defaultProperties);

                // Act
                try
                {
                    // Call the pre-processor
                    TestLogger logger = CheckExecutionSucceeds(mockUpdater, "/v:version", "/n:name", "/k:key");
                    logger.AssertWarningsLogged(1); // Should be warned once about the missing "begin" / "end"
                    logger.AssertSingleWarningExists(ArgumentProcessor.BeginVerb, ArgumentProcessor.EndVerb);

                    mockUpdater.AssertUpdateAttempted();
                    mockUpdater.AssertVersionChecked();

                    string logPath = DummyExeHelper.AssertDummyPreProcLogExists(binDir, this.TestContext);
                    DummyExeHelper.AssertExpectedLogContents(logPath,
                                                             "/v:version",
                                                             "/n:name",
                                                             "/k:key",
                                                             "/s:" + defaultPropertiesFilePath);

                    DummyExeHelper.AssertDummyPostProcLogDoesNotExist(binDir);

                    // Call the post-process (no arguments)
                    logger = CheckExecutionSucceeds(mockUpdater);

                    logPath = DummyExeHelper.AssertDummyPostProcLogExists(binDir, this.TestContext);
                    DummyExeHelper.AssertExpectedLogContents(logPath, null);

                    logger.AssertWarningsLogged(1); // Should be warned once about the missing "begin" / "end"
                    logger.AssertSingleWarningExists(ArgumentProcessor.BeginVerb, ArgumentProcessor.EndVerb);
                }
                finally
                {
                    File.Delete(defaultPropertiesFilePath);
                }
            }
        }