Esempio n. 1
0
            public async Task CreateAsync_Maps_Posts_And_Throws_HttpRequestException_When_ApiCall_Fails()
            {
                // Arrange
                var expectedWorkoutViewModel = new WorkoutViewModel {
                    Name = "Test workout 01"
                };
                var expectedWorkout = new Workout {
                    Name = "Test workout 01"
                };

                MapperMock
                .Setup(x => x.Map <WorkoutViewModel, Workout>(expectedWorkoutViewModel))
                .Returns(expectedWorkout)
                .Verifiable();
                HttpClientMock
                .Setup(x => x.PostEntityAsync(It.IsAny <string>(), expectedWorkout))
                .ReturnsAsync(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    Content    = new StringContent("Content as string")
                })
                .Verifiable();

                // Act, Assert
                await Assert.ThrowsAsync <HttpRequestException>(() =>
                                                                ServiceUnderTest.CreateAsync(expectedWorkoutViewModel));

                MapperMock.Verify(x => x.Map <WorkoutViewModel, Workout>(expectedWorkoutViewModel), Times.Once);
                HttpClientMock.Verify(x => x.PostEntityAsync(It.IsAny <string>(), expectedWorkout), Times.Once);
            }
Esempio n. 2
0
        public async Task Run_should_populate_StartTime_and_EndTime_and_TotalRunTime()
        {
            // given
            var beforeStart = DateTime.UtcNow;

            var response = new HttpResponse();

            response.ResponseTime = TimeSpan.FromSeconds(5);

            HttpClientMock httpClient = new HttpClientMock(response);
            var            runner     = new TestFileRunner(httpClient, GetRepositoryFactory(), new JsonConfiguration(), _capturedVariableProviderFactory.Object, GetTestFileRunnerLoggerFactory());

            var testFile = CreateTestFile(new[]
            {
                new Test()
                {
                    Url = "foo1"
                },
            });

            // when
            TestFileResult session = await runner.RunAsync(testFile, "development", "bob");

            // then
            Assert.That(session.StartTime, Is.GreaterThanOrEqualTo(beforeStart));
            Assert.That(session.EndTime, Is.GreaterThanOrEqualTo(session.StartTime));
            Assert.That(session.TotalRunTime, Is.EqualTo(session.EndTime - session.StartTime));
        }
Esempio n. 3
0
        public void Arrange()
        {
            _httpClientMock = new HttpClientMock();
            _httpClientMock
            .SetDefaultResponse(ResponseBuilder.Json(
                                    new OAuth2Token
            {
                AccessToken = "someaccesstoken",
                ExpiresIn   = 3600,
            }, new SystemTextMtwJsonSerializer()));

            _configuration = new SubmitLearnerDataConfiguration
            {
                OAuthTokenEndpoint = "https://localhost:12345/oauth2/token",
                OAuthClientId      = "some-client-id",
                OAuthClientSecret  = "super-secure-secret",
                OAuthScope         = "work",
            };

            _loggerMock = new Mock <ILogger <SubmitLearnerDataAuthenticator> >();

            _authenticator = new SubmitLearnerDataAuthenticator(
                _httpClientMock.AsHttpClient(),
                _configuration,
                _loggerMock.Object);
        }
Esempio n. 4
0
        public void EventSourceClient_KeepAliveResponse()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.SSE_Channels_Response(":keepalive\n\n");

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.CONNECTED, action.Action);
                Thread.Sleep(1000);
                Assert.AreEqual(0, eventsReceived.Count);
            }
        }
Esempio n. 5
0
        public void EventSourceClient_SegmentUpdateEvent_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"xxxx_xxxx_segments\",\"data\":\"{\\\"type\\\":\\\"SEGMENT_UPDATE\\\",\\\"changeNumber\\\":1585868933303,\\\"segmentName\\\":\\\"test-segment\\\"}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                eventsReceived.TryTake(out EventReceivedEventArgs ev, 10000);
                Assert.AreEqual(NotificationType.SEGMENT_UPDATE, ev.Event.Type);
                Assert.AreEqual(1585868933303, ((SegmentChangeNotification)ev.Event).ChangeNumber);
                Assert.AreEqual("test-segment", ((SegmentChangeNotification)ev.Event).SegmentName);
                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.CONNECTED, action.Action);
            }
        }
Esempio n. 6
0
        public void EventSourceClient_ControlEvent_StreamingDisabled_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"[?occupancy=metrics.publishers]control_pri\",\"data\":\"{\\\"type\\\":\\\"CONTROL\\\",\\\"controlType\\\":\\\"STREAMING_DISABLED\\\"}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                eventsReceived.TryTake(out EventReceivedEventArgs ev, 10000);
                Assert.AreEqual(NotificationType.CONTROL, ev.Event.Type);
                Assert.AreEqual(ControlType.STREAMING_DISABLED, ((ControlNotification)ev.Event).ControlType);
                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.CONNECTED, action.Action);
            }
        }
