public async Task GetNotificationEventsAsync_ReturnsExpectedResult() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("5.6"); var expectedEvent = new NotificationsResponse { Category = "QUALITY_GATE", Link = new Uri("http://foo.com"), Date = new DateTimeOffset(2010, 1, 1, 14, 59, 59, TimeSpan.FromHours(2)), Message = "foo", Project = "test" }; client .Setup(x => x.GetNotificationEventsAsync(It.IsAny <NotificationsRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(Result.Ok(new[] { expectedEvent })); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetNotificationEventsAsync("test", DateTimeOffset.Now, CancellationToken.None); // Assert client.VerifyAll(); result.Should().NotBeNull(); result.Should().HaveCount(1); result[0].Category.Should().Be(expectedEvent.Category); result[0].Link.Should().Be(expectedEvent.Link); result[0].Date.Should().Be(expectedEvent.Date); result[0].Message.Should().Be(expectedEvent.Message); }
public async Task Call_Real_SonarQube() { var url = new Uri("http://localhost:9000"); string userName = "******"; var password = new SecureString(); password.AppendChar('a'); password.AppendChar('d'); password.AppendChar('m'); password.AppendChar('i'); password.AppendChar('n'); var connInfo = new ConnectionInformation(url, userName, password); var service = new SonarQubeService(new HttpClientHandler(), "agent", new TestLogger()); try { await service.ConnectAsync(connInfo, CancellationToken.None); // Example string fileKey = "junk:MyClass.cs"; var result = await service.GetSourceCodeAsync(fileKey, CancellationToken.None); result.Should().NotBeNullOrEmpty(); } finally { service.Disconnect(); } }
public async Task GetSuppressedIssuesAsync_ReturnsExpectedResults() { var client = GetMockSqClientWithCredentialAndVersion("5.6"); client .Setup(x => x.GetIssuesAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(Result.Ok(new[] { new ServerIssue { Resolution = "WONTFIX" }, new ServerIssue { Resolution = "FALSE-POSITIVE" }, new ServerIssue { Resolution = "FIXED" }, new ServerIssue { Resolution = "" }, })); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetSuppressedIssuesAsync("key", CancellationToken.None); // Assert client.VerifyAll(); result.Should().HaveCount(3); result[0].ResolutionState.Should().Be(SonarQubeIssueResolutionState.WontFix); result[1].ResolutionState.Should().Be(SonarQubeIssueResolutionState.FalsePositive); result[2].ResolutionState.Should().Be(SonarQubeIssueResolutionState.Fixed); }
public async Task GetAllOrganizationsAsync_ReturnsExpectedResult() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("5.6"); client .SetupSequence(x => x.GetOrganizationsAsync(It.IsAny <OrganizationRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(Result.Ok(new[] { new OrganizationResponse { Key = "key", Name = "name" } })) .ReturnsAsync(Result.Ok(new OrganizationResponse[0])); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetAllOrganizationsAsync(CancellationToken.None); // Assert client.VerifyAll(); result.Should().NotBeNull(); result.Should().HaveCount(1); result[0].Key.Should().Be("key"); result[0].Name.Should().Be("name"); }
public async Task GetAllProjectsAsync_WhenOrganizationIsSpecified_ReturnsExpectedResult() { // Arrange var successResponse = new HttpResponseMessage(HttpStatusCode.OK); var client = GetMockSqClientWithCredentialAndVersion("5.6"); client .SetupSequence(x => x.GetComponentsSearchProjectsAsync( It.Is <ComponentRequest>(c => c.OrganizationKey == "org"), It.IsAny <CancellationToken>())) .ReturnsAsync(Result.Ok(new[] { new ComponentResponse { Key = "key", Name = "name" } })) .ReturnsAsync(Result.Ok(new ComponentResponse[0])); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetAllProjectsAsync("org", CancellationToken.None); // Assert client.VerifyAll(); result.Should().NotBeNull(); result.Should().HaveCount(1); result[0].Key.Should().Be("key"); result[0].Name.Should().Be("name"); }
public async Task Call_Real_SonarCloud() { // TODO: set to a valid SonarCloud token but make sure you don't check it in... string validSonarCloudToken = "DO NOT CHECK IN A REAL TOKEN"; var url = ConnectionInformation.FixedSonarCloudUri; var password = new SecureString(); var connInfo = new ConnectionInformation(url, validSonarCloudToken, password); var service = new SonarQubeService(new HttpClientHandler(), "agent", new TestLogger()); try { await service.ConnectAsync(connInfo, CancellationToken.None); // Example var fileKey = "vuln:Tools/Orchard/Logger.cs"; var result = await service.GetSourceCodeAsync(fileKey, CancellationToken.None); result.Should().NotBeNullOrEmpty(); } finally { service.Disconnect(); } }
public async Task GetQualityProfileAsync_WhenOnlyOneProfile_ReturnsExpectedQualityProfile() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("0.0"); client.Setup(x => x.GetQualityProfilesAsync(It.IsAny <QualityProfileRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new Result <QualityProfileResponse[]>(new HttpResponseMessage(), new[] { new QualityProfileResponse { Key = "QP_KEY", Language = "cs" } })); client.Setup(x => x.GetQualityProfileChangeLogAsync(It.IsAny <QualityProfileChangeLogRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new Result <QualityProfileChangeLogResponse>(new HttpResponseMessage(), new QualityProfileChangeLogResponse { Events = new[] { new QualityProfileChangeLogEventResponse { Date = DateTime.MaxValue } } })); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetQualityProfileAsync("PROJECT_KEY", SonarQubeLanguage.CSharp, CancellationToken.None); // Assert client.Verify(x => x.GetQualityProfilesAsync(It.IsAny <QualityProfileRequest>(), It.IsAny <CancellationToken>()), Times.Once); client.Verify(x => x.GetQualityProfileChangeLogAsync(It.IsAny <QualityProfileChangeLogRequest>(), It.IsAny <CancellationToken>()), Times.Once); result.Key.Should().Be("QP_KEY"); result.Language.Should().Be("cs"); result.TimeStamp.Should().Be(DateTime.MaxValue); }
public async Task ConnectAsync_WhenAlreadyConnected_ThrowsInvalidOperation() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("5.6"); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act Func <Task> func = async() => await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Assert client.VerifyAll(); func.Should().ThrowExactly <InvalidOperationException>().WithMessage("This operation expects the service not to be connected."); }
public async Task GetAllPluginsAsync_ReturnsExpectedResult() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("5.6"); client.Setup(x => x.GetPluginsAsync(It.IsAny <CancellationToken>())) .ReturnsAsync(() => new Result <PluginResponse[]>(new HttpResponseMessage(), new[] { new PluginResponse { Key = "key", Version = "version" } })); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetAllPluginsAsync(CancellationToken.None); // Assert client.VerifyAll(); result.Should().NotBeNull(); result.Should().HaveCount(1); result[0].Key.Should().Be("key"); result[0].Version.Should().Be("version"); }
protected async Task ConnectToSonarQube(string version = "5.6.0.0") { SetupRequest("api/server/version", version); SetupRequest("api/authentication/validate", "{ \"valid\": true}"); await service.ConnectAsync( new ConnectionInformation(BasePath, "valeri", new SecureString()), CancellationToken.None); }
public async Task IsConnected_WhenConnected_ReturnsTrue() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("5.6"); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = service.IsConnected; // Assert result.Should().BeTrue(); }
private async Task HasOrganizationsFeature_WhenConnectedToSQVersion_ReturnsExpected(string version, bool expected) { // Arrange var client = GetMockSqClientWithCredentialAndVersion(version); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = service.HasOrganizationsFeature; // Assert client.VerifyAll(); result.Should().Be(expected); }
public async Task EnsureIsConnected_WhenConnected_ShouldDoNothing() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("1.0.0.0"); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act Action action = () => service.EnsureIsConnected(); // Assert client.VerifyAll(); action.Should().NotThrow <InvalidOperationException>(); }
public async Task SonarQubeService_FactorySelector_RequestsNewFactoryOnEachConnect() { var logger = new TestLogger(); var sonarQubeConnectionInfo = new ConnectionInformation(new Uri("http://sonarqube")); var sonarCloudConnectionInfo = new ConnectionInformation(new Uri("https://sonarcloud.io")); var qubeFactoryMock = CreateRequestFactory("1.2.3"); var cloudFactoryMock = CreateRequestFactory("9.9"); var selectorMock = new Mock <IRequestFactorySelector>(); selectorMock.Setup(x => x.Select(false /* isSonarCloud */, logger)).Returns(qubeFactoryMock.Object); selectorMock.Setup(x => x.Select(true /* isSonarCloud */, logger)).Returns(cloudFactoryMock.Object); var testSubject = new SonarQubeService(Mock.Of <HttpMessageHandler>(), "user-agent", logger, selectorMock.Object, Mock.Of <ISecondaryIssueHashUpdater>()); // 1. Connect to SonarQube await testSubject.ConnectAsync(sonarQubeConnectionInfo, CancellationToken.None); qubeFactoryMock.Invocations.Count.Should().Be(2); cloudFactoryMock.Invocations.Count.Should().Be(0); testSubject.IsConnected.Should().BeTrue(); testSubject.ServerInfo.ServerType.Should().Be(ServerType.SonarQube); // 2. Disconnect testSubject.Disconnect(); testSubject.IsConnected.Should().BeFalse(); // 3. Connect to SonarCloud await testSubject.ConnectAsync(sonarCloudConnectionInfo, CancellationToken.None); qubeFactoryMock.Invocations.Count.Should().Be(2); cloudFactoryMock.Invocations.Count.Should().Be(2); testSubject.IsConnected.Should().BeTrue(); testSubject.ServerInfo.ServerType.Should().Be(ServerType.SonarCloud); }
public async Task GetProjectDashboardUrl_ReturnsExpectedUrl() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("5.6"); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = service.GetProjectDashboardUrl("myProject"); // Assert client.VerifyAll(); result.Host.Should().Be("mysq.com"); result.LocalPath.Should().Be("/dashboard/index/myProject"); }
public async Task Disconnect_WhenConnected_DisposeTheSonarQubeClient() { // Arrange var successResponse = new HttpResponseMessage(HttpStatusCode.OK); var client = GetMockSqClientWithCredentialAndVersion("5.6"); client.As <IDisposable>().Setup(x => x.Dispose()).Verifiable(); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act service.Disconnect(); // Assert client.VerifyAll(); }
public void ConnectAsync_WhenCredentialsAreInvalid_ThrowsExpectedException() { // Act var client = new Mock <ISonarQubeClient>(); client.Setup(x => x.ValidateCredentialsAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => new Result <CredentialResponse>(new HttpResponseMessage(), new CredentialResponse { IsValid = false })); var service = new SonarQubeService(WrapInMockFactory(client)); Func <Task> func = async() => await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Assert func.ShouldThrow <Exception>().WithMessage("Invalid credentials."); }
private static async Task <SonarQubeIssue[]> GetSonarQubeIssues(string sonarKey) { var service = new SonarQubeService(new HttpClientHandler(), "user-agent-string", Logger); await service.ConnectAsync( new ConnectionInformation(new Uri(AppSettings.SonarServer), AppSettings.SonarUserName, AppSettings.SonarUserPassword.ToSecureString()), CancellationToken.None); var getIssueWrapper = new IssuesRequestWrapper() { ProjectKey = sonarKey, Logger = Logger, HttpMethod = HttpMethod.Get }; var issues = await getIssueWrapper.InvokeAsync(Client, CancellationToken.None); return(issues); }
public async Task GetQualityProfileAsync_WhenError404_CallsAgainWithNoProjectKey() { // Arrange var client = GetMockSqClientWithCredentialAndVersion("0.0"); client .SetupSequence(x => x.GetQualityProfilesAsync(It.IsAny <QualityProfileRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(Result.NotFound(new QualityProfileResponse[0])) .ReturnsAsync(Result.Ok(new[] { new QualityProfileResponse { Key = "QP_KEY", Language = "cs" } })); client .Setup(x => x.GetQualityProfileChangeLogAsync(It.IsAny <QualityProfileChangeLogRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(Result.Ok(new QualityProfileChangeLogResponse { Events = new[] { new QualityProfileChangeLogEventResponse { Date = DateTime.MaxValue } } })); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetQualityProfileAsync("PROJECT_KEY", "ORG_KEY", SonarQubeLanguage.CSharp, CancellationToken.None); // Assert client.Verify(x => x.GetQualityProfilesAsync( // Defaults is set to true in the client It.Is <QualityProfileRequest>(r => r.Defaults == null && r.ProjectKey == null && r.OrganizationKey == "ORG_KEY"), It.IsAny <CancellationToken>()), Times.Once); client.Verify(x => x.GetQualityProfilesAsync( It.Is <QualityProfileRequest>(r => r.Defaults == null && r.ProjectKey == "PROJECT_KEY" && r.OrganizationKey == "ORG_KEY"), It.IsAny <CancellationToken>()), Times.Once); client.Verify(x => x.GetQualityProfileChangeLogAsync(It.IsAny <QualityProfileChangeLogRequest>(), It.IsAny <CancellationToken>()), Times.Once); result.Key.Should().Be("QP_KEY"); result.Language.Should().Be("cs"); result.TimeStamp.Should().Be(DateTime.MaxValue); }
protected async Task ConnectToSonarQube(string version = "5.6.0.0", string serverUrl = DefaultBasePath) { SetupRequest("api/server/version", version, serverUrl: serverUrl); SetupRequest("api/authentication/validate", "{ \"valid\": true}", serverUrl: serverUrl); await service.ConnectAsync( new ConnectionInformation(new Uri(serverUrl), "valeri", new SecureString()), CancellationToken.None); // Sanity checks service.IsConnected.Should().BeTrue(); service.SonarQubeVersion.Should().Be(new Version(version)); logger.InfoMessages.Should().Contain( x => x.StartsWith($"Connecting to '{serverUrl}", StringComparison.OrdinalIgnoreCase)); logger.InfoMessages.Should().Contain( x => x.StartsWith($"Connected to SonarQube '{version}'.")); }
public async Task GetRoslynExportProfileAsync_ReturnsExpectedResult() { // Arrange var roslynExport = new RoslynExportProfileResponse(); var client = GetMockSqClientWithCredentialAndVersion("5.6"); client.Setup(x => x.GetRoslynExportProfileAsync(It.IsAny <RoslynExportProfileRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => new Result <RoslynExportProfileResponse>(new HttpResponseMessage(), roslynExport)); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetRoslynExportProfileAsync("name", SonarQubeLanguage.CSharp, CancellationToken.None); // Assert client.VerifyAll(); result.Should().Be(roslynExport); }
public async Task SonarQubeService_UsesFactorySelector(string serverUrl, bool isSonarCloud) { var logger = new TestLogger(); var connectionInfo = new ConnectionInformation(new Uri(serverUrl)); var requestFactoryMock = CreateRequestFactory("1.2.3"); var selectorMock = new Mock <IRequestFactorySelector>(); selectorMock.Setup(x => x.Select(isSonarCloud, logger)).Returns(requestFactoryMock.Object); var testSubject = new SonarQubeService(Mock.Of <HttpMessageHandler>(), "user-agent", logger, selectorMock.Object, Mock.Of <ISecondaryIssueHashUpdater>()); await testSubject.ConnectAsync(connectionInfo, CancellationToken.None); selectorMock.Verify(x => x.Select(isSonarCloud, logger), Times.Once); requestFactoryMock.Invocations.Count.Should().Be(2); testSubject.IsConnected.Should().BeTrue(); var expectedServerType = isSonarCloud ? ServerType.SonarCloud : ServerType.SonarQube; testSubject.ServerInfo.ServerType.Should().Be(expectedServerType); testSubject.ServerInfo.Version.Should().Be(new Version(1, 2, 3)); }
public async Task GetRoslynExportProfileAsync_WhenServerIsGreaterThanOrEqualTo66_ReturnsExpectedResult() { // Arrange var roslynExport = new RoslynExportProfileResponse(); Expression <Func <RoslynExportProfileRequestV66Plus, bool> > matchRequest = r => r.OrganizationKey == "my-org"; var client = GetMockSqClientWithCredentialAndVersion("6.6"); client .Setup(x => x.GetRoslynExportProfileAsync(It.Is(matchRequest), CancellationToken.None)) .ReturnsAsync(Result.Ok(roslynExport)); var service = new SonarQubeService(WrapInMockFactory(client)); await service.ConnectAsync(new ConnectionInformation(new Uri("http://mysq.com")), CancellationToken.None); // Act var result = await service.GetRoslynExportProfileAsync("name", "my-org", SonarQubeLanguage.CSharp, CancellationToken.None); // Assert client.VerifyAll(); result.Should().Be(roslynExport); }