Example #1
0
        public async Task SendServiceAsync_OnSuccessfulRequest()
        {
            var handler  = new MockDelegatingHandler();
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            handler.Responses.Add(response);

            var options = new DatasyncClientOptions
            {
                HttpPipeline   = new HttpMessageHandler[] { handler },
                InstallationId = "hijack",
                UserAgent      = "hijack"
            };
            var client = new WrappedHttpClient(Endpoint, options);

            var request = new ServiceRequest {
                Method = HttpMethod.Get, UriPathAndQuery = "/tables/movies/", EnsureResponseContent = false
            };
            var actualResponse = await client.WrappedSendAsync(request).ConfigureAwait(false);

            Assert.Equal(200, actualResponse.StatusCode);

            // Check that the right headers were applied to the request
            Assert.Single(handler.Requests);
            var actual = handler.Requests[0];

            Assert.Equal(options.UserAgent, actual.Headers.UserAgent.ToString());
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-VERSION", options.UserAgent);
            AssertEx.HasHeader(actual.Headers, "ZUMO-API-VERSION", "3.0.0");
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-INSTALLATION-ID", options.InstallationId);
        }
Example #2
0
        public async Task SendServiceAsync_OnBadRequest(string content, string expectedMessage)
        {
            var handler  = new MockDelegatingHandler();
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = content == null ? null : new StringContent(content, Encoding.UTF8, "application/json")
            };

            handler.Responses.Add(response);

            var options = new DatasyncClientOptions
            {
                HttpPipeline   = new HttpMessageHandler[] { handler },
                InstallationId = "hijack",
                UserAgent      = "hijack"
            };
            var client  = new WrappedHttpClient(Endpoint, options);
            var request = new ServiceRequest {
                Method = HttpMethod.Get, UriPathAndQuery = "/tables/movies/"
            };
            var exception = await Assert.ThrowsAsync <DatasyncInvalidOperationException>(() => client.WrappedSendAsync(request));

            Assert.Same(response, exception.Response);
            Assert.StartsWith(expectedMessage, exception.Message);

            // Check that the right headers were applied to the request
            Assert.Single(handler.Requests);
            var actual = handler.Requests[0];

            Assert.Equal(options.UserAgent, actual.Headers.UserAgent.ToString());
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-VERSION", options.UserAgent);
            AssertEx.HasHeader(actual.Headers, "ZUMO-API-VERSION", "3.0.0");
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-INSTALLATION-ID", options.InstallationId);
        }
        public void SendAsync_Traces_And_Invokes_Inner()
        {
            // Arrange
            HttpResponseMessage response = new HttpResponseMessage();
            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) =>
                                                 TaskHelpers.FromResult<HttpResponseMessage>(response));

            TestTraceWriter traceWriter = new TestTraceWriter();
            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) =>
                                     TaskHelpers.FromResult<HttpResponseMessage>(response));
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SendAsync" },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "SendAsync" }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Task<HttpResponseMessage> task = method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;
            HttpResponseMessage actualResponse = task.Result;

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(response, actualResponse);
        }
        public void SendAsync_Traces_And_Throws_When_Inner_Throws()
        {
            // Arrange
            InvalidOperationException exception   = new InvalidOperationException("test");
            MockDelegatingHandler     mockHandler = new MockDelegatingHandler(
                (rqst, cancellation) =>
            {
                throw exception;
            }
                );

            TestTraceWriter      traceWriter = new TestTraceWriter();
            MessageHandlerTracer tracer      = new MessageHandlerTracer(mockHandler, traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler(
                (rqst, cancellation) =>
            {
                throw exception;
            }
                );

            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info)
                {
                    Kind      = TraceKind.Begin,
                    Operation = "SendAsync"
                },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error)
                {
                    Kind      = TraceKind.End,
                    Operation = "SendAsync"
                }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod(
                "SendAsync",
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
                );

            // Act
            Exception thrown = Assert.Throws <TargetInvocationException>(
                () => method.Invoke(tracer, new object[] { request, CancellationToken.None })
                );

            // Assert
            Assert.Equal <TraceRecord>(
                expectedTraces,
                traceWriter.Traces,
                new TraceRecordComparer()
                );
            Assert.Same(exception, thrown.InnerException);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
        public void SendAsync_Traces_And_Throws_When_Inner_Throws()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => { throw exception; });

            TestTraceWriter traceWriter = new TestTraceWriter();
            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { throw exception; });
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SendAsync" },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "SendAsync" }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Exception thrown =
                Assert.Throws<TargetInvocationException>(
                    () => method.Invoke(tracer, new object[] { request, CancellationToken.None }));

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown.InnerException);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
        public void DelegatingHandlersAreCloned()
        {
            string userAccount = "*****@*****.**";
            Guid subscriptionId = Guid.NewGuid();
             AzureContext context = new AzureContext
            (
                new AzureSubscription()
                {
                    Account = userAccount,
                    Environment = "AzureCloud",
                    Id = subscriptionId,
                    Properties = new Dictionary<AzureSubscription.Property, string>() { { AzureSubscription.Property.Tenants, "common" } }
                }, 
                new AzureAccount()
                {
                    Id = userAccount,
                    Type = AzureAccount.AccountType.User,
                    Properties = new Dictionary<AzureAccount.Property, string>() { { AzureAccount.Property.Tenants, "common" } }
                },
                AzureEnvironment.PublicEnvironments["AzureCloud"]
            );

            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(userAccount, Guid.NewGuid().ToString());
            var mockHandler = new MockDelegatingHandler();
            var factory = new ClientFactory();
            factory.AddHandler(mockHandler);
            var client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            Assert.Equal(5, MockDelegatingHandler.cloneCount); 
        }