Esempio n. 7
0
        public void EventSourceClient_NotificationError_ShouldReceiveError()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "event: error\ndata: {\"message\":\"Token expired\",\"code\":40142,\"statusCode\":401,\"href\":\"https://help.ably.io/error/40142\"}\n\n";
                httpClientMock.SSE_Channels_Response(notification);

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.DISCONNECT, action.Action);
            }
        }
        public async Task ShouldGetPushNotificationsAsync_All()
        {
            // Arrange
            var loggerMock = new Mock <ILogger>();

            var httpClientMock = new HttpClientMock();

            httpClientMock.SetupSendAsync()
            .ReturnsAsync(NotificationOverviewResults.Success("notification_id_test", count: 3))
            .Verifiable();

            var appCenterConfiguration  = new TestAppCenterConfiguration();
            var pushNotificationService = new AppCenterPushNotificationService(loggerMock.Object, httpClientMock.Object, appCenterConfiguration);

            // Act
            var notificationOverviewResults = await pushNotificationService.GetPushNotificationsAsync(top : 30);

            // Assert
            this.testOutputHelper.WriteLine($"{ObjectDumper.Dump(notificationOverviewResults, DumpStyle.CSharp)}");

            notificationOverviewResults.Should().BeEquivalentTo(NotificationOverviewResults.GetExample1().Values);

            httpClientMock.VerifySendAsync(
                request => request.Method == HttpMethod.Get &&
                request.RequestUri == new Uri("https://appcenter.ms/api/v0.1/apps/testOrg/TestApp.Android/push/notifications?%24top=30&%24orderby=count%20desc&%24inlinecount=none"),
                Times.Exactly(1)
                );
            httpClientMock.VerifySendAsync(
                request => request.Method == HttpMethod.Get &&
                request.RequestUri == new Uri("https://appcenter.ms/api/v0.1/apps/testOrg/TestApp.iOS/push/notifications?%24top=30&%24orderby=count%20desc&%24inlinecount=none"),
                Times.Exactly(1)
                );
        }
        public async Task StayIdleGivenNoLogEvents()
        {
            // Arrange
            var httpClient = new HttpClientMock();

            // 1 ms period
            var period = TimeSpan.FromMilliseconds(1);

            using (new TimeRolledDurableHttpSink(
                       requestUri: "https://www.mylogs.com",
                       bufferBaseFileName: "SomeBuffer",
                       bufferRollingInterval: BufferRollingInterval.Day,
                       bufferFileSizeLimitBytes: null,
                       bufferFileShared: false,
                       retainedBufferFileCountLimit: null,
                       batchPostingLimit: 1,
                       batchSizeLimitBytes: ByteSize.MB,
                       period: period,
                       textFormatter: new NormalTextFormatter(),
                       batchFormatter: new ArrayBatchFormatter(),
                       httpClient: httpClient))
            {
                // Act
                await Task.Delay(10 *period);     // Sleep 10x the period

                // Assert
                httpClient.BatchCount.ShouldBe(0);
                httpClient.LogEvents.ShouldBeEmpty();
            }
        }
        public void SendAsync_UnitTest1()
        {
            var instance = new HttpClientMock();
            var request  = new HttpRequestMessage();

            instance.SendAsync(request);
        }
        public void SendAsync_UnitTest3()
        {
            var instance = new HttpClientMock();
            var request  = new HttpRequestMessage();

            instance.SendAsync(request, HttpCompletionOption.ResponseContentRead, new CancellationToken());
        }
        public async Task SendAsync_WithBodyIdempotent_Success()
        {
            var httpClientMock = new HttpClientMock();
            var httpClient     = new DefaultHttpClient(httpClientMock.HttpClient);
            var client         = new DummyClient(httpClient, null);
            var path           = "/x";
            var url            = $"{MercadoPagoConfig.BaseUrl}{path}";
            var request        = new DummyIdempotentRequest("hello");

            var httpResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{'name':'world'}"),
            };

            httpResponse.Headers.Add("X-Custom-Response-Header", "456");

            // Mock
            httpClientMock.MockRequest(url, System.Net.Http.HttpMethod.Post, httpResponse);

            DummyResource dummyResource =
                await client.SendAsync(path, MercadoPagoCore.Http.HttpMethod.Post, request);

            Assert.NotNull(dummyResource);
            Assert.Equal("world", dummyResource.Name);
        }
        public void SendAsync_UnitTest()
        {
            var instance = new HttpClientMock();
            var request  = new HttpRequestMessage();

            instance.SendAsync(request, new CancellationToken());
        }
        public async Task SearchAsync_NullParameters_Success()
        {
            var           httpClientMock = new HttpClientMock();
            var           httpClient     = new DefaultHttpClient(httpClientMock.HttpClient);
            var           client         = new DummyClient(httpClient, null);
            var           path           = "/x";
            SearchRequest request        = null;
            string        json           = File.ReadAllText("Client/Mock/DummySearchResponse.json");
            var           url            = $"{MercadoPagoConfig.BaseUrl}{path}";
            var           httpResponse   = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json),
            };

            // Mock
            httpClientMock.MockRequest(url, System.Net.Http.HttpMethod.Get, httpResponse);

            ResultsResourcesPage <DummyResource> resultsSearchPage
                = await client.SearchAsync(path, request);

            Assert.NotNull(resultsSearchPage);
            Assert.NotNull(resultsSearchPage.Paging);
            Assert.Equal(1000, resultsSearchPage.Paging.Total);
            Assert.Equal(10, resultsSearchPage.Paging.Limit);
            Assert.Equal(0, resultsSearchPage.Paging.Offset);
            Assert.NotNull(resultsSearchPage.Results);
            Assert.True(resultsSearchPage.Results.Count > 0);
        }
        public async Task SendAsync_InvalidJsonResponse_Error()
        {
            var httpClientMock = new HttpClientMock();
            var httpClient     = new DefaultHttpClient(httpClientMock.HttpClient);
            var client         = new DummyClient(httpClient, null);
            var path           = "/x";
            var url            = $"{MercadoPagoConfig.BaseUrl}{path}";
            var request        = new DummyRequest("hello");

            var httpResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("invalid json"),
            };

            // Mock
            httpClientMock.MockRequest(url, System.Net.Http.HttpMethod.Post, httpResponse);

            try
            {
                await client.SendAsync(path, MercadoPagoCore.Http.HttpMethod.Post, request);
            }
            catch (MercadoPagoApiException ex)
            {
                Assert.Contains("Invalid response from API.", ex.Message);
            }
        }
        public async Task SendAsync_WithRequestOptions_Success()
        {
            var httpClientMock = new HttpClientMock();
            var httpClient     = new DefaultHttpClient(httpClientMock.HttpClient);
            var client         = new DummyClient(httpClient, null);
            var path           = "/x";
            var url            = $"{MercadoPagoConfig.BaseUrl}{path}";
            var request        = new DummyRequest("hello");

            var requestOptions = new RequestOptions
            {
                AccessToken   = Guid.NewGuid().ToString(),
                RetryStrategy = new DefaultRetryStrategy(0),
            };

            requestOptions.CustomHeaders.Add("X-Custom-Header", "custom");
            requestOptions.CustomHeaders.Add(Headers.ContentType, "plain/text");       // should not add
            requestOptions.CustomHeaders.Add(Headers.Authorization, "Basic user:123"); // should not add

            var httpResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{'name':'world'}"),
            };

            httpResponse.Headers.Add("X-Custom-Response-Header", "456");

            // Mock
            httpClientMock.MockRequest(url, System.Net.Http.HttpMethod.Put, httpResponse);

            DummyResource dummyResource =
                await client.SendAsync(path, MercadoPagoCore.Http.HttpMethod.Put, request, requestOptions);

            Assert.NotNull(dummyResource);
            Assert.Equal("world", dummyResource.Name);
        }
