public void SonarQubeServiceWrapper_TryGetProperties()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                ConnectionInformation conn = ConfigureValidConnection(testSubject, new ProjectInformation[0]);

                // Setup
                var property1 = new ServerProperty {
                    Key = "prop1", Value = "val1"
                };
                var property2 = new ServerProperty {
                    Key = "prop2", Value = "val2"
                };

                var expectedProperties = new[] { property1, property2 };

                // Setup test server
                RequestHandler handler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.PropertiesAPI,
                    ctx => ServiceServerProperties(ctx, expectedProperties)
                    );

                // Act
                ServerProperty[] actualProperties;
                Assert.IsTrue(testSubject.TryGetProperties(conn, CancellationToken.None, out actualProperties), "TryGetProperties failed unexpectedly");

                // Verify
                CollectionAssert.AreEqual(expectedProperties.Select(x => x.Key).ToArray(), actualProperties.Select(x => x.Key).ToArray(), "Unexpected server property keys");
                CollectionAssert.AreEqual(expectedProperties.Select(x => x.Value).ToArray(), actualProperties.Select(x => x.Value).ToArray(), "Unexpected server property values");
                handler.AssertHandlerCalled(1);
            }
        }
        public async Task SonarQubeServiceWrapper_DownloadQualityProfile_ProjectWithAnalysis()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                HttpClient     httpClient      = testSubject.CreateHttpClient();
                var            language        = Language.CSharp;
                QualityProfile expectedProfile = CreateRandomQualityProfile(language);
                var            project         = new ProjectInformation {
                    Key = "awesome1", Name = "My Awesome Project"
                };
                ConfigureValidConnection(testSubject, new[] { project });

                // Setup test server
                RegisterQualityProfileQueryValidator(testSubject);

                RequestHandler handler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.CreateQualityProfileUrl(language, project),
                    ctx => ServiceQualityProfiles(ctx, new[] { expectedProfile })
                    );

                // Act
                QualityProfile actualProfile = await SonarQubeServiceWrapper.DownloadQualityProfile(httpClient, project, language, CancellationToken.None);

                // Verify
                Assert.IsNotNull(actualProfile, "Expected a quality profile");
                Assert.AreEqual(expectedProfile.Key, actualProfile.Key, "Unexpected quality profile returned");
                handler.AssertHandlerCalled(1);
            }
        }
        private void SonarQubeServiceWrapper_TryGetExportProfile(Language language)
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                QualityProfile profile = CreateRandomQualityProfile(language);
                var            project = new ProjectInformation {
                    Key = "awesome1", Name = "My Awesome Project"
                };
                var expectedExport         = RoslynExportProfileHelper.CreateExport(ruleSet: TestRuleSetHelper.CreateTestRuleSet(3));
                var roslynExporter         = SonarQubeServiceWrapper.CreateRoslynExporterName(language);
                ConnectionInformation conn = ConfigureValidConnection(testSubject, new[] { project });

                // Setup test server
                RegisterProfileExportQueryValidator(testSubject);

                RequestHandler getExportHandler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.CreateQualityProfileExportUrl(profile, language, roslynExporter),
                    ctx => ServiceProfileExport(ctx, expectedExport)
                    );

                // Act
                RoslynExportProfile actualExport;
                Assert.IsTrue(testSubject.TryGetExportProfile(conn, profile, language, CancellationToken.None, out actualExport), "TryGetExportProfile failed unexpectedly");

                // Verify
                Assert.IsNotNull(actualExport, "Expected a profile export to be returned");
                RoslynExportProfileHelper.AssertAreEqual(expectedExport, actualExport);
                getExportHandler.AssertHandlerCalled(1);
            }
        }
        public void SonarQubeServiceWrapper_TryGetProjects_Authentication_Basic_Invalid()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup case 1: Invalid password
                testSubject.BasicAuthUsers.Add("admin", "admin1");
                var connectionInfo = new ConnectionInformation(new Uri("http://server"), "admin", "admin".ConvertToSecureString());

                // Act
                ProjectInformation[] projects = null;
                Assert.IsFalse(testSubject.TryGetProjects(connectionInfo, CancellationToken.None, out projects), "Auth failed");

                // Verify
                this.outputWindowPane.AssertOutputStrings(1);
                Assert.IsNull(projects, "Not expecting projects");

                // Setup case 2: Invalid user name
                testSubject.BasicAuthUsers.Clear();
                testSubject.BasicAuthUsers.Add("admin1", "admin");

                // Act
                Assert.IsFalse(testSubject.TryGetProjects(connectionInfo, CancellationToken.None, out projects), "Auth failed");

                // Verify
                this.outputWindowPane.AssertOutputStrings(2);
                Assert.IsNull(projects, "Not expecting projects");
            }
        }
        public void SonarQubeServiceWrapper_TryGetPlugins()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                var connectionInfo = new ConnectionInformation(new Uri("http://servername"));
                var plugin1        = new ServerPlugin {
                    Key = "plugin1"
                };
                var plugin2 = new ServerPlugin {
                    Key = "plugin2"
                };

                var expectedPlugins = new[] { plugin1, plugin2 };

                // Setup test server
                RequestHandler handler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.ServerPluginsInstalledAPI,
                    ctx => ServiceServerPlugins(ctx, expectedPlugins)
                    );

                // Act
                ServerPlugin[] actualPlugins;
                Assert.IsTrue(testSubject.TryGetPlugins(connectionInfo, CancellationToken.None, out actualPlugins), "TryGetPlugins failed unexpectedly");

                // Verify
                CollectionAssert.AreEqual(expectedPlugins.Select(x => x.Key).ToArray(), actualPlugins.Select(x => x.Key).ToArray(), "Unexpected server plugins");
                handler.AssertHandlerCalled(1);
            }
        }
 private static void RegisterQualityProfileChangeLogValidator(TestableSonarQubeServiceWrapper testSubject)
 {
     testSubject.RegisterQueryValidator(SonarQubeServiceWrapper.QualityProfileChangeLogAPI, request =>
     {
         var queryMap = ParseQuery(request.Uri.Query);
         Assert.AreEqual(2, queryMap.Count, "Unexpected query params.: {0}", string.Join(", ", queryMap.Keys));
         Assert.IsNotNull(queryMap["profileKey"], "Missing query param: profileKey");
         Assert.AreEqual("1", queryMap["ps"], "Expecting always page size 1");
     });
 }
        private static ConnectionInformation ConfigureValidConnection(TestableSonarQubeServiceWrapper testSubject, IEnumerable <ProjectInformation> projects)
        {
            var connectionInfo = new ConnectionInformation(new Uri("http://test-server"));

            testSubject.AllowAnonymous = true;
            testSubject.RegisterConnectionHandler(new RequestHandler {
                ResponseText = Serialize(projects)
            });

            return(connectionInfo);
        }
 private static void RegisterProfileExportQueryValidator(TestableSonarQubeServiceWrapper testSubject)
 {
     testSubject.RegisterQueryValidator(SonarQubeServiceWrapper.QualityProfileExportAPI, request =>
     {
         var queryMap = ParseQuery(request.Uri.Query);
         Assert.AreEqual(3, queryMap.Count, "Unexpected query params.: {0}", string.Join(", ", queryMap.Keys));
         Assert.IsNotNull(queryMap["name"], "Missing query param: name");
         Assert.IsNotNull(queryMap["language"], "Missing query param: language");
         Assert.IsNotNull(queryMap["format"], "Missing query param: format");
         Assert.AreEqual(SonarQubeServiceWrapper.RoslynExporterFormat, queryMap["format"], "Unexpected value for query param: format");
     });
 }
        public void SonarQubeServiceWrapper_TryGetPlugins_ArgChecks()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider, timeoutInMilliseconds: 1))
            {
                ServerPlugin[] plugins;

                // Null connection information
                Exceptions.Expect <ArgumentNullException>(() => testSubject.TryGetPlugins(null, CancellationToken.None, out plugins));

                // Those are API usage issue which we don't report to the output pane
                this.outputWindowPane.AssertOutputStrings(0);
            }
        }
        public void SonarQubeServiceWrapper_TryGetQualityProfile_FullFunctionality()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                Language       language = Language.CSharp;
                QualityProfile profile  = CreateRandomQualityProfile(language);
                var            project  = new ProjectInformation {
                    Key = "awesome1", Name = "My Awesome Project"
                };
                var changeLog = new QualityProfileChangeLog
                {
                    Page     = 1,
                    PageSize = 1,
                    Total    = 1,
                    Events   = new QualityProfileChangeLogEvent[]
                    {
                        new QualityProfileChangeLogEvent {
                            Date = DateTime.Now
                        }
                    }
                };
                ConnectionInformation conn = ConfigureValidConnection(testSubject, new[] { project });

                // Setup test server
                RegisterQualityProfileChangeLogValidator(testSubject);

                RequestHandler getProfileHandler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.CreateQualityProfileUrl(language, project),
                    ctx => ServiceQualityProfiles(ctx, new[] { profile })
                    );
                RequestHandler changeLogHandler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.CreateQualityProfileChangeLogUrl(profile),
                    ctx => ServiceChangeLog(ctx, changeLog)
                    );

                // Act
                QualityProfile actualProfile;
                Assert.IsTrue(testSubject.TryGetQualityProfile(conn, project, language, CancellationToken.None, out actualProfile), "TryGetExportProfile failed unexpectedly");

                // Verify
                Assert.IsNotNull(actualProfile, "Expected a profile to be returned");
                Assert.AreEqual(profile.Key, actualProfile.Key);
                Assert.AreEqual(profile.Name, actualProfile.Name);
                Assert.AreEqual(changeLog.Events[0].Date, actualProfile.QualityProfileTimestamp);

                getProfileHandler.AssertHandlerCalled(1);
                changeLogHandler.AssertHandlerCalled(1);
                this.outputWindowPane.AssertOutputStrings(0);
            }
        }
        public void SonarQubeServiceWrapper_TryGetProjects_Timeout()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider, timeoutInMilliseconds: 1))
            {
                // Setup
                testSubject.AllowAnonymous             = true;
                testSubject.DelayRequestInMilliseconds = 1000;
                var connectionInfo = new ConnectionInformation(new Uri("http://server"));

                // Act
                ProjectInformation[] projects = null;
                Assert.IsFalse(testSubject.TryGetProjects(connectionInfo, CancellationToken.None, out projects), "Should timeout");

                // Verify
                this.outputWindowPane.AssertOutputStrings(1);
                Assert.IsNull(projects);
            }
        }
        public void SonarQubeServiceWrapper_TryGetProjects_UnhandledExceptions()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                testSubject.AllowAnonymous = true;
                testSubject.RegisterConnectionHandler(new RequestHandler(ctx => { throw new InvalidOperationException(); }));
                var connectionInfo = new ConnectionInformation(new Uri("http://server"));

                // Act
                ProjectInformation[] projects = null;
                Assert.IsFalse(testSubject.TryGetProjects(connectionInfo, CancellationToken.None, out projects), "Exception been thrown");

                // Verify
                this.outputWindowPane.AssertOutputStrings(1);
                Assert.IsNull(projects, "Not expecting projects");
            }
        }
        public void SonarQubeServiceWrapper_TryGetProjects()
        {
            var p1 = new ProjectInformation
            {
                Name = "Project 1",
                Key  = "1"
            };
            var p2 = new ProjectInformation
            {
                Name = "Project 2",
                Key  = "2"
            };

            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup case 1: first time connect
                testSubject.AllowAnonymous = true;
                testSubject.RegisterConnectionHandler(new RequestHandler {
                    ResponseText = Serialize(new[] { p1 })
                });
                var connectionInfo1 = new ConnectionInformation(new Uri("http://server"));

                // Act
                ProjectInformation[] projects = null;
                Assert.IsTrue(testSubject.TryGetProjects(connectionInfo1, CancellationToken.None, out projects), "Expected to get the projects");

                // Verify
                AssertEqualProjects(new[] { p1 }, projects);
                this.outputWindowPane.AssertOutputStrings(0);

                // Setup case 2: second time connect
                var connectionInfo2 = new ConnectionInformation(new Uri("http://server"));

                // Act
                testSubject.RegisterConnectionHandler(new RequestHandler {
                    ResponseText = Serialize(new[] { p1, p2 })
                });
                Assert.IsTrue(testSubject.TryGetProjects(connectionInfo2, CancellationToken.None, out projects), "Expected to get the projects");

                // Verify
                AssertEqualProjects(new[] { p1, p2 }, projects);
                this.outputWindowPane.AssertOutputStrings(0);
            }
        }
        public void SonarQubeServiceWrapper_TryGetProjects_InvalidStatusCode()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                testSubject.AllowAnonymous = true;
                testSubject.RegisterConnectionHandler(new RequestHandler {
                    ResponseStatusCode = HttpStatusCode.InternalServerError
                });
                var connectionInfo = new ConnectionInformation(new Uri("http://server"));

                // Act
                ProjectInformation[] projects = null;
                Assert.IsFalse(testSubject.TryGetProjects(connectionInfo, CancellationToken.None, out projects), "Should fail");

                // Verify
                Assert.IsNull(projects);
                this.outputWindowPane.AssertOutputStrings(1);
            }
        }
 private static void RegisterQualityProfileQueryValidator(TestableSonarQubeServiceWrapper testSubject)
 {
     testSubject.RegisterQueryValidator(SonarQubeServiceWrapper.QualityProfileListAPI, request =>
     {
         var queryMap = ParseQuery(request.Uri.Query);
         if (queryMap.Count == 1)
         {
             Assert.IsNotNull(queryMap["language"], "Missing query param: language");
         }
         else if (queryMap.Count == 2)
         {
             Assert.IsNotNull(queryMap["language"], "Missing query param: language");
             Assert.IsNotNull(queryMap["project"], "Missing query param: project");
         }
         else
         {
             Assert.Fail("Unexpected query params.: {0}", string.Join(", ", queryMap.Keys));
         }
     });
 }
        public void SonarQubeServiceWrapper_TryGetProjects_Authentication_Basic_Valid()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                testSubject.BasicAuthUsers.Add("admin", "admin");
                testSubject.RegisterConnectionHandler(new RequestHandler {
                    ResponseText = Serialize(new ProjectInformation[0])
                });
                var connectionInfo = new ConnectionInformation(new Uri("http://server"), "admin", "admin".ConvertToSecureString());

                // Act
                ProjectInformation[] projects = null;
                Assert.IsTrue(testSubject.TryGetProjects(connectionInfo, CancellationToken.None, out projects), "Should be get an empty array of projects");

                // Verify
                this.outputWindowPane.AssertOutputStrings(0);
                Assert.IsNotNull(projects, "Expected projects");
                Assert.AreEqual(0, projects.Length, "Expected an empty array");
            }
        }
        public void SonarQubeServiceWrapper_TryGetExportProfile_ArgChecks()
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider, timeoutInMilliseconds: 1))
            {
                RoslynExportProfile   actualExport;
                ConnectionInformation connection = new ConnectionInformation(new Uri("http://valid"));
                QualityProfile        profile    = new QualityProfile();

                // No connection information
                Exceptions.Expect <ArgumentNullException>(() => testSubject.TryGetExportProfile(null, profile, Language.CSharp, CancellationToken.None, out actualExport));

                // No project information
                Exceptions.Expect <ArgumentNullException>(() => testSubject.TryGetExportProfile(connection, null, Language.CSharp, CancellationToken.None, out actualExport));

                // Invalid language
                var pascalLanguage = new Language("Pascal", "Pascal", Guid.Empty);
                Exceptions.Expect <ArgumentOutOfRangeException>(() => testSubject.TryGetExportProfile(connection, profile, pascalLanguage, CancellationToken.None, out actualExport));

                // Those are API usage issue which we don't report to the output pane
                this.outputWindowPane.AssertOutputStrings(0);
            }
        }
        private void SonarQubeServiceWrapper_TryGetQualityProfile_ReducedFunctionality(Language language)
        {
            using (var testSubject = new TestableSonarQubeServiceWrapper(this.serviceProvider))
            {
                // Setup
                QualityProfile profile = CreateRandomQualityProfile(language);
                var            project = new ProjectInformation {
                    Key = "awesome1", Name = "My Awesome Project"
                };
                ConnectionInformation conn = ConfigureValidConnection(testSubject, new[] { project });

                // Setup test server
                RegisterQualityProfileChangeLogValidator(testSubject);

                RequestHandler getProfileHandler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.CreateQualityProfileUrl(language, project),
                    ctx => ServiceQualityProfiles(ctx, new[] { profile })
                    );
                RequestHandler changeLogHandler = testSubject.RegisterRequestHandler(
                    SonarQubeServiceWrapper.CreateQualityProfileChangeLogUrl(profile),
                    ctx => ServiceChangeLog(ctx, null, simulateFault: true)
                    );

                // Act
                QualityProfile actualProfile;
                Assert.IsTrue(testSubject.TryGetQualityProfile(conn, project, language, CancellationToken.None, out actualProfile), "TryGetExportProfile failed unexpectedly");

                // Verify
                Assert.IsNotNull(actualProfile, "Expected a profile to be returned");
                Assert.AreEqual(profile.Key, actualProfile.Key);
                Assert.AreEqual(profile.Name, actualProfile.Name);
                Assert.IsNull(actualProfile.QualityProfileTimestamp);

                getProfileHandler.AssertHandlerCalled(1);
                changeLogHandler.AssertHandlerCalled(1);
                this.outputWindowPane.AssertOutputStrings(1);
            }
        }