public async Task NegotiateThatReturnsUrlGetFollowed() { var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); var firstNegotiate = true; testHttpHandler.OnNegotiate((request, cancellationToken) => { if (firstNegotiate) { firstNegotiate = false; return(ResponseUtils.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(new { url = "https://another.domain.url/chat" }))); } return(ResponseUtils.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(new { connectionId = "0rge0d00-0040-0030-0r00-000q00r00e00", availableTransports = new object[] { new { transport = "LongPolling", transferFormats = new[] { "Text" } }, } }))); }); testHttpHandler.OnLongPoll((token) => { var tcs = new TaskCompletionSource <HttpResponseMessage>(TaskCreationOptions.RunContinuationsAsynchronously); token.Register(() => tcs.TrySetResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent))); return(tcs.Task); }); testHttpHandler.OnLongPollDelete((token) => ResponseUtils.CreateResponse(HttpStatusCode.Accepted)); using (var noErrorScope = new VerifyNoErrorsScope()) { await WithConnectionAsync( CreateConnection(testHttpHandler, loggerFactory : noErrorScope.LoggerFactory), async (connection) => { await connection.StartAsync().DefaultTimeout(); }); } Assert.Equal("http://fakeuri.org/negotiate?negotiateVersion=1", testHttpHandler.ReceivedRequests[0].RequestUri.ToString()); Assert.Equal("https://another.domain.url/chat/negotiate?negotiateVersion=1", testHttpHandler.ReceivedRequests[1].RequestUri.ToString()); Assert.Equal("https://another.domain.url/chat?id=0rge0d00-0040-0030-0r00-000q00r00e00", testHttpHandler.ReceivedRequests[2].RequestUri.ToString()); Assert.Equal("https://another.domain.url/chat?id=0rge0d00-0040-0030-0r00-000q00r00e00", testHttpHandler.ReceivedRequests[3].RequestUri.ToString()); Assert.Equal(5, testHttpHandler.ReceivedRequests.Count); }
public void Setup() { this.testHttpMessageHandler = new TestHttpMessageHandler(); this.httpClient = new HttpClient(this.testHttpMessageHandler, /* disposeHandler */ true); this.httpProvider = new HttpProvider(this.serializer.Object); this.httpProvider.httpClient.Dispose(); this.httpProvider.httpClient = this.httpClient; }
public void SetUp() { _httpHandler = new TestHttpMessageHandler(); _cloudSearchClient = new CloudSearchClient(new CloudSearchSettings { Endpoint = "cloudsearch.example.com", HttpClientFactory = new TestHttpClientFactory(_httpHandler) }); }
public static IUnleash CreateUnleash(TestDefinition testDefinition, UnleashContextDefinition contextDefinition) { var fakeHttpClientFactory = A.Fake <IHttpClientFactory>(); var fakeHttpMessageHandler = new TestHttpMessageHandler(); var httpClient = new HttpClient(fakeHttpMessageHandler) { BaseAddress = new Uri("http://localhost") }; var fakeScheduler = A.Fake <IUnleashScheduledTaskManager>(); var fakeFileSystem = new MockFileSystem(); A.CallTo(() => fakeHttpClientFactory.Create(A <Uri> ._)).Returns(httpClient); A.CallTo(() => fakeScheduler.Configure(A <IEnumerable <IUnleashScheduledTask> > ._, A <CancellationToken> ._)).Invokes(action => { var task = ((IEnumerable <IUnleashScheduledTask>)action.Arguments[0]).First(); task.ExecuteAsync((CancellationToken)action.Arguments[1]).Wait(); }); fakeHttpMessageHandler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(testDefinition.State.ToString(), Encoding.UTF8, "application/json"), Headers = { ETag = new EntityTagHeaderValue("\"123\"") } }; var contextBuilder = new UnleashContext.Builder() .UserId(contextDefinition.UserId) .SessionId(contextDefinition.SessionId) .RemoteAddress(contextDefinition.RemoteAddress) .Environment(contextDefinition.Environment) .AppName(contextDefinition.AppName); if (contextDefinition.Properties != null) { foreach (var property in contextDefinition.Properties) { contextBuilder.AddProperty(property.Key, property.Value); } } var settings = new UnleashSettings { AppName = testDefinition.Name, UnleashContextProvider = new DefaultUnleashContextProvider(contextBuilder.Build()), HttpClientFactory = fakeHttpClientFactory, ScheduledTaskManager = fakeScheduler, FileSystem = fakeFileSystem }; var unleash = new DefaultUnleash(settings); return(unleash); }
public static HttpClient SetupHttpClientWithJsonResponse <TResponseContent>(HttpResponseContent <TResponseContent> response) { var messageHandler = new TestHttpMessageHandler(_ => Task.FromResult(new HttpResponseMessage(response.StatusCode) { Content = new StringContent(JsonConvert.SerializeObject(response.Content), Encoding.UTF8, "application/json") })); return(new HttpClient(messageHandler)); }
public HttpProviderTests() { this.testHttpMessageHandler = new TestHttpMessageHandler(); this.authProvider = new MockAuthenticationProvider(); var defaultHandlers = GraphClientFactory.CreateDefaultHandlers(authProvider.Object); var pipeline = GraphClientFactory.CreatePipeline(defaultHandlers, this.testHttpMessageHandler); this.httpProvider = new HttpProvider(pipeline, true, this.serializer.Object); }
public async Task OAuth2Client_E2E_DeviceFlowAndRefresh() { const string expectedUserCode = "736998"; const string expectedDeviceCode = "db6558b2a1d649758394ac3c2d9e00b1"; const string expectedAccessToken1 = "LET_ME_IN-1"; const string expectedAccessToken2 = "LET_ME_IN-2"; const string expectedRefreshToken1 = "REFRESH_ME-1"; const string expectedRefreshToken2 = "REFRESH_ME-2"; var baseUri = new Uri("https://example.com"); OAuth2ServerEndpoints endpoints = CreateEndpoints(baseUri); var httpHandler = new TestHttpMessageHandler { ThrowOnUnexpectedRequest = true }; string[] expectedScopes = { "read", "write", "delete" }; OAuth2Application app = CreateTestApplication(); var server = new TestOAuth2Server(endpoints); server.RegisterApplication(app); server.Bind(httpHandler); server.TokenGenerator.UserCodes.Add(expectedUserCode); server.TokenGenerator.DeviceCodes.Add(expectedDeviceCode); server.TokenGenerator.AccessTokens.Add(expectedAccessToken1); server.TokenGenerator.RefreshTokens.Add(expectedRefreshToken1); OAuth2Client client = CreateClient(httpHandler, endpoints); OAuth2DeviceCodeResult deviceResult = await client.GetDeviceCodeAsync(expectedScopes, CancellationToken.None); // Simulate the user taking some time to sign in with the user code Thread.Sleep(1000); server.SignInDeviceWithUserCode(deviceResult.UserCode); OAuth2TokenResult result1 = await client.GetTokenByDeviceCodeAsync(deviceResult, CancellationToken.None); Assert.NotNull(result1); Assert.Equal(expectedScopes, result1.Scopes); Assert.Equal(expectedAccessToken1, result1.AccessToken); Assert.Equal(expectedRefreshToken1, result1.RefreshToken); server.TokenGenerator.AccessTokens.Add(expectedAccessToken2); server.TokenGenerator.RefreshTokens.Add(expectedRefreshToken2); OAuth2TokenResult result2 = await client.GetTokenByRefreshTokenAsync(result1.RefreshToken, CancellationToken.None); Assert.NotNull(result2); Assert.Equal(expectedScopes, result2.Scopes); Assert.Equal(expectedAccessToken2, result2.AccessToken); Assert.Equal(expectedRefreshToken2, result2.RefreshToken); }
public BaseRequestExtensionsTests() { defaultAuthProvider = new MockAuthenticationProvider(defaultAuthHeader); testHttpMessageHandler = new TestHttpMessageHandler(); var defaultHandlers = GraphClientFactory.CreateDefaultHandlers(defaultAuthProvider.Object); var pipeline = GraphClientFactory.CreatePipeline(defaultHandlers, this.testHttpMessageHandler); httpProvider = new HttpProvider(pipeline, true, serializer.Object); baseClient = new BaseClient("https://localhost/v1.0", defaultAuthProvider.Object, httpProvider); }
public SimpleHttpProviderTests() { this.testHttpMessageHandler = new TestHttpMessageHandler(); this.authProvider = new MockAuthenticationProvider(); this.serializer = new MockSerializer(); var defaultHandlers = GraphClientFactory.CreateDefaultHandlers(authProvider.Object); var httpClient = GraphClientFactory.Create(handlers: defaultHandlers, finalHandler: testHttpMessageHandler); this.simpleHttpProvider = new SimpleHttpProvider(httpClient, this.serializer.Object); }
private async Task MakeRequestAsync(string resourcePath, HttpMethod httpMethod, object requestData = null, IDictionary <string, string> headers = null, bool rawResponse = false) { var handler = new TestHttpMessageHandler(); var manager = new HttpDataAccessManager(DummyUri, handler); await manager.MakeRequestAsync <dynamic>(resourcePath, httpMethod, requestData, headers, rawResponse); Assert.Equal(handler.RequestMessage.Method, httpMethod); Assert.Equal(handler.RequestMessage.Headers.Count(), headers != null ? headers.Count : 0); Assert.Equal(handler.RequestMessage.RequestUri.AbsoluteUri, DummyUri.AbsoluteUri.TrimEnd('/') + "/" + resourcePath); }
private async Task MakeRequestAsync(string resourcePath, HttpMethod httpMethod, object requestData = null, IDictionary<string, string> headers = null, bool rawResponse = false) { var handler = new TestHttpMessageHandler(); var manager = new HttpDataAccessManager(DummyUri, handler); await manager.MakeRequestAsync<dynamic>(resourcePath, httpMethod, requestData, headers, rawResponse); Assert.Equal(handler.RequestMessage.Method, httpMethod); Assert.Equal(handler.RequestMessage.Headers.Count(), headers != null ? headers.Count : 0); Assert.Equal(handler.RequestMessage.RequestUri.AbsoluteUri, DummyUri.AbsoluteUri.TrimEnd('/') + "/" + resourcePath); }
public void Setup() { this.serializer = new MockSerializer(); this.httpResponseMessage = new HttpResponseMessage(); this.testHttpMessageHandler = new TestHttpMessageHandler(); //this.httpProvider = new HttpProvider(authenticationProvider.Object, this.testHttpMessageHandler, true, this.serializer.Object); this.httpProvider = new MockHttpProvider(this.httpResponseMessage, this.serializer.Object); this.baseClient = new BaseClient( this.baseUrl, this.authenticationProvider.Object, this.httpProvider.Object); }
public async Task OAuth2Client_E2E_InteractiveWebFlowAndRefresh() { const string expectedAuthCode = "e78a711d11"; const string expectedAccessToken1 = "LET_ME_IN-1"; const string expectedAccessToken2 = "LET_ME_IN-2"; const string expectedRefreshToken1 = "REFRESH_ME-1"; const string expectedRefreshToken2 = "REFRESH_ME-2"; var baseUri = new Uri("https://example.com"); OAuth2ServerEndpoints endpoints = CreateEndpoints(baseUri); var httpHandler = new TestHttpMessageHandler { ThrowOnUnexpectedRequest = true }; string[] expectedScopes = { "read", "write", "delete" }; OAuth2Application app = CreateTestApplication(); var server = new TestOAuth2Server(endpoints); server.RegisterApplication(app); server.Bind(httpHandler); server.TokenGenerator.AuthCodes.Add(expectedAuthCode); server.TokenGenerator.AccessTokens.Add(expectedAccessToken1); server.TokenGenerator.RefreshTokens.Add(expectedRefreshToken1); IOAuth2WebBrowser browser = new TestOAuth2WebBrowser(httpHandler); OAuth2Client client = CreateClient(httpHandler, endpoints); OAuth2AuthorizationCodeResult authCodeResult = await client.GetAuthorizationCodeAsync( expectedScopes, browser, CancellationToken.None); OAuth2TokenResult result1 = await client.GetTokenByAuthorizationCodeAsync(authCodeResult, CancellationToken.None); Assert.NotNull(result1); Assert.Equal(expectedScopes, result1.Scopes); Assert.Equal(expectedAccessToken1, result1.AccessToken); Assert.Equal(expectedRefreshToken1, result1.RefreshToken); server.TokenGenerator.AccessTokens.Add(expectedAccessToken2); server.TokenGenerator.RefreshTokens.Add(expectedRefreshToken2); OAuth2TokenResult result2 = await client.GetTokenByRefreshTokenAsync(result1.RefreshToken, CancellationToken.None); Assert.NotNull(result2); Assert.Equal(expectedScopes, result2.Scopes); Assert.Equal(expectedAccessToken2, result2.AccessToken); Assert.Equal(expectedRefreshToken2, result2.RefreshToken); }
public void Setup() { HttpHandler = new TestHttpMessageHandler(); HttpHandler.FakeResponse = new HttpResponseMessage(System.Net.HttpStatusCode.OK); HttpHandler.FakeResponse.Content = new StringContent("{ 'something': 'good' }"); var httpClient = new HttpClient(HttpHandler) { BaseAddress = new Uri("http://localhost/someuri/") }; Subject = new ApiClient(httpClient); }
public async Task AzureDevOpsRestApi_GetAuthorityAsync_NoNetwork_ThrowsException() { var context = new TestCommandContext(); var uri = new Uri("https://example.com"); var httpHandler = new TestHttpMessageHandler { SimulateNoNetwork = true }; context.HttpClientFactory.MessageHandler = httpHandler; var api = new AzureDevOpsRestApi(context); await Assert.ThrowsAsync <HttpRequestException>(() => api.GetAuthorityAsync(uri)); }
public async Task OAuth2Client_GetTokenByDeviceCodeAsync() { const string expectedUserCode = "342728"; const string expectedDeviceCode = "ad6498533bf54f4db53e49612a4acfb0"; const string expectedAccessToken = "LET_ME_IN"; const string expectedRefreshToken = "REFRESH_ME"; var baseUri = new Uri("https://example.com"); OAuth2ServerEndpoints endpoints = CreateEndpoints(baseUri); var httpHandler = new TestHttpMessageHandler { ThrowOnUnexpectedRequest = true }; string[] expectedScopes = { "read", "write", "delete" }; var grant = new OAuth2Application.DeviceCodeGrant(expectedUserCode, expectedDeviceCode, expectedScopes); OAuth2Application app = CreateTestApplication(); app.DeviceGrants.Add(grant); var server = new TestOAuth2Server(endpoints); server.RegisterApplication(app); server.Bind(httpHandler); server.TokenGenerator.UserCodes.Add(expectedUserCode); server.TokenGenerator.DeviceCodes.Add(expectedDeviceCode); server.TokenGenerator.AccessTokens.Add(expectedAccessToken); server.TokenGenerator.RefreshTokens.Add(expectedRefreshToken); OAuth2Client client = CreateClient(httpHandler, endpoints); var deviceCodeResult = new OAuth2DeviceCodeResult(expectedDeviceCode, expectedUserCode, null, null); Task <OAuth2TokenResult> resultTask = client.GetTokenByDeviceCodeAsync(deviceCodeResult, CancellationToken.None); // Simulate the user taking some time to sign in with the user code Thread.Sleep(1000); server.SignInDeviceWithUserCode(expectedUserCode); OAuth2TokenResult result = await resultTask; Assert.NotNull(result); Assert.Equal(expectedScopes, result.Scopes); Assert.Equal(expectedAccessToken, result.AccessToken); Assert.Equal(expectedRefreshToken, result.RefreshToken); }
private async Task RunInvalidNegotiateResponseTest <TException>(string negotiatePayload, string expectedExceptionMessage) where TException : Exception { var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); testHttpHandler.OnNegotiate((_, cancellationToken) => ResponseUtils.CreateResponse(HttpStatusCode.OK, negotiatePayload)); await WithConnectionAsync( CreateConnection(testHttpHandler), async (connection) => { var exception = await Assert.ThrowsAsync <TException>( () => connection.StartAsync().DefaultTimeout()); Assert.Equal(expectedExceptionMessage, exception.Message); }); }
public async Task StartSkipsOverTransportsThatTheClientDoesNotUnderstand() { var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); testHttpHandler.OnLongPoll(cancellationToken => ResponseUtils.CreateResponse(HttpStatusCode.NoContent)); testHttpHandler.OnNegotiate((request, cancellationToken) => { return(ResponseUtils.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(new { connectionId = "00000000-0000-0000-0000-000000000000", availableTransports = new object[] { new { transport = "QuantumEntanglement", transferFormats = new[] { "Qbits" }, }, new { transport = "CarrierPigeon", transferFormats = new[] { "Text" }, }, new { transport = "LongPolling", transferFormats = new[] { "Text", "Binary" } }, } }))); }); var transportFactory = new Mock <ITransportFactory>(MockBehavior.Strict); transportFactory.Setup(t => t.CreateTransport(HttpTransportType.LongPolling)) .Returns(new TestTransport(transferFormat: TransferFormat.Text | TransferFormat.Binary)); using (var noErrorScope = new VerifyNoErrorsScope()) { await WithConnectionAsync( CreateConnection(testHttpHandler, transportFactory : transportFactory.Object, loggerFactory : noErrorScope.LoggerFactory, transferFormat : TransferFormat.Binary), async (connection) => { await connection.StartAsync().DefaultTimeout(); }); } }
public async Task HttpOptionsSetOntoHttpClientHandler() { var testHttpHandler = TestHttpMessageHandler.CreateDefault(); var negotiateUrlTcs = new TaskCompletionSource <string>(); testHttpHandler.OnNegotiate((request, cancellationToken) => { negotiateUrlTcs.TrySetResult(request.RequestUri.ToString()); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, ResponseUtils.CreateNegotiationContent())); }); HttpClientHandler httpClientHandler = null; var httpOptions = new HttpConnectionOptions(); httpOptions.Url = new Uri("http://fakeuri.org/"); httpOptions.HttpMessageHandlerFactory = inner => { httpClientHandler = (HttpClientHandler)inner; return(testHttpHandler); }; httpOptions.Cookies.Add(new Cookie("Name", "Value", string.Empty, "fakeuri.org")); var clientCertificate = new X509Certificate(Array.Empty <byte>()); httpOptions.ClientCertificates.Add(clientCertificate); httpOptions.UseDefaultCredentials = false; httpOptions.Credentials = Mock.Of <ICredentials>(); httpOptions.Proxy = Mock.Of <IWebProxy>(); httpOptions.Transports = HttpTransportType.LongPolling; await WithConnectionAsync( CreateConnection(httpOptions), async (connection) => { await connection.StartAsync().DefaultTimeout(); }); Assert.NotNull(httpClientHandler); Assert.Equal(1, httpClientHandler.CookieContainer.Count); Assert.Single(httpClientHandler.ClientCertificates); Assert.Same(clientCertificate, httpClientHandler.ClientCertificates[0]); Assert.False(httpClientHandler.UseDefaultCredentials); Assert.Same(httpOptions.Proxy, httpClientHandler.Proxy); Assert.Same(httpOptions.Credentials, httpClientHandler.Credentials); }
public async Task HttpConnectionSetsAccessTokenOnAllRequests(HttpTransportType transportType) { var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); var requestsExecuted = false; var callCount = 0; testHttpHandler.OnNegotiate((_, cancellationToken) => { return(ResponseUtils.CreateResponse(HttpStatusCode.OK, ResponseUtils.CreateNegotiationContent())); }); testHttpHandler.OnRequest(async(request, next, token) => { Assert.Equal("Bearer", request.Headers.Authorization.Scheme); // Call count increments with each call and is used as the access token Assert.Equal(callCount.ToString(CultureInfo.InvariantCulture), request.Headers.Authorization.Parameter); requestsExecuted = true; return(await next()); }); testHttpHandler.OnRequest((request, next, token) => { return(Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent))); }); Task <string> AccessTokenProvider() { callCount++; return(Task.FromResult(callCount.ToString(CultureInfo.InvariantCulture))); } await WithConnectionAsync( CreateConnection(testHttpHandler, transportType : transportType, accessTokenProvider : AccessTokenProvider), async (connection) => { await connection.StartAsync().DefaultTimeout(); await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello world 1")); await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello world 2")); }); // Fail safe in case the code is modified and some requests don't execute as a result Assert.True(requestsExecuted); Assert.Equal(1, callCount); }
public void Dispose_CalledWhenHttpMessageHandlerSpecifiedAndHttpClientDisposedTrue_HttpClientDisposed() { // Arrange var handler = new TestHttpMessageHandler(); var channel = GrpcChannel.ForAddress("https://localhost", new GrpcChannelOptions { HttpHandler = handler, DisposeHttpClient = true }); // Act channel.Dispose(); // Assert Assert.IsTrue(channel.Disposed); Assert.IsTrue(handler.Disposed); }
public async Task ShouldLogApiCall() { var logger = new TestLogger(); var innerHandler = new TestHttpMessageHandler(new byte[] { }); var loggingDelegatingHandler = new LoggingDelegatingHandler(logger, innerHandler); var httpClient = new HttpClient(loggingDelegatingHandler); await httpClient.PostAsync("https://foo.bar", new StringContent("Test")); Assert.AreEqual(new Uri("https://foo.bar/"), logger.LogApiCallUri); var content = await logger.LogApiCallHttpContent.ReadAsStringAsync(); Assert.AreEqual("Test", content); }
public void Dispose_CalledWhenHttpClientSpecified_HttpClientNotDisposed() { // Arrange var handler = new TestHttpMessageHandler(); var httpClient = new HttpClient(handler); var channel = GrpcChannel.ForAddress("https://localhost", new GrpcChannelOptions { HttpClient = httpClient }); // Act channel.Dispose(); // Assert Assert.IsTrue(channel.Disposed); Assert.IsFalse(handler.Disposed); }
public async Task HttpConnectionSetsUserAgentOnAllRequests(HttpTransportType transportType) { var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); var requestsExecuted = false; testHttpHandler.OnNegotiate((_, cancellationToken) => { return(ResponseUtils.CreateResponse(HttpStatusCode.OK, ResponseUtils.CreateNegotiationContent())); }); testHttpHandler.OnRequest(async(request, next, token) => { var userAgentHeader = request.Headers.UserAgent.ToString(); Assert.NotNull(userAgentHeader); Assert.StartsWith("Microsoft SignalR/", userAgentHeader); // user agent version should come from version embedded in assembly metadata var assemblyVersion = typeof(Constants) .Assembly .GetCustomAttribute <AssemblyInformationalVersionAttribute>(); Assert.Contains(assemblyVersion.InformationalVersion, userAgentHeader); requestsExecuted = true; return(await next()); }); testHttpHandler.OnRequest((request, next, token) => { return(Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent))); }); await WithConnectionAsync( CreateConnection(testHttpHandler, transportType : transportType), async (connection) => { await connection.StartAsync().DefaultTimeout(); await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello World")); }); // Fail safe in case the code is modified and some requests don't execute as a result Assert.True(requestsExecuted); }
public async Task CheckHealthAsync_Unhealthy_ThrowsException() { var check = new HttpCheck(); var httpSettings = new HttpRequestSettings() { HttpMethod = HttpMethod.Get, Uri = new Uri("http://localhost") }; var settings = new HttpCheckSettings("http", false, 0, null, httpSettings); var context = new HealthCheckContext(settings); var httpHandler = new TestHttpMessageHandler(); httpHandler.Sender = r => throw new HttpRequestException(); settings.HttpHandler = httpHandler; await Assert.ThrowsAsync <HttpRequestException>(async() => await check.CheckHealthAsync(context, settings)); }
public async Task SendsDeleteRequestWhenTransportCompleted() { var handler = TestHttpMessageHandler.CreateDefault(); using (var httpClient = new HttpClient(handler)) { var longPollingTransport = new LongPollingTransport(httpClient); await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); await longPollingTransport.StopAsync(); var deleteRequest = handler.ReceivedRequests.SingleOrDefault(r => r.Method == HttpMethod.Delete); Assert.NotNull(deleteRequest); Assert.Equal(TestUri, deleteRequest.RequestUri); } }
public async Task BitbucketRestApi_GetUserInformationAsync_ReturnsUserInfo_ForSuccessfulRequest(string username, string password, bool isBearerToken) { var twoFactorAuthenticationEnabled = false; var uuid = Guid.NewGuid(); var accountId = "1234"; var context = new TestCommandContext(); var expectedRequestUri = new Uri("https://api.bitbucket.org/2.0/user"); var userinfoResponseJson = $"{{ \"username\": \"{username}\" , \"has_2fa_enabled\": \"{twoFactorAuthenticationEnabled}\", \"account_id\": \"{accountId}\", \"uuid\": \"{uuid}\"}}"; var httpResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(userinfoResponseJson) }; var httpHandler = new TestHttpMessageHandler(); httpHandler.Setup(HttpMethod.Get, expectedRequestUri, request => { if (isBearerToken) { RestTestUtilities.AssertBearerAuth(request, password); } else { RestTestUtilities.AssertBasicAuth(request, username, password); } return(httpResponse); }); context.HttpClientFactory.MessageHandler = httpHandler; var api = new BitbucketRestApi(context); var result = await api.GetUserInformationAsync(username, password, isBearerToken); Assert.NotNull(result); Assert.Equal(username, result.Response.UserName); Assert.Equal(accountId, result.Response.AccountId); Assert.Equal(uuid, result.Response.Uuid); Assert.Equal(twoFactorAuthenticationEnabled, result.Response.IsTwoFactorAuthenticationEnabled); httpHandler.AssertRequest(HttpMethod.Get, expectedRequestUri, 1); }
public void CallingGet() { // Arrange var responseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Response from API") }; var responseHandler = new TestHttpMessageHandler(responseMessage); var httpClient = new HttpClient(responseHandler); var httpClientWrapper = new HttpClientWrapper(httpClient); //Act var result = httpClientWrapper.Get("http://localhost/testAddress"); // Assert Assert.That(result, Is.EqualTo(responseMessage.Content.ReadAsStringAsync().Result)); }
private static IHostBuilder CreateHostBuilder(TestHttpMessageHandler handler) { return(Host.CreateDefaultBuilder() .ConfigureServices((hostContext, services) => { services .AddAuditTrailClient(o => { o.DeliveryEndpoint = "https://example.com/events/"; o.TemporaryStorageEncryptionKey = SymmetricJwk.FromByteArray(new byte[32]); }) .ConfigurePrimaryHttpMessageHandler(() => handler) .ConfigureHttpClient(builder => { }); services.Replace(new ServiceDescriptor(typeof(IAccessTokenAcquirer), typeof(NullTokenAcquirer), ServiceLifetime.Singleton)); })); }
public async Task CanCancelStartingConnectionAfterNegotiate() { using (StartVerifiableLog()) { // Set up a SyncPoint within Negotiate, so we can verify // that the call has gotten that far var negotiateSyncPoint = new SyncPoint(); var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); testHttpHandler.OnNegotiate(async(request, cancellationToken) => { // Wait here for the test code to cancel the "outer" token await negotiateSyncPoint.WaitToContinue().DefaultTimeout(); // Cancel cancellationToken.ThrowIfCancellationRequested(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); await WithConnectionAsync( CreateConnection(testHttpHandler), async (connection) => { // Kick off StartAsync, but don't wait for it var cts = new CancellationTokenSource(); var startTask = connection.StartAsync(cts.Token); // Wait for the connection to get to the "WaitToContinue" call above, // which means it has gotten to Negotiate await negotiateSyncPoint.WaitForSyncPoint().DefaultTimeout(); // Assert that StartAsync has not yet been canceled Assert.False(startTask.IsCanceled); // Cancel StartAsync, then "release" the SyncPoint // so the negotiate handler can keep going cts.Cancel(); negotiateSyncPoint.Continue(); // Assert that StartAsync was canceled await Assert.ThrowsAsync <TaskCanceledException>(() => startTask).DefaultTimeout(); }); } }
public async Task StartSkipsOverTransportsThatDoNotSupportTheRequredTransferFormat() { var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false); testHttpHandler.OnLongPoll(cancellationToken => ResponseUtils.CreateResponse(HttpStatusCode.NoContent)); testHttpHandler.OnNegotiate((request, cancellationToken) => { return(ResponseUtils.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(new { connectionId = "00000000-0000-0000-0000-000000000000", availableTransports = new object[] { new { transport = "WebSockets", transferFormats = new[] { "Qbits" }, }, new { transport = "ServerSentEvents", transferFormats = new[] { "Text" }, }, new { transport = "LongPolling", transferFormats = new[] { "Text", "Binary" } }, } }))); }); var transportFactory = new Mock <ITransportFactory>(MockBehavior.Strict); transportFactory.Setup(t => t.CreateTransport(HttpTransportType.LongPolling)) .Returns(new TestTransport(transferFormat: TransferFormat.Text | TransferFormat.Binary)); await WithConnectionAsync( CreateConnection(testHttpHandler, transportFactory : transportFactory.Object, transferFormat : TransferFormat.Binary), async (connection) => { await connection.StartAsync().DefaultTimeout(); }); }
public async Task CachingFunctionShouldPreserveHeaders() { var innerHandler = new TestHttpMessageHandler(_ => { var ret = new HttpResponseMessage() { Content = new StringContent("foo", Encoding.UTF8), StatusCode = HttpStatusCode.OK, }; ret.Headers.ETag = new EntityTagHeaderValue("\"worifjw\""); return Observable.Return(ret); }); var etagResponses = new List<string>(); var fixture = new RateLimitedHttpMessageHandler(innerHandler, Priority.UserInitiated, cacheResultFunc: (rq, re, key, ct) => { etagResponses.Add(re.Headers.ETag.Tag); return Task.FromResult(true); }); var client = new HttpClient(fixture); var resp = await client.GetAsync("http://lol/bar"); Assert.Equal("\"worifjw\"", etagResponses[0]); }
public async Task CachingFunctionShouldBeCalledWithContent() { var innerHandler = new TestHttpMessageHandler(_ => { var ret = new HttpResponseMessage() { Content = new StringContent("foo", Encoding.UTF8), StatusCode = HttpStatusCode.OK, }; ret.Headers.ETag = new EntityTagHeaderValue("\"worifjw\""); return Observable.Return(ret); }); var contentResponses = new List<byte[]>(); var fixture = new RateLimitedHttpMessageHandler(innerHandler, Priority.UserInitiated, cacheResultFunc: async (rq, re, key, ct) => { contentResponses.Add(await re.Content.ReadAsByteArrayAsync()); }); var client = new HttpClient(fixture); var str = await client.GetStringAsync("http://lol/bar"); Assert.Equal("foo", str); Assert.Equal(1, contentResponses.Count); Assert.Equal(3, contentResponses[0].Length); }
public async Task OnlyCacheRelevantMethods(string method, bool shouldCache) { var innerHandler = new TestHttpMessageHandler(_ => { var ret = new HttpResponseMessage() { Content = new StringContent("foo", Encoding.UTF8), StatusCode = HttpStatusCode.OK, }; return Observable.Return(ret); }); var cached = false; var fixture = new RateLimitedHttpMessageHandler(innerHandler, Priority.UserInitiated, cacheResultFunc: (rq, re, key, ct) => { cached = true; return Task.FromResult(true); }); var client = new HttpClient(fixture); var request = new HttpRequestMessage(new HttpMethod(method), "http://lol/bar"); await client.SendAsync(request); Assert.Equal(shouldCache, cached); }