Esempio n. 17
0
            public async Task CreateAsync_Maps_Posts_And_Completes_When_ApiCall_Succeeds()
            {
                // Arrange
                var expectedWorkoutViewModel = new WorkoutViewModel {
                    Name = "Test workout 01"
                };
                var expectedWorkout = new Workout {
                    Name = "Test workout 01"
                };

                MapperMock
                .Setup(x => x.Map <WorkoutViewModel, Workout>(expectedWorkoutViewModel))
                .Returns(expectedWorkout)
                .Verifiable();
                HttpClientMock
                .Setup(x => x.PostEntityAsync(It.IsAny <string>(), expectedWorkout))
                .ReturnsAsync(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content    = new StringContent("Content as string")
                })
                .Verifiable();

                // Act
                await ServiceUnderTest.CreateAsync(expectedWorkoutViewModel);

                // Assert
                MapperMock.Verify(x => x.Map <WorkoutViewModel, Workout>(expectedWorkoutViewModel), Times.Once);
                HttpClientMock.Verify(x => x.PostEntityAsync(It.IsAny <string>(), expectedWorkout), Times.Once);
            }
Esempio n. 18
0
            public async Task ReadOneAsync_Gets_Maps_And_Returns_A_Workout_When_ApiCall_Returns_Workout()
            {
                // Arrange
                const int id = 1;
                var       expectedWorkout = new Workout {
                    Name = "Test workout 01", Id = id
                };
                var expectedWorkoutViewModel = new WorkoutViewModel {
                    Name = "Test workout 01", Id = id
                };

                HttpClientMock
                .Setup(x => x.GetStringAsync(It.IsAny <string>()))
                .ReturnsAsync(JsonConvert.SerializeObject(expectedWorkout))
                .Verifiable();
                MapperMock
                .Setup(x => x.Map <Workout, WorkoutViewModel>(It.IsAny <Workout>()))
                .Returns(expectedWorkoutViewModel)
                .Verifiable();

                // Act
                var result = await ServiceUnderTest.ReadOneAsync(id);

                // Assert
                Assert.Same(expectedWorkoutViewModel, result);
                HttpClientMock.Verify(x => x.GetStringAsync(It.IsAny <string>()), Times.Once);
                MapperMock.Verify(x => x.Map <Workout, WorkoutViewModel>(It.IsAny <Workout>()), Times.Once);
            }