Example #7
0
        public async Task SendHttpAsync_OnSuccessfulRequest_WithAuth()
        {
            var handler = new MockDelegatingHandler();
            var options = new DatasyncClientOptions
            {
                HttpPipeline   = new HttpMessageHandler[] { handler },
                InstallationId = "hijack",
                UserAgent      = "hijack"
            };
            var requestor = () => Task.FromResult(ValidAuthenticationToken);
            var client    = new WrappedHttpClient(Endpoint, new GenericAuthenticationProvider(requestor, "X-ZUMO-AUTH"), options);
            var response  = new HttpResponseMessage(HttpStatusCode.OK);

            handler.Responses.Add(response);
            var request = new HttpRequestMessage(HttpMethod.Get, "");

            var actualResponse = await client.WrappedSendAsync(request).ConfigureAwait(false);

            Assert.Same(response, actualResponse);      // We get the provided response back.

            // Check that the right headers were applied to the request
            Assert.Single(handler.Requests);
            var actual = handler.Requests[0];

            Assert.Equal(options.UserAgent, actual.Headers.UserAgent.ToString());
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-VERSION", options.UserAgent);
            AssertEx.HasHeader(actual.Headers, "ZUMO-API-VERSION", "3.0.0");
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-AUTH", ValidAuthenticationToken.Token);
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-INSTALLATION-ID", options.InstallationId);
        }
Example #8
0
        public void Create1_SetsInnerHandler()
        {
            // Arrange
            MockDelegatingHandler handler = new MockDelegatingHandler();

            // Act
            HttpClient client = HttpClientFactory.Create(handler);

            // Assert
            Assert.IsType <HttpClientHandler>(handler.InnerHandler);
        }
Example #9
0
        public void CreatePipeline_CB_ThrowsArgumentException()
        {
            var b = new MockDelegatingHandler();
            var c = new HttpClientHandler();

            var options = new DatasyncClientOptions {
                HttpPipeline = new HttpMessageHandler[] { c, b }
            };

            // Act
            Assert.Throws <ArgumentException>(() => _ = new WrappedHttpClient(Endpoint, options));
        }
        public async Task SendAsync_Traces_And_Invokes_Inner()
        {
            // Arrange
            HttpResponseMessage   response    = new HttpResponseMessage();
            MockDelegatingHandler mockHandler = new MockDelegatingHandler(
                (rqst, cancellation) => Task.FromResult <HttpResponseMessage>(response)
                );

            TestTraceWriter        traceWriter      = new TestTraceWriter();
            MessageHandlerTracer   tracer           = new MessageHandlerTracer(mockHandler, traceWriter);
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler(
                (rqst, cancellation) => Task.FromResult <HttpResponseMessage>(response)
                );

            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info)
                {
                    Kind      = TraceKind.Begin,
                    Operation = "SendAsync"
                },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info)
                {
                    Kind      = TraceKind.End,
                    Operation = "SendAsync"
                }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod(
                "SendAsync",
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
                );

            // Act
            Task <HttpResponseMessage> task =
                method.Invoke(tracer, new object[] { request, CancellationToken.None })
                as Task <HttpResponseMessage>;
            HttpResponseMessage actualResponse = await task;

            // Assert
            Assert.Equal <TraceRecord>(
                expectedTraces,
                traceWriter.Traces,
                new TraceRecordComparer()
                );
            Assert.Same(response, actualResponse);
        }
Example #11
0
        public void CreatePipeline_CBWithAuth_ThrowsArgumentException()
        {
            var b = new MockDelegatingHandler();
            var c = new HttpClientHandler();

            var options = new DatasyncClientOptions {
                HttpPipeline = new HttpMessageHandler[] { c, b }
            };

            // Act
            var authProvider = new GenericAuthenticationProvider(() => Task.FromResult(ValidAuthenticationToken), "X-ZUMO-AUTH");

            Assert.Throws <ArgumentException>(() => _ = new WrappedHttpClient(Endpoint, authProvider, options));
        }
