public void CanAddNewSubscription() { var httpClient = new StubHttpClient() { ExpectedUrl = endpointUrls.AddSubscription, ExpectedResponse = "", }; var reader = new ReaderAccount(httpClient, endpointUrls); reader.AddSubscription("http://feeds.feedburner.com/ajaxian"); }
public void SetUp() { this.Client = new CronofyAccountClient(AccessToken); this.Http = new StubHttpClient(); Client.HttpClient = Http; }
public void CanParseAtomBasedSubscriptionItems() { var httpClient = new StubHttpClient() { ExpectedUrl = endpointUrls.SubscriptionItems + "feed%2Fid", // feed ID must be URL-encoded ExpectedResponse = @"{ ""items"": [ { ""title"": ""Ajaxian » Front Page"", ""content"": { ""content"": ""Dummy Content"" } } ] }", }; var reader = new ReaderAccount(httpClient, endpointUrls); var subscription = new Subscription(null) { Id = "feed/id", }; Assert.AreEqual("Ajaxian » Front Page", reader.ItemsForSubscription(subscription).ElementAt(0).Title); Assert.AreEqual("Dummy Content", reader.ItemsForSubscription(subscription).ElementAt(0).Content); }
public void SetUp() { this.client = new CronofyOAuthClient(clientId, clientSecret); this.http = new StubHttpClient(); client.HttpClient = http; }
public async void GetContent_given_valid_url_of_invalid_imageformat_returns_null() { var mock = new Mock <ImgurRatelimiter>(null); mock.Setup(m => m.IsRequestAllowed()).Returns(true); mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true); var imageId = "example"; var output = new ImgurImage { Height = 5, Width = 10, Title = "test", Link = $"i.imgur.com/{imageId}", Type = "image/png" }; var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri($"https://api.imgur.com/3/image/{imageId}"), HttpStatusCode.OK, new ApiHelper <ImgurImage> { Data = output }); var source = new ImgurImageSource(StubHttpClient.Create(handler), mock.Object); source.Settings = CreateSettings(); var result = await source.GetContent(imageId); Assert.Null(result); mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once); mock.Verify(i => i.IsRequestAllowed(), Times.Once); }
public async void GetContent_given_username_with_1_image_of_invalid_type_returns_empty_album() { var mock = new Mock <ImgurRatelimiter>(null); mock.Setup(m => m.IsRequestAllowed()).Returns(true); mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true); var username = "******"; var image = new ImgurImage { Height = 10, Width = 5, Title = "title", Type = "image/png" }; var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/count"), HttpStatusCode.OK, new ApiHelper <int> { Data = 1 }); handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/0"), HttpStatusCode.OK, new ApiHelper <ICollection <ImgurImage> > { Data = new List <ImgurImage> { image } }); var source = new ImgurAccountImagesSource(StubHttpClient.Create(handler), mock.Object); source.Settings = CreateSettings(); var result = await source.GetContent(username); Assert.NotNull(result); Assert.Empty(result.Images); mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once); mock.Verify(i => i.IsRequestAllowed(), Times.Exactly(2)); }
public ApplicationCalendars() { this.client = new CronofyOAuthClient(clientId, clientSecret); this.http = new StubHttpClient(); client.HttpClient = http; }
public void SetUp() { // mock logger var mockLogger = Substitute.For <ILogger>(); mockLogger.IsDebugEnabled.Returns(true); mockLogger.IsInfoEnabled.Returns(true); mockLogger.IsWarnEnabled.Returns(true); mockLogger.IsErrorEnabled.Returns(true); // mock trust manager var trustManager = Substitute.For <ISSLTrustManager>(); var openKitConfig = Substitute.For <IOpenKitConfiguration>(); openKitConfig.EndpointUrl.Returns(BaseUrl); openKitConfig.DefaultServerId.Returns(ServerId); openKitConfig.ApplicationId.Returns(ApplicationId); openKitConfig.TrustManager.Returns(trustManager); var threadSuspender = Substitute.For <IInterruptibleThreadSuspender>(); // HTTPClient spy var httpConfiguration = HttpClientConfiguration.From(openKitConfig); spyClient = Substitute.ForPartsOf <StubHttpClient>(mockLogger, httpConfiguration, threadSuspender); mockAdditionalParameters = Substitute.For <IAdditionalQueryParameters>(); }
public HmacVerification() { this.client = new CronofyOAuthClient(clientId, clientSecret); this.http = new StubHttpClient(); client.HttpClient = http; }
public async void GetContent_given_url_for_listing_with_a_selfpost_returns_empty_album() { var tokenMock = new Mock <ITokenAcquirer <RedditToken> >(); tokenMock.Setup(m => m.AcquireToken()).ReturnsAsync(new RedditToken { Access_token = "test" }); var query = "example.json"; var returnedInfo = CreateApiReturnValue(new RedditPost { Is_self = true }); var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=1"), HttpStatusCode.OK, returnedInfo); var client = StubHttpClient.Create(handler); var source = new RedditSource(client, null, null, null, tokenMock.Object); var result = await source.GetContent(query, 1); Assert.NotNull(result); Assert.Empty(result.GetImages()); Assert.Empty(result.GetCollections()); tokenMock.Verify(i => i.AcquireToken(), Times.Once); }
public async Task setup_scenario() { var retryManager = new StubRetryManager { Delay = new StubRetryDelay(10), Predicate = new StubRetryPredicate(2) }; _baseHttpClient = new StubHttpClient(); var configuration = new RetryingConfiguration { RetryPolicy = "default" }; var httpClient = _baseHttpClient.AddRetrying( configuration, retryManager, new [] { _callback }); var message = new HttpRequestMessage(HttpMethod.Get, "/get-content"); message.Properties.Add("propertyA", "valueA"); message.Properties.Add("propertyB", 12358); try { await httpClient.SendAsync(message); } catch { // Ignore the exception } }
public GetTokenFromRefreshToken() { this.client = new CronofyOAuthClient(clientId, clientSecret); this.http = new StubHttpClient(); client.HttpClient = http; }
public async void GetContent_given_url_for_listing_with_link_containing_extension_but_nonsupported_domain_returns_album_with_image() { var tokenMock = new Mock <ITokenAcquirer <RedditToken> >(); tokenMock.Setup(m => m.AcquireToken()).ReturnsAsync(new RedditToken { Access_token = "test" }); var url = "example.com/test.jpg"; var query = "example.json"; var returnedInfo = CreateApiReturnValue(new RedditPost { Domain = "example.com", Url = url }); var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=1"), HttpStatusCode.OK, returnedInfo); var client = StubHttpClient.Create(handler); var source = new RedditSource(client, null, null, null, tokenMock.Object); source.Settings = CreateSettings(); var result = await source.GetContent(query, 1); Assert.NotNull(result); Assert.Equal(1, result.GetImages().Count()); Assert.NotNull(result.GetImages().First() as GenericImage); tokenMock.Verify(i => i.AcquireToken(), Times.Once); }
public async void GetContent_given_albumid_with_images_of_invalid_type_returns_empty_album() { var mock = new Mock <ImgurRatelimiter>(null); mock.Setup(m => m.IsRequestAllowed()).Returns(true); mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true); var albumId = "example"; var imageNum = 15; var album = new ImgurAlbum { Images = new List <ImgurImage>(Enumerable.Repeat(new ImgurImage { Type = "image/test" }, imageNum)) }; var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri($"https://api.imgur.com/3/album/{albumId}"), HttpStatusCode.OK, new ApiHelper <ImgurAlbum> { Data = album }); var source = new ImgurAlbumSource(StubHttpClient.Create(handler), mock.Object); var result = await source.GetContent(albumId); Assert.NotNull(result); Assert.NotNull(result.Images); Assert.Equal(0, result.Images.Count); mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once); mock.Verify(i => i.IsRequestAllowed(), Times.Once); }
private Property TestReturnsExpectedWithHttpStatusCode(HttpStatusCode st, Func <HttpSender, SendResult> act) { // Arrange StubHttpClient client = StubHttpClient.ThatReturns(st); var sut = new HttpSender(client); sut.Configure(new LocationMethod("ignored location")); // Act SendResult r = act(sut); // Assert var code = (int)st; bool isFatal = r == SendResult.FatalFail; bool isRetryable = r == SendResult.RetryableFail; bool isSuccess = r == SendResult.Success; Assert.True(client.IsCalled, "Stub HTTP client isn't called"); return(isRetryable .Equals(code >= 500 || code == 408 || code == 429) .Or(isSuccess.Equals(code >= 200 && code <= 206)) .Or(isFatal.Equals(code >= 400 && code < 500)) .Classify(isSuccess, "Success with code: " + code) .Classify(isRetryable, "Retryable with code: " + code) .Classify(isFatal, "Fatal with code: " + code)); }
public RevokeToken() { this.client = new CronofyOAuthClient(clientId, clientSecret); this.http = new StubHttpClient(); client.HttpClient = http; }
public async void GetContent_given_nonexistant_url_returns_null() { var testUrl = "example.deviantart.com/testtesttest"; var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri($"http://backend.deviantart.com/oembed?url={testUrl}"), HttpStatusCode.NotFound, new object()); var source = new DeviantartImageSource(StubHttpClient.Create(handler)); var result = await source.GetContent(testUrl); Assert.Null(result); }
public async Task setup_scenario() { var httpClient = new StubHttpClient <string> { Response = "Hey!" }; var testSubject = new HttpApiStatusEndpointDependency(httpClient, new HttpApiConfiguration { Name = "downstreamApiName" }); _result = await testSubject.GetStatusAsync(CancellationToken.None); }
public void SetUp() { this.client = new CronofyOAuthClient(clientId, clientSecret); this.http = new StubHttpClient(); client.HttpClient = http; this.upsertEventRequest = new SmartInviteEventRequestBuilder() .Summary(summary) .Start(start) .End(end) .Build(); }
protected AsyncClientFixture() { HttpClient = new StubHttpClient(); JsonNetSerializer = new JsonNetSerializer(); AsyncClient = new AsyncClient(HttpClient, JsonNetSerializer) { OnBeforeSend = request => { if (request.Content != null) RequestContent = request.Content.ReadAsStringAsync().Result; } }; }
public async Task setup_scenario() { var httpClient = new StubHttpClient <Status> { BaseAddress = new Uri("http://stubbaseaddress"), StatusCode = HttpStatusCode.InternalServerError }; var testSubject = new HttpApiStatusEndpointDependency(httpClient, new HttpApiConfiguration { Name = "dependencyName" }); _result = await testSubject.GetStatusAsync(CancellationToken.None); }
public async Task setup_scenario() { var httpClient = new StubHttpClient <Status> { BaseAddress = new Uri("http://stubbaseaddress"), Latency = TimeSpan.FromSeconds(3) }; var testSubject = new HttpApiStatusEndpointDependency(httpClient, new HttpApiConfiguration { Name = "expectedDependencyName" }); _result = await testSubject.GetStatusAsync(new CancellationTokenSource(20).Token); }
public async Task setup_scenario() { _baseHttpClient = new StubHttpClient(new HttpResponseMessage()); _state = new StubCircuitBreakerState { ShouldAcceptResponse = false }; var stateCache = new StubCircuitBreakerManager { State = _state }; var configuration = new CircuitBreakingConfiguration(); var httpClient = _baseHttpClient.AddCircuitBreaking(configuration, stateCache); _response = await httpClient.GetAsync("/ping"); }
public AddToCalendar() { this.client = new CronofyOAuthClient(clientId, clientSecret); this.http = new StubHttpClient(); client.HttpClient = http; this.upsertEventRequest = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Start(start) .End(end) .Build(); }
public async Task setup_scenario() { var httpClient = new StubHttpClient <Status> { BaseAddress = new Uri("http://stubbaseaddress"), Exception = new HttpClientTimeoutException(HttpMethod.Get, new Uri("http://stubbaseaddress/.status")) }; var testSubject = new HttpApiStatusEndpointDependency(httpClient, new HttpApiConfiguration { Name = "expectedDependencyName" }); _result = await testSubject.GetStatusAsync(CancellationToken.None); }
public async Task setup_scenario() { _expectedResponse = new HttpResponseMessage(HttpStatusCode.OK); _baseHttpClient = new StubHttpClient(_expectedResponse); _state = new StubCircuitBreakerState { ShouldAcceptResponse = true }; var stateCache = new StubCircuitBreakerManager { State = _state }; var configuration = new CircuitBreakingConfiguration(); var httpClient = _baseHttpClient.AddCircuitBreaking(configuration, stateCache); _actualResponse = await httpClient.GetAsync("/ping"); }
public async Task setup_scenario() { var throttleManager = new StubThrottleManager { Sync = new StubThrottleSync(ConcurrentRequests) }; _expectedResponse = new HttpResponseMessage(HttpStatusCode.Accepted); var baseHttpClient = new StubHttpClient(_expectedResponse); var configuration = new ThrottlingConfiguration { ThrottlePolicy = "default" }; var httpClient = baseHttpClient.AddThrottling(configuration, throttleManager); _actualResponse = await httpClient.GetAsync("/ping"); }
public async void GetContent_when_connection_forbidden_returns_response_with_statuscode() { var response = new ImgurRatelimitResponse(); var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri("https://api.imgur.com/3/credits"), HttpStatusCode.Forbidden, new ApiHelper <ImgurRatelimitResponse> { Data = response }); var source = new ImgurRatelimitSource(StubHttpClient.Create(handler)); var result = await source.GetContent(); Assert.NotNull(result); Assert.Equal(HttpStatusCode.Forbidden, result.StatusCode); }
public async Task setup_scenario() { var baseHttpClient = new StubHttpClient(new Exception()); var configuration = new InstrumentingConfiguration { Uri = new Uri("http://localhost") }; var httpClient = baseHttpClient.AddInstrumenting(configuration, new[] { _callback }); try { await httpClient.GetAsync("/ping"); } catch { // Ignore the exception } }
public async Task Send_Returns_Empty_Response_For_Empty_Request_For_Response_SendPMode() { // Arrange IStep sut = CreateSendStepWithResponse( StubHttpClient.ThatReturns(HttpStatusCode.Accepted)); MessagingContext ctx = CreateMessagingContextWithDefaultPullRequest(); ctx.SendingPMode = CreateSendPModeWithPushUrl(); // Act StepResult actualResult = await sut.ExecuteAsync(ctx); // Assert Assert.True(actualResult.MessagingContext.AS4Message.IsEmpty); Assert.False(actualResult.CanProceed); }
public async Task Send_Results_In_Stop_Execution_If_Response_Is_PullRequest_Warning_For_Exsisting_SendPMode() { // Arrange AS4Message as4Message = AS4Message.Create(Error.CreatePullRequestWarning($"error-{Guid.NewGuid()}")); IStep sut = CreateSendStepWithResponse( StubHttpClient.ThatReturns(as4Message)); MessagingContext ctx = CreateMessagingContextWithDefaultPullRequest(); ctx.SendingPMode = CreateSendPModeWithPushUrl(); // Act StepResult actualResult = await sut.ExecuteAsync(ctx); // Assert Assert.False(actualResult.CanProceed); }
public async Task setup_scenario() { _exceptionThrown = new Exception(); var baseHttpClient = new StubHttpClient(_exceptionThrown); var configuration = new InstrumentingConfiguration { Uri = new Uri("http://exception-host") }; var httpClient = baseHttpClient.AddInstrumenting(configuration, new [] { _callback }); try { await httpClient.GetAsync("/ping"); } catch (Exception e) { _exception = e; } }
public async void GetContent_given_valid_url_of_invalid_imageformat_returns_null() { var testUrl = "example.deviantart.com/testtesttest.ini"; var output = new DeviantartImage { Author_name = "example", Height = 5, Width = 10, Title = "test", Url = testUrl }; var handler = StubHttpClient.GetHandler(); handler.AddResponse(new Uri($"http://backend.deviantart.com/oembed?url={testUrl}"), HttpStatusCode.OK, output); var source = new DeviantartImageSource(StubHttpClient.Create(handler)); source.Settings = CreateSettings(); var result = await source.GetContent(testUrl); Assert.Null(result); }
public void CanFetchSubscriptionList() { var httpClient = new StubHttpClient() { ExpectedUrl = endpointUrls.SubscriptionList, ExpectedResponse = @"{ ""subscriptions"": [ { ""id"": ""feed/http://feeds.feedburner.com/ajaxian"", ""title"": ""Ajaxian » Front Page"" } ] }", }; var reader = new ReaderAccount(httpClient, endpointUrls); Assert.AreEqual("feed/http://feeds.feedburner.com/ajaxian", reader.Subscriptions.ElementAt(0).Id); Assert.AreEqual("Ajaxian » Front Page", reader.Subscriptions.ElementAt(0).Title); }