public void RuleSetUpdater_FindAllIncludesUnderRoot()
        {
            // Arrange
            const string slnRoot     = @"X:\SolutionDir\";
            string       projectRoot = Path.Combine(slnRoot, @"Project\");
            string       sonarRoot   = Path.Combine(slnRoot, @"Sonar\");
            string       commonRoot  = Path.Combine(slnRoot, @"Common\");

            const string sonarRs1FileName      = "Sonar1.ruleset";
            const string sonarRs2FileName      = "Sonar2.ruleset";
            const string projectRsBaseFileName = "ProjectBase.ruleset";
            const string commonRs1FileName     = "SolutionCommon1.ruleset";
            const string commonRs2FileName     = "SolutionCommon2.ruleset";

            var sonarRs1      = TestRuleSetHelper.CreateTestRuleSet(sonarRoot, sonarRs1FileName);
            var sonarRs2      = TestRuleSetHelper.CreateTestRuleSet(sonarRoot, sonarRs2FileName);
            var projectBaseRs = TestRuleSetHelper.CreateTestRuleSet(projectRoot, projectRsBaseFileName);
            var commonRs1     = TestRuleSetHelper.CreateTestRuleSet(commonRoot, commonRs1FileName);
            var commonRs2     = TestRuleSetHelper.CreateTestRuleSet(commonRoot, commonRs2FileName);

            var inputRuleSet = TestRuleSetHelper.CreateTestRuleSet(projectRoot, "test.ruleset");

            AddRuleSetInclusion(inputRuleSet, projectBaseRs, useRelativePath: true);
            AddRuleSetInclusion(inputRuleSet, commonRs1, useRelativePath: true);
            AddRuleSetInclusion(inputRuleSet, commonRs2, useRelativePath: false);
            var expected1 = AddRuleSetInclusion(inputRuleSet, sonarRs1, useRelativePath: true);
            var expected2 = AddRuleSetInclusion(inputRuleSet, sonarRs2, useRelativePath: false);

            // Act
            RuleSetInclude[] actual = RuleSetUpdater.FindAllIncludesUnderRoot(inputRuleSet, sonarRoot).ToArray();

            // Assert
            CollectionAssert.AreEquivalent(new[] { expected1, expected2 }, actual);
        }
        private static RuleConflictInfo CreateConflictsBasedOnNumberOfCalls(int findConflictCalls)
        {
            RuleSet temp = TestRuleSetHelper.CreateTestRuleSet(2);
            Dictionary <RuleReference, RuleAction> map = new Dictionary <RuleReference, RuleAction>();

            switch (findConflictCalls)
            {
            case 1:
                return(new RuleConflictInfo());    // No conflicts

            case 2:
                return(new RuleConflictInfo(temp.Rules));    // Missing rules

            case 3:
                map[temp.Rules[0]] = RuleAction.Error;
                return(new RuleConflictInfo(map));    // Weakened rules

            case 4:
                map[temp.Rules[0]] = RuleAction.Error;
                return(new RuleConflictInfo(temp.Rules.Skip(1), map));    // One of each

            default:
                FluentAssertions.Execution.Execute.Assertion.FailWith("Called unexpected number of times");
                return(null);
            }
        }
        public void HasInclude_RelativePaths()
        {
            // Arrange
            var target = TestRuleSetHelper.CreateTestRuleSet(@"c:\aaa\Solution\SomeFolder\fullFilePath.ruleset");

            var relativeInclude           = @"Solution\SomeFolder\fullFilePath.ruleset".ToLowerInvariant(); // Catch casing errors
            var sourceWithRelativeInclude = TestRuleSetHelper.CreateTestRuleSetWithIncludes(@"c:\aaa\fullFilePath.ruleset",
                                                                                            relativeInclude, "otherInclude.ruleset");

            // Alternative directory separator, different relative path format
            var relativeInclude2           = @"./Solution/SomeFolder/fullFilePath.ruleset";
            var sourceWithRelativeInclude2 = TestRuleSetHelper.CreateTestRuleSetWithIncludes(@"c:\aaa\fullFilePath.ruleset",
                                                                                             "c://XXX/Solution/SomeFolder/another.ruleset", relativeInclude2);

            // Case 1: Relative include
            // Act
            var hasInclude = RuleSetIncludeChecker.HasInclude(sourceWithRelativeInclude, target);

            // Assert
            hasInclude.Should().BeTrue();

            // Case 2: Relative include, alternative path separators
            // Act
            hasInclude = RuleSetIncludeChecker.HasInclude(sourceWithRelativeInclude2, target);

            // Assert
            hasInclude.Should().BeTrue();
        }
        public async Task GetConfig_LegacyMode_WithNoNugetPackage_Fails()
        {
            // Arrange
            const string QualityProfileName = "SQQualityProfileName";
            const string ProjectName        = "SQProjectName";
            var          legacyNuGetBinding = new NuGetBindingOperation(new ConfigurableHost(), this.logger);
            var          testSubject        = this.CreateTestSubject("key", ProjectName, legacyNuGetBinding);

            RuleSet ruleSet         = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(new[] { "Key1", "Key2" });
            var     additionalFiles = new[] { new AdditionalFileResponse {
                                                  FileName = "abc.xml", Content = new byte[] { 1, 2, 3 }
                                              } };
            RoslynExportProfileResponse export = RoslynExportProfileHelper.CreateExport(ruleSet, Enumerable.Empty <PackageName>(), additionalFiles);

            var language = Language.VBNET;
            var profile  = this.ConfigureProfileExport(export, language, QualityProfileName);

            // Act
            var result = await testSubject.GetConfigurationAsync(profile, null, language, CancellationToken.None)
                         .ConfigureAwait(false);

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

            this.logger.AssertOutputStrings(1);
            var expectedOutput = string.Format(Strings.SubTextPaddingFormat,
                                               string.Format(Strings.NoNuGetPackageForQualityProfile, language.Name));

            this.logger.AssertOutputStrings(expectedOutput);
        }
        public async Task GetConfig_WithNoActiveRules_Fails()
        {
            // Arrange
            const string QualityProfileName = "SQQualityProfileName";
            const string ProjectName        = "SQProjectName";
            var          testSubject        = this.CreateTestSubject(ProjectName, "http://connected");

            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(new[] { "Key1", "Key2" });

            foreach (var rule in ruleSet.Rules)
            {
                rule.Action = RuleAction.None;
            }
            var nugetPackages   = new[] { new PackageName("myPackageId", new SemanticVersion("1.0.0")) };
            var additionalFiles = new[] { new AdditionalFileResponse {
                                              FileName = "abc.xml", Content = new byte[] { 1, 2, 3 }
                                          } };
            RoslynExportProfileResponse export = RoslynExportProfileHelper.CreateExport(ruleSet, nugetPackages, additionalFiles);

            var language = Language.VBNET;
            var profile  = this.ConfigureProfileExport(export, language, QualityProfileName);

            // Act
            var result = await testSubject.GetConfigurationAsync(profile, null, language, CancellationToken.None)
                         .ConfigureAwait(false);

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

            this.logger.AssertOutputStrings(1);
            var expectedOutput = string.Format(Strings.SubTextPaddingFormat,
                                               string.Format(Strings.NoSonarAnalyzerActiveRulesForQualityProfile, QualityProfileName, language.Name));

            this.logger.AssertOutputStrings(expectedOutput);
        }
        public async Task BindingWorkflow_DownloadQualityProfile_WithNoRules_Fails()
        {
            // Arrange
            const string    QualityProfileName        = "SQQualityProfileName";
            const string    ProjectName               = "SQProjectName";
            BindingWorkflow testSubject               = this.CreateTestSubject("key", ProjectName);
            ConfigurableProgressController controller = new ConfigurableProgressController();
            var notifications = new ConfigurableProgressStepExecutionEvents();

            RuleSet ruleSet         = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(Enumerable.Empty <string>());
            var     nugetPackages   = new[] { new PackageName("myPackageId", new SemanticVersion("1.0.0")) };
            var     additionalFiles = new[] { new AdditionalFileResponse {
                                                  FileName = "abc.xml", Content = new byte[] { 1, 2, 3 }
                                              } };
            RoslynExportProfileResponse export = RoslynExportProfileHelper.CreateExport(ruleSet, nugetPackages, additionalFiles);

            var language = Language.VBNET;
            SonarQubeQualityProfile profile = this.ConfigureProfileExport(export, language, QualityProfileName);

            // Act
            await testSubject.DownloadQualityProfileAsync(controller, notifications, new[] { language }, CancellationToken.None);

            // Assert
            testSubject.Rulesets.Should().NotContainKey(Language.VBNET, "Not expecting any rules for this language");
            testSubject.Rulesets.Should().NotContainKey(language, "Not expecting any rules");
            controller.NumberOfAbortRequests.Should().Be(1);

            notifications.AssertProgressMessages(Strings.DownloadingQualityProfileProgressMessage);

            this.outputWindowPane.AssertOutputStrings(1);
            var expectedOutput = string.Format(Strings.SubTextPaddingFormat,
                                               string.Format(Strings.NoSonarAnalyzerActiveRulesForQualityProfile, QualityProfileName, language.Name));

            this.outputWindowPane.AssertOutputStrings(expectedOutput);
        }
Exemplo n.º 7
0
        private static void AssertConfigSectionEqual(Configuration expected, Configuration actual)
        {
            CollectionAssert.AreEqual(expected.AdditionalFiles, actual.AdditionalFiles, "Additional files differ");

            RuleSet expectedRuleSet = TestRuleSetHelper.XmlToRuleSet(expected.RuleSet.OuterXml);
            RuleSet actualRuleSet = TestRuleSetHelper.XmlToRuleSet(actual.RuleSet.OuterXml);
            RuleSetAssert.AreEqual(expectedRuleSet, actualRuleSet, "Rule sets differ");
        }
Exemplo n.º 8
0
        private static void AssertConfigSectionEqual(ConfigurationResponse expected, ConfigurationResponse actual)
        {
            actual.AdditionalFiles.Should().BeEquivalentTo(expected.AdditionalFiles, "Additional files differ");

            RuleSet expectedRuleSet = TestRuleSetHelper.XmlToRuleSet(expected.RuleSet.OuterXml);
            RuleSet actualRuleSet   = TestRuleSetHelper.XmlToRuleSet(actual.RuleSet.OuterXml);

            RuleSetAssert.AreEqual(expectedRuleSet, actualRuleSet, "Rule sets differ");
        }
Exemplo n.º 9
0
        public void RuleSetSerializer_WriteRuleSetFile_ArgChecks()
        {
            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSet(this.TestContext.TestRunDirectory, this.TestContext.TestName + ".ruleset");

            Exceptions.Expect <ArgumentNullException>(() => this.testSubject.WriteRuleSetFile(null, @"c:\file.ruleSet"));
            Exceptions.Expect <ArgumentNullException>(() => this.testSubject.WriteRuleSetFile(ruleSet, null));
            Exceptions.Expect <ArgumentNullException>(() => this.testSubject.WriteRuleSetFile(ruleSet, ""));
            Exceptions.Expect <ArgumentNullException>(() => this.testSubject.WriteRuleSetFile(ruleSet, "\t\n"));
        }
        private RuleSet CreateCommonRuleSet(string ruleSetFileName = "SonarQube.ruleset", RuleAction defaultAction = RuleAction.Warning, int rules = DefaultNumberOfRules)
        {
            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSet(rules);

            ruleSet.Rules.ToList().ForEach(r => r.Action = defaultAction);
            ruleSet.FilePath = Path.Combine(this.SonarQubeRuleSetFolder, ruleSetFileName);
            ruleSet.WriteToFile(ruleSet.FilePath);

            this.temporaryFiles.AddFile(ruleSet.FilePath, false);
            return(ruleSet);
        }
        public static ProjectRuleSetConflict CreateConflict(string projectFilePath = "project.csproj", string baselineRuleSet = "baseline.ruleset", string projectRuleSet = "project.csproj", int numberOfConflictingRules = 1)
        {
            IEnumerable <string> ids = Enumerable.Range(0, numberOfConflictingRules).Select(i => "id" + i);
            var ruleSet = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(ids);

            var conflict = new ProjectRuleSetConflict(
                new RuleConflictInfo(ruleSet.Rules, new Dictionary <RuleReference, RuleAction>()),
                new RuleSetInformation(projectFilePath, baselineRuleSet, projectRuleSet, null));

            return(conflict);
        }
        public void HasInclude_NoIncludes()
        {
            // Arrange
            var ruleSet             = TestRuleSetHelper.CreateTestRuleSet(@"c:\Solution\SomeFolder\fullFilePath.ruleset");
            var unreferencedRuleset = TestRuleSetHelper.CreateTestRuleSet(@"c:\unreferenced.ruleset");

            // Act No includes at all
            var include = RuleSetIncludeChecker.HasInclude(ruleSet, unreferencedRuleset);

            // Assert
            include.Should().BeFalse();
        }
        private RuleSet CreateVsRuleSet(int rules, string ruleSetFileName, RuleAction defaultAction = RuleAction.Warning)
        {
            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSet(rules);

            ruleSet.Rules.ToList().ForEach(r => r.Action = defaultAction);
            ruleSet.FilePath = Path.Combine(this.VsRuleSetsDirectory, ruleSetFileName);
            ruleSet.WriteToFile(ruleSet.FilePath);

            this.temporaryFiles.AddFile(ruleSet.FilePath, false);

            return(ruleSet);
        }
        public void ToRuleSet_DumpsContentToRuleSetFileAndLoadsIt()
        {
            // Arrange
            var ruleset = TestRuleSetHelper.CreateTestRuleSet(numRules: 10);
            var roslynProfileExporter = RoslynExportProfileHelper.CreateExport(ruleset);

            // Act
            var result = RulesHelper.ToRuleSet(roslynProfileExporter);

            // Assert
            TestRuleSetHelper.RuleSetToXml(result).Should().Be(TestRuleSetHelper.RuleSetToXml(ruleset));
        }
        public async Task BindingWorkflow_DownloadQualityProfile_Success()
        {
            // Arrange
            const string QualityProfileName = "SQQualityProfileName";
            const string ProjectName        = "SQProjectName";

            // Record all of the calls to NuGetBindingOperation.ProcessExport
            var actualProfiles = new List <Tuple <Language, RoslynExportProfileResponse> >();
            Mock <INuGetBindingOperation> nuGetOpMock = new Mock <INuGetBindingOperation>();

            nuGetOpMock.Setup(x => x.ProcessExport(It.IsAny <Language>(), It.IsAny <RoslynExportProfileResponse>()))
            .Callback <Language, RoslynExportProfileResponse>((l, r) => actualProfiles.Add(new Tuple <Language, RoslynExportProfileResponse>(l, r)))
            .Returns(true);

            BindingWorkflow testSubject = this.CreateTestSubject("key", ProjectName, nuGetOpMock.Object);


            ConfigurableProgressController controller = new ConfigurableProgressController();
            var notifications = new ConfigurableProgressStepExecutionEvents();

            RuleSet ruleSet         = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(new[] { "Key1", "Key2" });
            var     expectedRuleSet = new RuleSet(ruleSet)
            {
                NonLocalizedDisplayName = string.Format(Strings.SonarQubeRuleSetNameFormat, ProjectName, QualityProfileName),
                NonLocalizedDescription = "\r\nhttp://connected/profiles/show?key="
            };
            var nugetPackages   = new[] { new PackageName("myPackageId", new SemanticVersion("1.0.0")) };
            var additionalFiles = new[] { new AdditionalFileResponse {
                                              FileName = "abc.xml", Content = new byte[] { 1, 2, 3 }
                                          } };
            RoslynExportProfileResponse export = RoslynExportProfileHelper.CreateExport(ruleSet, nugetPackages, additionalFiles);

            var language = Language.VBNET;
            SonarQubeQualityProfile profile = this.ConfigureProfileExport(export, language, QualityProfileName);

            // Act
            await testSubject.DownloadQualityProfileAsync(controller, notifications, new[] { language }, CancellationToken.None);

            // Assert
            RuleSetAssert.AreEqual(expectedRuleSet, testSubject.Rulesets[language], "Unexpected rule set");
            testSubject.QualityProfiles[language].Should().Be(profile);
            VerifyNuGetPackgesDownloaded(nugetPackages, language, actualProfiles);

            controller.NumberOfAbortRequests.Should().Be(0);
            notifications.AssertProgress(0.0, 1.0);
            notifications.AssertProgressMessages(Strings.DownloadingQualityProfileProgressMessage, string.Empty);

            this.outputWindowPane.AssertOutputStrings(1);
            var expectedOutput = string.Format(Strings.SubTextPaddingFormat,
                                               string.Format(Strings.QualityProfileDownloadSuccessfulMessageFormat, QualityProfileName, string.Empty, language.Name));

            this.outputWindowPane.AssertOutputStrings(expectedOutput);
        }
        public void ToQualityProfile_SelectRulesNotMarkedAsNone()
        {
            // Arrange
            var ruleset           = TestRuleSetHelper.CreateTestRuleSet(numRules: 5);
            var nonNoneRulesCount = ruleset.Rules.Count(x => x.Action != RuleAction.None);

            // Act
            var result = RulesHelper.ToQualityProfile(ruleset, Language.CSharp);

            // Assert
            result.Language.Should().Be(Language.CSharp);
            result.Rules.Should().HaveCount(nonNoneRulesCount);
        }
        public void HasInclude_NoIncludesFromSourceToTarget()
        {
            // Arrange
            var target = TestRuleSetHelper.CreateTestRuleSet(@"c:\Solution\SomeFolder\fullFilePath.ruleset");

            var sourceWithInclude = TestRuleSetHelper.CreateTestRuleSetWithIncludes(@"c:\fullFilePath.ruleset",
                                                                                    "include1", "c:\\foo\\include2", "fullFilePath.ruleset");

            // Act - No includes from source to target
            var include = RuleSetIncludeChecker.HasInclude(sourceWithInclude, target);

            // Assert
            include.Should().BeFalse();
        }
        public void BindingWorkflow_DownloadQualityProfile_WithNoActiveRules_Fails()
        {
            // Arrange
            const string QualityProfileName   = "SQQualityProfileName";
            const string SonarQubeProjectName = "SQProjectName";
            var          projectInfo          = new ProjectInformation {
                Key = "key", Name = SonarQubeProjectName
            };
            BindingWorkflow testSubject = this.CreateTestSubject(projectInfo);
            ConfigurableProgressController controller = new ConfigurableProgressController();
            var notifications = new ConfigurableProgressStepExecutionEvents();

            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(new[] { "Key1", "Key2" });

            foreach (var rule in ruleSet.Rules)
            {
                rule.Action = RuleAction.None;
            }
            var expectedRuleSet = new RuleSet(ruleSet)
            {
                NonLocalizedDisplayName = string.Format(Strings.SonarQubeRuleSetNameFormat, SonarQubeProjectName, QualityProfileName),
                NonLocalizedDescription = "\r\nhttp://connected/profiles/show?key="
            };
            var nugetPackages   = new[] { new PackageName("myPackageId", new SemanticVersion("1.0.0")) };
            var additionalFiles = new[] { new AdditionalFile {
                                              FileName = "abc.xml", Content = new byte[] { 1, 2, 3 }
                                          } };
            RoslynExportProfile export = RoslynExportProfileHelper.CreateExport(ruleSet, nugetPackages, additionalFiles);

            var            language = Language.VBNET;
            QualityProfile profile  = this.ConfigureProfileExport(export, language);

            profile.Name = QualityProfileName;

            // Act
            testSubject.DownloadQualityProfile(controller, CancellationToken.None, notifications, new[] { language });

            // Assert
            testSubject.Rulesets.Should().NotContainKey(Language.VBNET, "Not expecting any rules for this language");
            testSubject.Rulesets.Should().NotContainKey(language, "Not expecting any rules");
            controller.NumberOfAbortRequests.Should().Be(1);

            notifications.AssertProgressMessages(Strings.DownloadingQualityProfileProgressMessage);

            this.outputWindowPane.AssertOutputStrings(1);
            var expectedOutput = string.Format(Strings.SubTextPaddingFormat,
                                               string.Format(Strings.NoSonarAnalyzerActiveRulesForQualityProfile, QualityProfileName, language.Name));

            this.outputWindowPane.AssertOutputStrings(expectedOutput);
        }
        public void HasInclude_AbsolutePaths()
        {
            // Arrange
            var target = TestRuleSetHelper.CreateTestRuleSet(@"c:\Solution\SomeFolder\fullFilePath.ruleset");

            var absoluteInclude           = target.FilePath.ToUpperInvariant(); // Catch casing errors
            var sourceWithAbsoluteInclude = TestRuleSetHelper.CreateTestRuleSetWithIncludes(@"c:\fullFilePath.ruleset",
                                                                                            ".\\include1.ruleset", absoluteInclude, "c:\\dummy\\include2.ruleset");

            // Act
            var hasInclude = RuleSetIncludeChecker.HasInclude(sourceWithAbsoluteInclude, target);

            // Assert
            hasInclude.Should().BeTrue();
        }
        public void HasInclude_SourceIsTarget_ReturnsTrue()
        {
            // Covers the case where the ruleset is included directly in the project, rather
            // than indirectly as a RuleSetInclude in another ruleset.

            // Arrange
            var source = TestRuleSetHelper.CreateTestRuleSet(@"c:\Solution\SomeFolder\fullFilePath.ruleset");
            var target = TestRuleSetHelper.CreateTestRuleSet(@"C:/SOLUTION\./SomeFolder\fullFilePath.ruleset");

            // Act
            var include = RuleSetIncludeChecker.HasInclude(source, target);

            // Assert
            include.Should().BeTrue();
        }
        public void HasInclude_RelativePaths_Complex2()
        {
            // Arrange
            var target = TestRuleSetHelper.CreateTestRuleSet(@"c:\Solution\SomeFolder\fullFilePath.ruleset");

            var relativeInclude           = @"./.\..\..\Dummy1\Dummy2\..\.././Solution\SomeFolder\fullFilePath.ruleset";
            var sourceWithRelativeInclude = TestRuleSetHelper.CreateTestRuleSetWithIncludes(@"c:\aaa\bbb\fullFilePath.ruleset",
                                                                                            relativeInclude);

            // Act
            var hasInclude = RuleSetIncludeChecker.HasInclude(sourceWithRelativeInclude, target);

            // Assert
            hasInclude.Should().BeTrue();
        }
Exemplo n.º 22
0
        public void BindingWorkflow_DownloadQualityProfile_Success()
        {
            // Setup
            const string QualityProfileName   = "SQQualityProfileName";
            const string SonarQubeProjectName = "SQProjectName";
            var          projectInfo          = new ProjectInformation {
                Key = "key", Name = SonarQubeProjectName
            };
            BindingWorkflow testSubject = this.CreateTestSubject(projectInfo);
            ConfigurableProgressController controller = new ConfigurableProgressController();
            var notifications = new ConfigurableProgressStepExecutionEvents();

            RuleSet ruleSet         = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(new[] { "Key1", "Key2" });
            var     expectedRuleSet = new RuleSet(ruleSet)
            {
                NonLocalizedDisplayName = string.Format(Strings.SonarQubeRuleSetNameFormat, SonarQubeProjectName, QualityProfileName),
                NonLocalizedDescription = "\r\nhttp://connected/profiles/show?key="
            };
            var nugetPackages   = new[] { new PackageName("myPackageId", new SemanticVersion("1.0.0")) };
            var additionalFiles = new[] { new AdditionalFile {
                                              FileName = "abc.xml", Content = new byte[] { 1, 2, 3 }
                                          } };
            RoslynExportProfile export = RoslynExportProfileHelper.CreateExport(ruleSet, nugetPackages, additionalFiles);

            var            language = Language.VBNET;
            QualityProfile profile  = this.ConfigureProfileExport(export, language);

            profile.Name = QualityProfileName;

            // Act
            testSubject.DownloadQualityProfile(controller, CancellationToken.None, notifications, new[] { language });

            // Verify
            RuleSetAssert.AreEqual(expectedRuleSet, testSubject.Rulesets[language], "Unexpected rule set");
            Assert.AreSame(profile, testSubject.QualityProfiles[language]);
            VerifyNuGetPackgesDownloaded(nugetPackages, testSubject, language);
            controller.AssertNumberOfAbortRequests(0);
            notifications.AssertProgress(
                0.0,
                1.0);
            notifications.AssertProgressMessages(Strings.DownloadingQualityProfileProgressMessage, string.Empty);

            this.outputWindowPane.AssertOutputStrings(1);
            var expectedOutput = string.Format(Strings.SubTextPaddingFormat,
                                               string.Format(Strings.QualityProfileDownloadSuccessfulMessageFormat, QualityProfileName, string.Empty, language.Name));

            this.outputWindowPane.AssertOutputStrings(expectedOutput);
        }
Exemplo n.º 23
0
        public void RuleSetSerializer_LoadRuleSet()
        {
            // Setup
            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSet(this.TestContext.TestRunDirectory, this.TestContext.TestName + ".ruleset");

            this.temporaryFiles.AddFile(ruleSet.FilePath, false);
            ruleSet.WriteToFile(ruleSet.FilePath);
            this.fileSystem.RegisterFile(ruleSet.FilePath);

            // Act
            RuleSet loaded = this.testSubject.LoadRuleSet(ruleSet.FilePath);

            // Verify
            Assert.IsNotNull(loaded, "Expected to load a rule set file");
            RuleSetAssert.AreEqual(ruleSet, loaded, "Loaded unexpected rule set");
        }
Exemplo n.º 24
0
        public void RuleSetSerializer_LoadRuleSet()
        {
            // Arrange
            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSet(this.TestContext.TestRunDirectory, this.TestContext.TestName + ".ruleset");

            temporaryFiles.AddFile(ruleSet.FilePath, false);
            ruleSet.WriteToFile(ruleSet.FilePath);
            fileSystem.AddFile(ruleSet.FilePath, new MockFileData(""));

            // Act
            RuleSet loaded = this.testSubject.LoadRuleSet(ruleSet.FilePath);

            // Assert
            loaded.Should().NotBeNull("Expected to load a rule set file");
            RuleSetAssert.AreEqual(ruleSet, loaded, "Loaded unexpected rule set");
        }
        public async Task GetConfig_Success()
        {
            // Arrange
            const string QualityProfileName = "SQQualityProfileName";
            const string ProjectName        = "SQProjectName";

            // Record all of the calls to NuGetBindingOperation.ProcessExport
            var actualProfiles = new List <Tuple <Language, RoslynExportProfileResponse> >();
            Mock <INuGetBindingOperation> nuGetOpMock = new Mock <INuGetBindingOperation>();

            nuGetOpMock.Setup(x => x.ProcessExport(It.IsAny <Language>(), It.IsAny <RoslynExportProfileResponse>()))
            .Callback <Language, RoslynExportProfileResponse>((l, r) => actualProfiles.Add(new Tuple <Language, RoslynExportProfileResponse>(l, r)))
            .Returns(true);

            var testSubject = this.CreateTestSubject(ProjectName, "http://connected/", nuGetOpMock.Object);

            RuleSet ruleSet         = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(new[] { "Key1", "Key2" });
            var     expectedRuleSet = new RuleSet(ruleSet)
            {
                NonLocalizedDisplayName = string.Format(Strings.SonarQubeRuleSetNameFormat, ProjectName, QualityProfileName),
                NonLocalizedDescription = "\r\nhttp://connected/profiles/show?key="
            };
            var nugetPackages   = new[] { new PackageName("myPackageId", new SemanticVersion("1.0.0")) };
            var additionalFiles = new[] { new AdditionalFileResponse {
                                              FileName = "abc.xml", Content = new byte[] { 1, 2, 3 }
                                          } };
            RoslynExportProfileResponse export = RoslynExportProfileHelper.CreateExport(ruleSet, nugetPackages, additionalFiles);

            var language = Language.VBNET;
            SonarQubeQualityProfile profile = this.ConfigureProfileExport(export, language, QualityProfileName);

            // Act
            var result = await testSubject.GetConfigurationAsync(profile, "TODO", language, CancellationToken.None)
                         .ConfigureAwait(false);

            // Assert
            result.Should().NotBeNull();
            var dotNetResult = result as DotNetBindingConfigFile;

            dotNetResult.Should().NotBeNull();

            RuleSetAssert.AreEqual(expectedRuleSet, dotNetResult.RuleSet, "Unexpected rule set");
            VerifyNuGetPackgesDownloaded(nugetPackages, language, actualProfiles);

            this.logger.AssertOutputStrings(0); // not expecting anything in the case of success
        }
        public async Task DownloadQualityProfile_Success()
        {
            // Arrange
            const string QualityProfileName = "SQQualityProfileName";
            const string ProjectName        = "SQProjectName";

            Mock <INuGetBindingOperation> nuGetOpMock = new Mock <INuGetBindingOperation>();

            var notifications   = new ConfigurableProgressStepExecutionEvents();
            var progressAdapter = new FixedStepsProgressAdapter(notifications);

            RuleSet expectedRuleSet = TestRuleSetHelper.CreateTestRuleSetWithRuleIds(new[] { "Key1", "Key2" });
            var     configFile      = new Mock <IBindingConfigFile>().Object;

            var language = Language.VBNET;
            SonarQubeQualityProfile profile = this.ConfigureQualityProfile(language, QualityProfileName);

            var configProviderMock = new Mock <IBindingConfigProvider>();

            configProviderMock.Setup(x => x.GetConfigurationAsync(profile, null, language, CancellationToken.None))
            .ReturnsAsync(configFile);

            var testSubject = this.CreateTestSubject("key", ProjectName, nuGetOpMock.Object, configProviderMock.Object);

            ConfigureSupportedBindingProject(testSubject.InternalState, language);

            // Act
            var result = await testSubject.DownloadQualityProfileAsync(progressAdapter, CancellationToken.None);

            // Assert
            result.Should().BeTrue();
            testSubject.InternalState.BindingConfigFiles.Should().ContainKey(language);
            testSubject.InternalState.BindingConfigFiles[language].Should().Be(configFile);
            testSubject.InternalState.BindingConfigFiles.Count().Should().Be(1);

            testSubject.InternalState.QualityProfiles[language].Should().Be(profile);

            notifications.AssertProgress(0.0, 1.0);
            notifications.AssertProgressMessages(Strings.DownloadingQualityProfileProgressMessage, string.Empty);

            this.outputWindowPane.AssertOutputStrings(1);
            var expectedOutput = string.Format(Strings.SubTextPaddingFormat,
                                               string.Format(Strings.QualityProfileDownloadSuccessfulMessageFormat, QualityProfileName, string.Empty, language.Name));

            this.outputWindowPane.AssertOutputStrings(expectedOutput);
        }
Exemplo n.º 27
0
        public void RuleSetSerializer_WriteRuleSetFile()
        {
            // Setup
            RuleSet ruleSet = TestRuleSetHelper.CreateTestRuleSet(this.TestContext.TestRunDirectory, this.TestContext.TestName + ".ruleset");

            this.temporaryFiles.AddFile(ruleSet.FilePath, false);
            string expectedPath = Path.Combine(this.TestContext.TestRunDirectory, this.TestContext.TestName + "Other.ruleset");

            // Act
            this.testSubject.WriteRuleSetFile(ruleSet, expectedPath);

            // Verify
            Assert.IsTrue(File.Exists(expectedPath), "File not exists where expected");
            Assert.IsFalse(File.Exists(ruleSet.FilePath), "Expected to save only to the specified file path");
            RuleSet loaded = RuleSet.LoadFromFile(expectedPath);

            RuleSetAssert.AreEqual(ruleSet, loaded, "Written unexpected rule set");
        }
        public void HasInclude_RelativePaths_Complex()
        {
            // Regression test for https://github.com/SonarSource/sonarlint-visualstudio/issues/658
            // "SonarLint for Visual Studio 2017 plugin does not respect shared imports "

            // Arrange
            var target = TestRuleSetHelper.CreateTestRuleSet(@"c:\Solution\SomeFolder\fullFilePath.ruleset");

            var relativeInclude           = @".\..\..\Solution\SomeFolder\fullFilePath.ruleset";
            var sourceWithRelativeInclude = TestRuleSetHelper.CreateTestRuleSetWithIncludes(@"c:\aaa\bbb\fullFilePath.ruleset",
                                                                                            relativeInclude);

            // Act
            var hasInclude = RuleSetIncludeChecker.HasInclude(sourceWithRelativeInclude, target);

            // Assert
            hasInclude.Should().BeTrue();
        }
        public void RuleSetConflictsController_FixConflictsCommandExecution()
        {
            // Arrange
            var testSubject = new RuleSetConflictsController(this.host, this.conflictsManager);

            this.ConfigureServiceProviderForFixConflictsCommandExecution();
            this.host.VisualStateManager.IsBusy = false;
            this.host.VisualStateManager.SetBoundProject(new Uri("http://foo"), null, "project123");
            var section = ConfigurableSectionController.CreateDefault();

            this.host.SetActiveSection(section);
            ConfigurableUserNotification notifications = (ConfigurableUserNotification)section.UserNotifications;

            ProjectRuleSetConflict[] conflicts = new[] { ConfigurableConflictsManager.CreateConflict() };

            RuleSet fixedRuleSet = TestRuleSetHelper.CreateTestRuleSet(3);

            fixedRuleSet.FilePath = "MyFixedRules.ruleset";

            RuleSetInspectorTestDataProvider inspectorData = new RuleSetInspectorTestDataProvider();
            var weakenedRulesMap = new Dictionary <RuleReference, RuleAction>();

            inspectorData.FindConflictsResult = new RuleConflictInfo(new RuleReference[0], weakenedRulesMap);
            inspectorData.FixConflictsResult  = new FixedRuleSetInfo(fixedRuleSet, new[] { "reset.ruleset" }, new[] { "deletedRuleId1" });
            this.ruleSetInspector.FindConflictingRulesAction = inspectorData.FindConflictingRulesAction;
            this.ruleSetInspector.FixConflictingRulesAction  = inspectorData.FixConflictingRulesAction;

            ICommand fixMeCommand = testSubject.CreateFixConflictsCommand(conflicts);

            section.UserNotifications.ShowNotificationWarning("fix me", NotificationIds.RuleSetConflictsId, fixMeCommand);

            // Act
            fixMeCommand.Execute(null);

            // Assert
            this.sccFS.files.Should().ContainKey(fixedRuleSet.FilePath);
            this.rsSerializer.AssertRuleSetsAreSame(fixedRuleSet.FilePath, fixedRuleSet);
            this.outputWindowPane.AssertOutputStrings(1);
            this.outputWindowPane.AssertMessageContainsAllWordsCaseSensitive(0,
                                                                             words: new[] { fixedRuleSet.FilePath, "deletedRuleId1", "reset.ruleset" },
                                                                             splitter: new[] { '\n', '\r', '\t', '\'', ':' });
            notifications.AssertNoNotification(NotificationIds.RuleSetConflictsId);
        }
        public void ConflictsManager_GetCurrentConflicts_HasConflicts_WithAggregationApplied()
        {
            // Arrange
            this.SetSolutionBinding(SonarLintMode.LegacyConnected);
            this.SetValidProjects(3);
            this.SetValidSolutionRuleSetPerProjectKind();
            IEnumerable <RuleSetDeclaration> knownDeclarations = this.SetValidRuleSetDeclarationPerProjectAndConfiguration(
                useUniqueProjectRuleSets: false,
                configurationNames: new[] { "Debug", "Release" });

            this.ConfigureInspectorWithConflicts(knownDeclarations, () =>
            {
                RuleSet temp = TestRuleSetHelper.CreateTestRuleSet(1);
                return(new RuleConflictInfo(temp.Rules)); // Missing rules
            });

            // Act + Assert
            testSubject.GetCurrentConflicts().Should().HaveCount(3, "Expecting 3 conflicts (1 per project) since the ruleset declaration for project configuration are the same");
            this.outputWindowPane.AssertOutputStrings(0);
        }