Example #12
0
        public void CreatePipeline_B_CreatesPipeline()
        {
            var b = new MockDelegatingHandler();

            var options = new DatasyncClientOptions {
                HttpPipeline = new HttpMessageHandler[] { b }
            };

            // Act
            var client = new WrappedHttpClient(Endpoint, options);

            // Assert
            Assert.Same(b, client.HttpHandler);
            Assert.IsAssignableFrom <HttpClientHandler>(b.InnerHandler);
        }
Example #13
0
        public async Task SendAsync_Traces_And_Faults_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception            = new InvalidOperationException("test");
            TaskCompletionSource <HttpResponseMessage> tcs = new TaskCompletionSource <HttpResponseMessage>();

            tcs.TrySetException(exception);
            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => { return(tcs.Task); });

            TestTraceWriter      traceWriter = new TestTraceWriter();
            MessageHandlerTracer tracer      = new MessageHandlerTracer(mockHandler, traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer returns a Task that throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { return(tcs.Task); });

            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "SendAsync"
                },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error)
                {
                    Kind = TraceKind.End, Operation = "SendAsync"
                }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                                    BindingFlags.Instance);

            // Act
            Task <HttpResponseMessage> task =
                method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task <HttpResponseMessage>;

            // Assert
            Exception thrown = await Assert.ThrowsAsync <InvalidOperationException>(() => task);

            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
Example #14
0
        public void CreatePipeline_BWithAuth_CreatesPipeline()
        {
            var b = new MockDelegatingHandler();

            var options = new DatasyncClientOptions {
                HttpPipeline = new HttpMessageHandler[] { b }
            };

            // Act
            var authProvider = new GenericAuthenticationProvider(() => Task.FromResult(ValidAuthenticationToken), "X-ZUMO-AUTH");
            var client       = new WrappedHttpClient(Endpoint, authProvider, options);

            // Assert
            Assert.Same(authProvider, client.HttpHandler);
            Assert.Same(b, authProvider.InnerHandler);
            Assert.IsAssignableFrom <HttpClientHandler>(b.InnerHandler);
        }
Example #15
0
        public void CreatePipeline_ABC_CreatesPipeline()
        {
            var a = new MockDelegatingHandler();
            var b = new MockDelegatingHandler();
            var c = new HttpClientHandler();

            var options = new DatasyncClientOptions {
                HttpPipeline = new HttpMessageHandler[] { a, b, c }
            };

            // Act
            var client = new WrappedHttpClient(Endpoint, options);

            // Assert
            Assert.Same(a, client.HttpHandler);
            Assert.Same(b, a.InnerHandler);
            Assert.Same(c, b.InnerHandler);
        }
Example #16
0
        public async Task SendAsync_NoHeader_WhenExpired()
        {
            var handler = new MockDelegatingHandler();

            handler.Responses.Add(new HttpResponseMessage(HttpStatusCode.OK));
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/test");
            var sut     = new WrappedAuthenticationProvider(() => Task.FromResult(ExpiredAuthenticationToken), "X-ZUMO-AUTH")
            {
                InnerHandler = handler
            };

            var response = await sut.WrappedSendAsync(request).ConfigureAwait(false);

            Assert.NotNull(response);
            Assert.Single(handler.Requests);
            var headers = handler.Requests[0].Headers;

            Assert.False(headers.Contains("X-ZUMO-AUTH"));
        }
Example #17
0
        public async Task SendAsync_AddsHeader_BearerAuth()
        {
            var handler = new MockDelegatingHandler();

            handler.Responses.Add(new HttpResponseMessage(HttpStatusCode.OK));
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/test");
            var sut     = new WrappedAuthenticationProvider(() => Task.FromResult(ValidAuthenticationToken))
            {
                InnerHandler = handler
            };

            var response = await sut.WrappedSendAsync(request).ConfigureAwait(false);

            Assert.NotNull(response);
            Assert.Single(handler.Requests);
            var headers = handler.Requests[0].Headers;

            Assert.Equal(ValidAuthenticationToken.Token, headers.Authorization.Parameter);
            Assert.Equal("Bearer", headers.Authorization.Scheme);
        }