Esempio n. 19
0
        public void SendBulkImpressions_WithRetries()
        {
            var impressions = new List <KeyImpression>();

            for (int i = 0; i < 10; i++)
            {
                impressions.Add(new KeyImpression($"key-{i}", $"feature-{i}", "off", 1, 1, "label-test", $"bucket-{i}"));
            }

            var data1 = "[{\"f\":\"feature-0\",\"i\":[{\"k\":\"key-0\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-0\"}]},{\"f\":\"feature-1\",\"i\":[{\"k\":\"key-1\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-1\"}]},{\"f\":\"feature-2\",\"i\":[{\"k\":\"key-2\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-2\"}]},{\"f\":\"feature-3\",\"i\":[{\"k\":\"key-3\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-3\"}]},{\"f\":\"feature-4\",\"i\":[{\"k\":\"key-4\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-4\"}]},{\"f\":\"feature-5\",\"i\":[{\"k\":\"key-5\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-5\"}]},{\"f\":\"feature-6\",\"i\":[{\"k\":\"key-6\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-6\"}]},{\"f\":\"feature-7\",\"i\":[{\"k\":\"key-7\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-7\"}]},{\"f\":\"feature-8\",\"i\":[{\"k\":\"key-8\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-8\"}]},{\"f\":\"feature-9\",\"i\":[{\"k\":\"key-9\",\"t\":\"off\",\"m\":1,\"c\":1,\"r\":\"label-test\",\"b\":\"bucket-9\"}]}]";

            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.Post_Response("/api/testImpressions/bulk", 500, data1, "fail");

                var impressionsSdkApiClient = new ImpressionsSdkApiClient("", new Dictionary <string, string>(), httpClientMock.GetUrl(), 10000, 10000, _telemetryRuntimeProducer.Object, _wrapperAdapter, 10);
                impressionsSdkApiClient.SendBulkImpressions(impressions);

                Thread.Sleep(5000);

                var logs = httpClientMock.GetImpressionLogs();
                Assert.AreEqual(3, logs.Count);

                foreach (var log in logs)
                {
                    Assert.IsTrue(log.RequestMessage.Body.Equals(data1));
                }
            }
        }
Esempio n. 20
0
        public async Task RequestsColumnsFromQueryIfNoExpand()
        {
            var workitemReferences = new[] { new WorkItemReference(1), new WorkItemReference(2), new WorkItemReference(3) };
            var columns            = new[] { new ColumnReference("C1", "System.C1"), new ColumnReference("C2", "System.C2") };
            var queryResult        = new FlatWorkItemsQueryResult {
                QueryType = "flat", WorkItems = workitemReferences, Columns = columns
            };

            HttpClientMock.Setup(c => c.ExecuteGet <JObject>(It.IsAny <string>(), CancellationToken))
            .ReturnsAsync(JObject.FromObject(queryResult));

            var workitems = workitemReferences.Select(r => new WorkItem {
                Id = r.Id
            });

            SetupGetCollectionOf <WorkItem>(url => url.Contains(string.Join(',', columns.Select(c => c.ReferenceName))) && !url.Contains("$expand=All"))
            .ReturnsAsync(new CollectionResponse <WorkItem> {
                Value = workitems
            });

            var result = await Client.GetWorkItemsAsync(Guid.NewGuid(), expand : false, cancellationToken : CancellationToken);

            result.Should().NotBeEmpty();
            result.Should().BeEquivalentTo(workitems);

            HttpClientMock.VerifyAll();
        }
        public async Task DoNotFetchMorePullRequestsIfCreatedAfterIsSet()
        {
            var page1 = new[] { CreatePR("PR 1", daysAgo: 1), CreatePR("PR 2 skip", daysAgo: 1) };
            var page2 = new[] { CreatePR("PR 3 skip", daysAgo: 3), CreatePR("PR 4", daysAgo: 5) };
            var page3 = new[] { CreatePR("PR 5", daysAgo: 6) };

            SetupPagedGetCollectionOf <PullRequest>()
            .ReturnsAsync(new CollectionResponse <PullRequest> {
                Value = page1
            })
            .ReturnsAsync(new CollectionResponse <PullRequest> {
                Value = page2
            })
            .ReturnsAsync(new CollectionResponse <PullRequest> {
                Value = page3
            })
            .ReturnsAsync(new CollectionResponse <PullRequest> {
                Value = Enumerable.Empty <PullRequest>()
            });

            var query = new PullRequestQuery {
                CreatedAfter = DateTime.UtcNow.AddDays(-4)
            };
            var result = await Client.GetPullRequestsAsync(ProjectName, RepositoryName, query, CancellationToken);

            result.Should().HaveCount(3);
            HttpClientMock.Verify(c => c.ExecuteGet <CollectionResponse <PullRequest> >(It.IsAny <string>(), CancellationToken), Times.Exactly(2));
        }
