public void EmbeddedInstall_PluginWithNoFiles_Succeeds()
        {
            // Arrange
            var localCacheDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var logger        = new TestLogger();

            var request1 = new Plugin("plugin1", "1.0", "p1.resource1.zip");
            var request2 = new Plugin("plugin2", "2.0", "p2.resource1.zip");

            var mockServer = new MockSonarQubeServer();

            AddPlugin(mockServer, request1, "p1.resource1.file1.dll", "p1.resource1.file2.dll");
            AddPlugin(mockServer, request2 /* no assemblies */);

            var expectedPaths = new List <string>();

            expectedPaths.AddRange(CalculateExpectedCachedFilePaths(localCacheDir, 0, "p1.resource1.file1.dll", "p1.resource1.file2.dll"));

            var testSubject = new EmbeddedAnalyzerInstaller(mockServer, localCacheDir, logger);

            // Act
            IEnumerable <AnalyzerPlugin> actualPlugins;

            using (new AssertIgnoreScope())
            {
                actualPlugins = testSubject.InstallAssemblies(new Plugin[] { request1, request2 });
            }

            // Assert
            actualPlugins.Should().NotBeNull("Returned list should not be null");
            AssertExpectedFilesReturned(expectedPaths, actualPlugins);
            AssertExpectedFilesExist(expectedPaths);
            // 5 = zip files + index file + content files
            AssertExpectedFilesInCache(5, localCacheDir);
            actualPlugins.Select(p => p.Key).Should().BeEquivalentTo(new string[] { "plugin1" }); // plugin with no resources should not be included
        }
        public void EmbeddedInstall_SinglePlugin_SingleResource_Succeeds()
        {
            // Arrange
            var localCacheDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var logger        = new TestLogger();

            var requestedPlugin = new Plugin("plugin1", "1.0", "embeddedFile1.zip");
            var mockServer      = new MockSonarQubeServer();

            AddPlugin(mockServer, requestedPlugin, "file1.dll", "file2.txt");

            var expectedFilePaths = CalculateExpectedCachedFilePaths(localCacheDir, 0, "file1.dll", "file2.txt");

            var testSubject = new EmbeddedAnalyzerInstaller(mockServer, localCacheDir, logger);

            // Act
            var actualFiles = testSubject.InstallAssemblies(new Plugin[] { requestedPlugin });

            // Assert
            actualFiles.Should().NotBeNull("Returned list should not be null");
            AssertExpectedFilesReturned(expectedFilePaths, actualFiles);
            AssertExpectedFilesExist(expectedFilePaths);
            AssertExpectedFilesInCache(4, localCacheDir); // one zip containing two files
        }
 private void AddPlugin(MockSonarQubeServer mockServer, Plugin plugin, params string[] files)
 {
     mockServer.Data.AddEmbeddedZipFile(plugin.Key, plugin.StaticResourceName, files);
 }
        public void PreProc_EndToEnd_SuccessCase()
        {
            // Checks end-to-end happy path for the pre-processor i.e.
            // * arguments are parsed
            // * targets are installed
            // * server properties are fetched
            // * rulesets are generated
            // * config file is created

            // Arrange
            var workingDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var logger     = new TestLogger();

            // Configure the server
            var mockServer = new MockSonarQubeServer();

            var data = mockServer.Data;

            data.ServerProperties.Add("server.key", "server value 1");

            data.Languages.Add("cs");
            data.Languages.Add("vbnet");
            data.Languages.Add("another_plugin");

            data.AddQualityProfile("qp1", "cs", null)
            .AddProject("key")
            .AddRule(new SonarRule("csharpsquid", "cs.rule3"));

            data.AddQualityProfile("qp2", "vbnet", null)
            .AddProject("key")
            .AddRule(new SonarRule("vbnet", "vb.rule3"));

            var mockAnalyzerProvider = new MockRoslynAnalyzerProvider
            {
                SettingsToReturn = new AnalyzerSettings
                {
                    RulesetPath = "c:\\xxx.ruleset"
                }
            };

            var mockTargetsInstaller = new Mock <ITargetsInstaller>();
            var mockFactory          = new MockObjectFactory(mockServer, mockTargetsInstaller.Object, mockAnalyzerProvider);

            TeamBuildSettings settings;

            using (PreprocessTestUtils.CreateValidNonTeamBuildScope())
                using (new WorkingDirectoryScope(workingDir))
                {
                    settings = TeamBuildSettings.GetSettingsFromEnvironment(new TestLogger());
                    settings.Should().NotBeNull("Test setup error: TFS environment variables have not been set correctly");
                    settings.BuildEnvironment.Should().Be(BuildEnvironment.NotTeamBuild, "Test setup error: build environment was not set correctly");

                    var preProcessor = new TeamBuildPreProcessor(mockFactory, logger);

                    // Act
                    var success = preProcessor.Execute(CreateValidArgs("key", "name", "1.0")).Result;
                    success.Should().BeTrue("Expecting the pre-processing to complete successfully");
                }

            // Assert
            AssertDirectoriesCreated(settings);

            mockTargetsInstaller.Verify(x => x.InstallLoaderTargets(workingDir), Times.Once());
            mockServer.AssertMethodCalled("GetProperties", 1);
            mockServer.AssertMethodCalled("GetAllLanguages", 1);
            mockServer.AssertMethodCalled("TryGetQualityProfile", 2); // C# and VBNet
            mockServer.AssertMethodCalled("GetRules", 2);             // C# and VBNet

            AssertAnalysisConfig(settings.AnalysisConfigFilePath, 2, logger);
        }
        // Regression test for https://github.com/SonarSource/sonar-scanner-msbuild/issues/699
        public void PreProc_EndToEnd_Success_LocalSettingsAreUsedInSonarLintXML()
        {
            // Checks that local settings are used when creating the SonarLint.xml file,
            // overriding

            // Arrange
            var workingDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var logger     = new TestLogger();

            // Configure the server
            var mockServer = new MockSonarQubeServer();

            var data = mockServer.Data;

            data.Languages.Add("cs");
            data.AddQualityProfile("qp1", "cs", null)
            .AddProject("key")
            .AddRule(new SonarRule("csharpsquid", "cs.rule3"));

            // Server-side settings
            data.ServerProperties.Add("server.key", "server value 1");
            data.ServerProperties.Add("shared.key1", "server shared value 1");
            data.ServerProperties.Add("shared.CASING", "server upper case value");

            // Local settings that should override matching server settings
            var args = new List <string>(CreateValidArgs("key", "name", "1.0"));

            args.Add("/d:local.key=local value 1");
            args.Add("/d:shared.key1=local shared value 1 - should override server value");
            args.Add("/d:shared.casing=local lower case value");

            var mockAnalyzerProvider = new MockRoslynAnalyzerProvider
            {
                SettingsToReturn = new AnalyzerSettings
                {
                    RulesetPath = "c:\\xxx.ruleset"
                }
            };
            var mockTargetsInstaller = new Mock <ITargetsInstaller>();
            var mockFactory          = new MockObjectFactory(mockServer, mockTargetsInstaller.Object, mockAnalyzerProvider);

            TeamBuildSettings settings;

            using (PreprocessTestUtils.CreateValidNonTeamBuildScope())
                using (new WorkingDirectoryScope(workingDir))
                {
                    settings = TeamBuildSettings.GetSettingsFromEnvironment(new TestLogger());
                    settings.Should().NotBeNull("Test setup error: TFS environment variables have not been set correctly");
                    settings.BuildEnvironment.Should().Be(BuildEnvironment.NotTeamBuild, "Test setup error: build environment was not set correctly");

                    var preProcessor = new TeamBuildPreProcessor(mockFactory, logger);

                    // Act
                    var success = preProcessor.Execute(args.ToArray()).Result;
                    success.Should().BeTrue("Expecting the pre-processing to complete successfully");
                }

            // Assert

            // Check the settings used when creating the SonarLint file - local and server settings should be merged
            mockAnalyzerProvider.SuppliedSonarProperties.Should().NotBeNull();
            mockAnalyzerProvider.SuppliedSonarProperties.AssertExpectedPropertyValue("server.key", "server value 1");
            mockAnalyzerProvider.SuppliedSonarProperties.AssertExpectedPropertyValue("local.key", "local value 1");
            mockAnalyzerProvider.SuppliedSonarProperties.AssertExpectedPropertyValue("shared.key1", "local shared value 1 - should override server value");
            // Keys are case-sensitive so differently cased values should be preserved
            mockAnalyzerProvider.SuppliedSonarProperties.AssertExpectedPropertyValue("shared.CASING", "server upper case value");
            mockAnalyzerProvider.SuppliedSonarProperties.AssertExpectedPropertyValue("shared.casing", "local lower case value");

            // Check the settings used when creating the config file - settings should be separate
            var actualConfig = AssertAnalysisConfig(settings.AnalysisConfigFilePath, 1, logger);

            AssertExpectedLocalSetting("local.key", "local value 1", actualConfig);
            AssertExpectedLocalSetting("shared.key1", "local shared value 1 - should override server value", actualConfig);
            AssertExpectedLocalSetting("shared.casing", "local lower case value", actualConfig);

            AssertExpectedServerSetting("server.key", "server value 1", actualConfig);
            AssertExpectedServerSetting("shared.key1", "server shared value 1", actualConfig);
            AssertExpectedServerSetting("shared.CASING", "server upper case value", actualConfig);
        }
        public void PreProc_NoProject()
        {
            // Arrange
            var workingDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var logger     = new TestLogger();

            // Configure the server
            var mockServer = new MockSonarQubeServer();

            var data = mockServer.Data;

            data.ServerProperties.Add("server.key", "server value 1");

            data.Languages.Add("cs");
            data.Languages.Add("vbnet");
            data.Languages.Add("another_plugin");

            data.AddQualityProfile("qp1", "cs", null)
            .AddProject("invalid")
            .AddRule(new SonarRule("fxcop", "cs.rule1"))
            .AddRule(new SonarRule("fxcop", "cs.rule2"));

            data.AddQualityProfile("qp2", "vbnet", null)
            .AddProject("invalid")
            .AddRule(new SonarRule("fxcop-vbnet", "vb.rule1"))
            .AddRule(new SonarRule("fxcop-vbnet", "vb.rule2"));

            var mockAnalyzerProvider = new MockRoslynAnalyzerProvider
            {
                SettingsToReturn = new AnalyzerSettings
                {
                    RulesetPath = "c:\\xxx.ruleset"
                }
            };

            var mockTargetsInstaller = new Mock <ITargetsInstaller>();
            var mockFactory          = new MockObjectFactory(mockServer, mockTargetsInstaller.Object, mockAnalyzerProvider);

            TeamBuildSettings settings;

            using (PreprocessTestUtils.CreateValidNonTeamBuildScope())
                using (new WorkingDirectoryScope(workingDir))
                {
                    settings = TeamBuildSettings.GetSettingsFromEnvironment(new TestLogger());
                    settings.Should().NotBeNull("Test setup error: TFS environment variables have not been set correctly");
                    settings.BuildEnvironment.Should().Be(BuildEnvironment.NotTeamBuild, "Test setup error: build environment was not set correctly");

                    var preProcessor = new TeamBuildPreProcessor(mockFactory, logger);

                    // Act
                    var success = preProcessor.Execute(CreateValidArgs("key", "name", "1.0", null)).Result;
                    success.Should().BeTrue("Expecting the pre-processing to complete successfully");
                }

            // Assert
            AssertDirectoriesCreated(settings);

            mockTargetsInstaller.Verify(x => x.InstallLoaderTargets(workingDir), Times.Once());
            mockServer.AssertMethodCalled("GetProperties", 1);
            mockServer.AssertMethodCalled("GetAllLanguages", 1);
            mockServer.AssertMethodCalled("TryGetQualityProfile", 2); // C# and VBNet
            mockServer.AssertMethodCalled("GetRules", 0);             // no quality profile assigned to project

            AssertAnalysisConfig(settings.AnalysisConfigFilePath, 0, logger);

            // only contains SonarQubeAnalysisConfig (no rulesets or additional files)
            AssertDirectoryContains(settings.SonarConfigDirectory, Path.GetFileName(settings.AnalysisConfigFilePath));
        }
        public void PreProc_EndToEnd_ShouldWarnOrNot_SonarQubeDeprecatedVersion(string sqVersion, bool shouldWarn)
        {
            // Arrange
            var workingDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var logger     = new TestLogger();

            // Configure the server
            var mockServer = new MockSonarQubeServer();

            var data = mockServer.Data;

            data.ServerProperties.Add("server.key", "server value 1");
            data.SonarQubeVersion = new Version(sqVersion);

            data.Languages.Add("cs");
            data.Languages.Add("vbnet");
            data.Languages.Add("another_plugin");

            data.AddQualityProfile("qp1", "cs", "organization")
            .AddProject("key")
            .AddRule(new SonarRule("csharpsquid", "cs.rule3"));

            data.AddQualityProfile("qp2", "vbnet", "organization")
            .AddProject("key")
            .AddRule(new SonarRule("vbnet", "vb.rule3"));

            var mockAnalyzerProvider = new MockRoslynAnalyzerProvider
            {
                SettingsToReturn = new AnalyzerSettings
                {
                    RulesetPath = "c:\\xxx.ruleset"
                }
            };

            var mockTargetsInstaller = new Mock <ITargetsInstaller>();
            var mockFactory          = new MockObjectFactory(mockServer, mockTargetsInstaller.Object, mockAnalyzerProvider);

            TeamBuildSettings settings;

            using (PreprocessTestUtils.CreateValidNonTeamBuildScope())
                using (new WorkingDirectoryScope(workingDir))
                {
                    settings = TeamBuildSettings.GetSettingsFromEnvironment(new TestLogger());
                    settings.Should().NotBeNull("Test setup error: TFS environment variables have not been set correctly");
                    settings.BuildEnvironment.Should().Be(BuildEnvironment.NotTeamBuild, "Test setup error: build environment was not set correctly");

                    var preProcessor = new TeamBuildPreProcessor(mockFactory, logger);

                    // Act
                    var success = preProcessor.Execute(CreateValidArgs("key", "name", "1.0", "organization")).Result;
                    success.Should().BeTrue("Expecting the pre-processing to complete successfully");
                }

            mockTargetsInstaller.Verify(x => x.InstallLoaderTargets(workingDir), Times.Once());

            if (shouldWarn)
            {
                mockServer.AssertWarningWritten("version is below supported");
            }
            else
            {
                mockServer.AssertNoWarningWritten();
            }
        }