Example #18
0
        public void DelegatingHandlersAreCloned()
        {
            string       userAccount    = "*****@*****.**";
            Guid         subscriptionId = Guid.NewGuid();
            AzureContext context        = new AzureContext
                                          (
                new AzureSubscription()
            {
                Account     = userAccount,
                Environment = "AzureCloud",
                Id          = subscriptionId,
                Properties  = new Dictionary <AzureSubscription.Property, string>()
                {
                    { AzureSubscription.Property.Tenants, "common" }
                }
            },
                new AzureAccount()
            {
                Id         = userAccount,
                Type       = AzureAccount.AccountType.User,
                Properties = new Dictionary <AzureAccount.Property, string>()
                {
                    { AzureAccount.Property.Tenants, "common" }
                }
            },
                AzureEnvironment.PublicEnvironments["AzureCloud"]
                                          );

            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(userAccount, Guid.NewGuid().ToString());
            var mockHandler = new MockDelegatingHandler();
            var factory     = new ClientFactory();

            factory.AddHandler(mockHandler);
            var client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);

            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            Assert.Equal(5, MockDelegatingHandler.cloneCount);
        }
Example #19
0
        public async Task SendAsync_OverwritesHeader_WhenNotExpired()
        {
            var handler = new MockDelegatingHandler();

            handler.Responses.Add(new HttpResponseMessage(HttpStatusCode.OK));
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/test");

            request.Headers.Add("X-ZUMO-AUTH", "a-test-header");
            var sut = new WrappedAuthenticationProvider(() => Task.FromResult(ValidAuthenticationToken), "X-ZUMO-AUTH")
            {
                InnerHandler = handler
            };

            var response = await sut.WrappedSendAsync(request).ConfigureAwait(false);

            Assert.NotNull(response);
            Assert.Single(handler.Requests);
            var headers = handler.Requests[0].Headers;

            Assert.Equal(ValidAuthenticationToken.Token, headers.GetValues("X-ZUMO-AUTH").First());
        }
Example #20
0
        public void DelegatingHandlersAreCloned()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string userAccount    = "*****@*****.**";
            Guid   subscriptionId = Guid.NewGuid();
            var    account        = new AzureAccount()
            {
                Id   = userAccount,
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("common");
            var sub = new AzureSubscription()
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetAccount(userAccount);
            sub.SetEnvironment("AzureCloud");
            sub.SetTenant("common");
            AzureContext context = new AzureContext
                                   (
                sub,
                account,
                AzureEnvironment.PublicEnvironments["AzureCloud"]
                                   );

            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory(userAccount, Guid.NewGuid().ToString());
            var mockHandler = new MockDelegatingHandler();
            var factory     = new ClientFactory();

            factory.AddHandler(mockHandler);
            var client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);

            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            Assert.Equal(5, MockDelegatingHandler.cloneCount);
        }
Example #21
0
        public async Task SendServiceAsync_OnSuccessfulRequest_WithAuth()
        {
            var handler  = new MockDelegatingHandler();
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{}", Encoding.UTF8, "application/json")
            };

            handler.Responses.Add(response);

            var options = new DatasyncClientOptions
            {
                HttpPipeline   = new HttpMessageHandler[] { handler },
                InstallationId = "hijack",
                UserAgent      = "hijack"
            };
            var requestor = () => Task.FromResult(ValidAuthenticationToken);
            var client    = new WrappedHttpClient(Endpoint, new GenericAuthenticationProvider(requestor, "X-ZUMO-AUTH"), options);
            var request   = new ServiceRequest {
                Method = HttpMethod.Get, UriPathAndQuery = "/tables/movies/"
            };

            var actualResponse = await client.WrappedSendAsync(request).ConfigureAwait(false);

            Assert.Equal(200, actualResponse.StatusCode);
            Assert.Equal("{}", actualResponse.Content);
            Assert.True(actualResponse.HasContent);

            // Check that the right headers were applied to the request
            Assert.Single(handler.Requests);
            var actual = handler.Requests[0];

            Assert.Equal(options.UserAgent, actual.Headers.UserAgent.ToString());
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-VERSION", options.UserAgent);
            AssertEx.HasHeader(actual.Headers, "ZUMO-API-VERSION", "3.0.0");
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-AUTH", ValidAuthenticationToken.Token);
            AssertEx.HasHeader(actual.Headers, "X-ZUMO-INSTALLATION-ID", options.InstallationId);
        }
Example #22
0
        public async Task SendServiceAsync_Throws_OnFailedRequest()
        {
            var handler  = new MockDelegatingHandler();
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest);

            handler.Responses.Add(response);

            var options = new DatasyncClientOptions
            {
                HttpPipeline   = new HttpMessageHandler[] { handler },
                InstallationId = "hijack",
                UserAgent      = "hijack"
            };
            var client = new WrappedHttpClient(Endpoint, options);

            var request = new ServiceRequest {
                Method = HttpMethod.Get, UriPathAndQuery = "/tables/movies/", EnsureResponseContent = false
            };
            var exception = await Assert.ThrowsAsync <DatasyncInvalidOperationException>(() => client.WrappedSendAsync(request)).ConfigureAwait(false);

            Assert.NotNull(exception.Request);
            Assert.NotNull(exception.Response);
            Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
        }