Esempio n. 22
0
        public async Task AggregatesWorkitemsFromFlatQuery()
        {
            var workitemReferences = new[] { new WorkItemReference(1), new WorkItemReference(2), new WorkItemReference(3) };
            var queryResult        = new FlatWorkItemsQueryResult {
                QueryType = "flat", WorkItems = workitemReferences
            };

            HttpClientMock.Setup(c => c.ExecuteGet <JObject>(It.IsAny <string>(), CancellationToken))
            .ReturnsAsync(JObject.FromObject(queryResult));

            var workitems = workitemReferences.Select(r => new WorkItem {
                Id = r.Id
            });

            SetupGetCollectionOf <WorkItem>(url => url.Contains("$expand=All"))
            .ReturnsAsync(new CollectionResponse <WorkItem> {
                Value = workitems
            });

            var result = await Client.GetWorkItemsAsync(Guid.NewGuid(), true, CancellationToken);

            result.Should().NotBeEmpty();
            result.Should().BeEquivalentTo(workitems);

            HttpClientMock.VerifyAll();
        }
Esempio n. 23
0
        public async Task AggregatesWorkitemsFromHierarchicalQuery()
        {
            var workitemLinks = new[]
            {
                new WorkItemLink(new WorkItemReference(1), new WorkItemReference(2), "forward"),
                new WorkItemLink(new WorkItemReference(1), new WorkItemReference(3), "forward"),
                new WorkItemLink(new WorkItemReference(2), new WorkItemReference(4), "forward"),
                new WorkItemLink(new WorkItemReference(5), new WorkItemReference(6), "forward"),
            };
            var queryResult = new HierarchicalWorkItemsQueryResult {
                QueryType = "tree", WorkItemRelations = workitemLinks
            };

            HttpClientMock.Setup(c => c.ExecuteGet <JObject>(It.IsAny <string>(), CancellationToken))
            .ReturnsAsync(JObject.FromObject(queryResult));

            var workitems = workitemLinks.SelectMany(l => new[] { l.Source, l.Target })
                            .Distinct()
                            .Select(r => new WorkItem {
                Id = r.Id
            });

            SetupGetCollectionOf <WorkItem>(url => url.Contains("$expand=All"))
            .ReturnsAsync(new CollectionResponse <WorkItem> {
                Value = workitems
            });

            var result = await Client.GetWorkItemsAsync(Guid.NewGuid(), true, CancellationToken);

            result.Should().NotBeEmpty();
            result.Should().BeEquivalentTo(workitems);

            HttpClientMock.VerifyAll();
        }
Esempio n. 24
0
        public async Task GetWorkItemsShouldComposeCorrectUrlForFlatQueries()
        {
            var query       = WorkItemsQuery.Get("Dummy query");
            var queryResult = new FlatWorkItemsQueryResult
            {
                Columns   = new[] { new ColumnReference("Id", "System.Id"), new ColumnReference("Title", "System.Title") },
                WorkItems = new[] { new WorkItemReference(2), new WorkItemReference(34), new WorkItemReference(56) }
            };
            var fields    = queryResult.Columns.Select(c => c.ReferenceName);
            var ids       = queryResult.WorkItems.Select(w => w.Id);
            var workItems = ids.Select(i => new WorkItem {
                Id = i
            });

            HttpClientMock.Setup(c => c.ExecutePost <FlatWorkItemsQueryResult>(It.IsAny <string>(), It.Is <WorkItemsQuery>(q => !q.IsHierarchical), CancellationToken))
            .ReturnsAsync(queryResult)
            .Verifiable();

            HttpClientMock.Setup(c => c.ExecuteGet <CollectionResponse <WorkItem> >(It.Is <string>(u => VerifyWorkItemsUrl(u, fields, ids)), CancellationToken))
            .ReturnsAsync(new CollectionResponse <WorkItem> {
                Value = workItems
            })
            .Verifiable();

            var result = await Client.GetWorkItemsAsync(query, false, CancellationToken);

            result.Should().HaveCount(workItems.Count());
            result.Should().BeEquivalentTo(workItems);

            HttpClientMock.Verify();
        }
        public async Task RespectQueueLimit()
        {
            // Arrange
            var httpClient = new HttpClientMock();

            // Create 10 log events
            var logEvents = Enumerable
                            .Range(1, 10)
                            .Select(number => Some.LogEvent("Event {number}", number))
                            .ToArray();

            using (var sink = new HttpSink(
                       "some/route",
                       1,
                       1,                            // Queue only holds 1 event
                       TimeSpan.FromMilliseconds(1), // 1 ms period
                       new NormalTextFormatter(),
                       new ArrayBatchFormatter(),
                       httpClient))
            {
                // Act
                foreach (var logEvent in logEvents)
                {
                    sink.Emit(logEvent);
                }

                await Task.Delay(TimeSpan.FromMilliseconds(10));    // Sleep 10x the period

                // Assert
                httpClient.LogEvents.Length.ShouldBeLessThan(logEvents.Length);    // Some log events will have been dropped
            }
        }
        public async Task PutNotFound()
        {
            var person = new Person {
                GivenName = "GivenName", Surname = "Surname"
            };
            var content = "Resource could not be found, 307EEC28-22DE-4BE3-8803-0AB5BE9DEBD8";

            PrepareMockNotFound(HttpMethod.Put, content);
            var client = new RestClient(_httpSender);

            Assert.IsNotNull(client);
            try
            {
                await client.PutAndReturnUpdatedObjectAsync("Persons/23", person);

                Assert.Fail("Expected an exception.");
            }
            catch (HttpOperationException e)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, e.Response.StatusCode);
                Assert.IsTrue(e.Response.Content.Contains(content));
                HttpClientMock.VerifyAll();
                throw;
            }
        }
Esempio n. 27
0
        public async Task GetWorkItemUpdatesVerifyUrl()
        {
            const int workItemId = 78778;
            var       updates    = new[]
            {
                new WorkItemUpdate {
                    WorkItemId = workItemId, Id = 1, Revision = 1
                },
                new WorkItemUpdate {
                    WorkItemId = workItemId, Id = 2, Revision = 2
                }
            };

            HttpClientMock.Setup(c => c.ExecuteGet <CollectionResponse <WorkItemUpdate> >(It.Is <string>(u => VerifyUpdatesUrl(u, workItemId)), CancellationToken))
            .ReturnsAsync(new CollectionResponse <WorkItemUpdate> {
                Value = updates
            })
            .Verifiable();

            var result = await Client.GetWorkItemUpdatesAsync(workItemId, CancellationToken);

            result.Should().HaveCount(2);
            result.Should().BeEquivalentTo(updates);

            HttpClientMock.Verify();
        }
Esempio n. 28
0
        public async Task StayIdleGivenNoLogEvents()
        {
            // Arrange
            var httpClient = new HttpClientMock();

            using (new FileSizeRolledDurableHttpSink(
                       "some/route",
                       "Buffer",
                       null,
                       false,
                       null,
                       1,
                       TimeSpan.FromMilliseconds(1),  // 1 ms period
                       new NormalTextFormatter(),
                       new ArrayBatchFormatter(),
                       httpClient))
            {
                // Act
                await Task.Delay(TimeSpan.FromMilliseconds(10));    // Sleep 10x the period

                // Assert
                httpClient.BatchCount.ShouldBe(0);
                httpClient.LogEvents.ShouldBeEmpty();
            }
        }
Esempio n. 29
0
        public void Arrange()
        {
            _httpClientMock = new HttpClientMock();
            _httpClientMock
            .When(c => true)
            .Then(ResponseBuilder.Json(
                      new RestProxyPublishMessageResponse
            {
                Offsets = new[]
                {
                    new RestProxyResponseOffset
                    {
                        Partition = 0,
                        Offset    = 1,
                    },
                },
            }));

            _configuration = new DataServicePlatformConfiguration
            {
                KafkaRestProxyUrl  = "https://localhost:9876",
                UkrlpProviderTopic = "some-topic",
            };

            _loggerMock = new Mock <ILogger <KafkaRestProxyUkrlpDataReceiver> >();

            _receiver = new KafkaRestProxyUkrlpDataReceiver(
                _httpClientMock.AsHttpClient(),
                _configuration,
                _loggerMock.Object);

            _cancellationToken = new CancellationToken();
        }
Esempio n. 30
0
        public void Arrange()
        {
            _httpClientMock = new HttpClientMock();
            _httpClientMock
            .SetDefaultResponse(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent("<element />", Encoding.UTF8, "text/xml")
            });

            _configuration = new UkrlpApiConfiguration
            {
                WebServiceUrl = "http://localhost:1234",
                StakeholderId = 123,
            };

            _logger = new Mock <ILogger <UkrlpSoapApiClient> >();

            _requestSerializer = new Mock <IRequestSerializer>();
            _requestSerializer.Setup(serializer => serializer.Serialize(It.IsAny <ProviderQueryRequest>()))
            .Returns("<unit-test>testing</unit-test>");

            _responseDeserializer = new Mock <IResponseDeserializer>();
            _responseDeserializer.Setup(deserializer => deserializer.DeserializeResponse(It.IsAny <string>()))
            .Returns(new Provider[0]);

            _client = new UkrlpSoapApiClient(
                _httpClientMock.AsHttpClient(),
                _configuration,
                _logger.Object,
                _requestSerializer.Object,
                _responseDeserializer.Object);
        }
		public void Constructor_NullProgressIndicator_ExceptionThrown()
		{
			// Fixture setup
			IHttpClient httpClient = new HttpClientMock();
			IRssParser rssParser = new RssParserMock();
			IProgressIndicator progressIndicator = null;

			// Exercise system
			// Verify outcome
			Assert.ThrowsException<ArgumentNullException>
				(() => new NewsFeedViewModel(httpClient, rssParser, progressIndicator));

			// Teardown
		}
		public async Task GetLatestNewsAsync_CallWithoutParameters_ExceptionThrown()
		{
			// Fixture setup
			IHttpClient httpClient = new HttpClientMock();
			IRssParser rssParser = new RssParserMock();
			IProgressIndicator progressIndicator = new ProgressIndicatorMock();

			var viewModel = new NewsFeedViewModel(httpClient, rssParser, progressIndicator);

			// Exercise system
			var task = viewModel.GetLatestNewsAsync();

			// Verify outcome
			await AssertEx.ThrowsExceptionAsync<ArgumentException>(() => task);

			// Teardown
		}
		public async Task GetLatestNewsAsync_NullRssParser_ExceptionThrown()
		{
			// Fixture setup
			var name = "News channel";
			var feedUri = new Uri("http://news.com/rss");

			IHttpClient httpClient = new HttpClientMock();
			IRssParser rssParser = null;

			var newsChannel = new NewsChannel(name, feedUri);

			// Exercise system
			var task = newsChannel.GetLatestNewsAsync(httpClient, rssParser);

			// Verify outcome
			await AssertEx.ThrowsExceptionAsync<ArgumentNullException>(() => task);

			// Teardown
		}
		public async Task GetLatestNewsAsync_UsingGazetaRuSampleData_ValidNewsFeed()
		{
			// Fixture setup
			var name = "News channel";
			var feedUri = new Uri("http://news.com/rss");

			IHttpClient httpClient = new HttpClientMock { SampleDataPreference = SampleDataPreference.GazetaRu };
			IRssParser rssParser = new SyndicationFeedDecorator();

			var newsChannel = new NewsChannel(name, feedUri);

			var expectedCount = 3;
			var expectedFirstItemTitle = "Минюст включил Национальный фонд в поддержку демократии в список нежелательных организаций";
			var expectedFirstItemText = "Министерство юстиции России включило Национальный фонд в поддержку демократии в список иностранных и международных неправительственных организаций, деятельность которых на территории страны признана нежелательной. Об этом сообщается на ...";
			var expectedFirstItemPublicationDate = new DateTimeOffset(2015, 7, 29, 19, 17, 5, TimeSpan.FromHours(3));
			Uri expectedFirstItemImageSource = null;

			// Exercise system
			var newsFeed = await newsChannel.GetLatestNewsAsync(httpClient, rssParser);
			var feedItems = newsFeed.Items.ToList();
			var firstItem = feedItems[0];

			// Verify outcome
			Assert.AreEqual(feedItems.Count, expectedCount);
			Assert.AreEqual(firstItem.Title, expectedFirstItemTitle);
			Assert.AreEqual(firstItem.Text, expectedFirstItemText);
			Assert.AreEqual(firstItem.PublicationDate, expectedFirstItemPublicationDate);
			Assert.AreEqual(firstItem.ImageSource, expectedFirstItemImageSource);

			// Teardown
		}
		public async Task GetLatestNewsAsync_UsingGazetaRuSampleData_NoHtmlSpecialEntitiesInText()
		{
			// Fixture setup
			var name = "News channel";
			var feedUri = new Uri("http://news.com/rss");

			IHttpClient httpClient = new HttpClientMock { SampleDataPreference = SampleDataPreference.GazetaRu };
			IRssParser rssParser = new SyndicationFeedDecorator();

			var newsChannel = new NewsChannel(name, feedUri);

			var expectedResult = false;

			// Exercise system
			var newsFeed = await newsChannel.GetLatestNewsAsync(httpClient, rssParser);
			var feedItems = newsFeed.Items.ToList();
			var thirdItem = feedItems[2];
			var itemContainsQuotationMark = thirdItem.Text.Contains("&quot;");

			// Verify outcome
			Assert.AreEqual(itemContainsQuotationMark, expectedResult);

			// Teardown
		}
		public async Task GetLatestNewsAsync_UsingLentaRuSampleData_ValidNewsFeed()
		{
			// Fixture setup
			var name = "News channel";
			var feedUri = new Uri("http://news.com/rss");

			IHttpClient httpClient = new HttpClientMock {SampleDataPreference = SampleDataPreference.LentaRu};
			IRssParser rssParser = new SyndicationFeedDecorator();

			var newsChannel = new NewsChannel(name, feedUri);

			var expectedCount = 3;
			var expectedFirstItemTitle = "На побережье французского острова в Индийском океане нашли обломок самолета";
			var expectedFirstItemText = "На побережье французского острова Реюньон, расположенного в Индийском океане к востоку от Мадагаскара, найден обломок неизвестного самолета. Специалисты считают, что трехметровая деталь могла принадлежать малайзийскому «Боингу», который пропал в ночь на 8 марта 2014 года.";
			var expectedFirstItemPublicationDate = new DateTimeOffset(2015, 7, 29, 19, 23, 0, TimeSpan.FromHours(3));
			var expectedFirstItemImageSource = new Uri("http://icdn.lenta.ru/images/2015/07/29/18/20150729183227894/pic_df052e4cec4b74c4b14d369026bcef69.jpg");

			// Exercise system
			var newsFeed = await newsChannel.GetLatestNewsAsync(httpClient, rssParser);
			var feedItems = newsFeed.Items.ToList();
			var firstItem = feedItems[0];

			// Verify outcome
			Assert.AreEqual(feedItems.Count, expectedCount);
			Assert.AreEqual(firstItem.Title, expectedFirstItemTitle);
			Assert.AreEqual(firstItem.Text, expectedFirstItemText);
			Assert.AreEqual(firstItem.PublicationDate, expectedFirstItemPublicationDate);
			Assert.AreEqual(firstItem.ImageSource, expectedFirstItemImageSource);

			// Teardown
		}
		public async Task GetLatestNewsAsync_MockForTwoNewsChannels_ValidNewsItemsSortingOrder()
		{
			// Fixture setup
			var firstItem = new NewsItem("First item", "News text", DateTimeOffset.Now, null);
			var secondItem = new NewsItem("Second item", "News text", firstItem.PublicationDate.AddSeconds(1), null);

			var requestCounter = 0;
			Func<string, NewsFeed> parsingFunc = rss =>
			{
				requestCounter++;
				if (requestCounter == 1) return new NewsFeed(new[] { firstItem });
				return new NewsFeed(new[] { secondItem });
			};

			IHttpClient httpClient = new HttpClientMock();
			IRssParser rssParser = new RssParserMock { CustomParsingFunction = parsingFunc };
			IProgressIndicator progressIndicator = new ProgressIndicatorMock();

			var viewModel = new NewsFeedViewModel(httpClient, rssParser, progressIndicator);
			var newsChannel = new NewsChannel("News channel", new Uri("http://news.com/rss"));

			var expectedFirstItemTitle = secondItem.Title;

			// Exercise system
			await viewModel.GetLatestNewsAsync(newsChannel, newsChannel);

			// Verify outcome
			Assert.AreEqual(viewModel.News[0].Title, expectedFirstItemTitle);

			// Teardown
		}
		public async Task GetLatestNewsAsync_MockForTwoNewsChannels_ValidItemCount()
		{
			// Fixture setup
			var newsItem = new NewsItem("News item", "News text", DateTimeOffset.Now, null);
			Func<string, NewsFeed> parsingFunc = rss => new NewsFeed(new[] { newsItem });

			IHttpClient httpClient = new HttpClientMock();
			IRssParser rssParser = new RssParserMock { CustomParsingFunction = parsingFunc };
			IProgressIndicator progressIndicator = new ProgressIndicatorMock();

			var viewModel = new NewsFeedViewModel(httpClient, rssParser, progressIndicator);
			var newsChannel = new NewsChannel("News channel", new Uri("http://news.com/rss"));

			var expectedNewsCount = 2;

			// Exercise system
			await viewModel.GetLatestNewsAsync(newsChannel, newsChannel);

			// Verify outcome
			Assert.AreEqual(viewModel.News.Count, expectedNewsCount);

			// Teardown
		}
		public async Task GetLatestNewsAsync_NullNewsFeedFromNewsChannel_ExceptionThrown()
		{
			// Fixture setup
			IHttpClient httpClient = new HttpClientMock();
			IRssParser rssParser = new RssParserMock();
			IProgressIndicator progressIndicator = new ProgressIndicatorMock();

			var viewModel = new NewsFeedViewModel(httpClient, rssParser, progressIndicator);
			var newsChannel = new NewsChannel("News channel", new Uri("http://news.com/rss"));

			// Exercise system
			var task = viewModel.GetLatestNewsAsync(newsChannel);

			// Verify outcome
			await AssertEx.ThrowsExceptionAsync<NullReferenceException>(() => task);

			// Teardown
		}