Exemplo n.º 1
0
        public async Task CanGetAndSetResponseHeaders(string headerName, string headerValue, bool contentHeader)
        {
            var mockHandler = new MockHttpClientHandler(
                httpRequestMessage => {
                var responseMessage = new HttpResponseMessage((HttpStatusCode)200);

                if (contentHeader)
                {
                    responseMessage.Content = new StreamContent(new MemoryStream());
                    Assert.True(responseMessage.Content.Headers.TryAddWithoutValidation(headerName, headerValue));
                }
                else
                {
                    Assert.True(responseMessage.Headers.TryAddWithoutValidation(headerName, headerValue));
                }

                return(Task.FromResult(responseMessage));
            });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com:340"));

            var response = await ExecuteRequest(request, transport);

            Assert.True(response.TryGetHeader(headerName, out var value));
            Assert.AreEqual(headerValue, value);

            Assert.True(response.TryGetHeader(headerName.ToUpper(), out value));
            Assert.AreEqual(headerValue, value);

            CollectionAssert.Contains(response.Headers, new HttpHeader(headerName, headerValue));
        }
Exemplo n.º 2
0
        public async Task OriginalContentStreamIsReturnedIfNotAsync()
        {
            var content = new AsyncContent()
            {
                MemoryStream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 })
            };
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            };
            var mockHandler = new MockHttpClientHandler(httpRequestMessage => Task.FromResult(httpResponseMessage));

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            HttpPipelineRequest request = transport.CreateRequest(null);

            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("http://example.com:340"));

            HttpPipelineResponse response = await ExecuteRequest(request, transport);

            byte[] data = new byte[5];

            content.CreateContentReadStreamAsyncCompletionSource.SetResult(null);
            Stream stream = response.ResponseContentStream;

            Assert.AreSame(content.MemoryStream, stream);
        }
Exemplo n.º 3
0
        public async Task CanGetAndSetRequestHeaders(string headerName, string headerValue, bool contentHeader)
        {
            IEnumerable <string> httpHeaderValues = null;

            var mockHandler = new MockHttpClientHandler(
                httpRequestMessage => {
                Assert.True(
                    httpRequestMessage.Headers.TryGetValues(headerName, out httpHeaderValues) ||
                    httpRequestMessage.Content.Headers.TryGetValues(headerName, out httpHeaderValues));
            });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com:340"));
            request.Content = HttpPipelineRequestContent.Create(Array.Empty <byte>());

            request.AddHeader(headerName, headerValue);

            Assert.True(request.TryGetHeader(headerName, out var value));
            Assert.AreEqual(headerValue, value);

            Assert.True(request.TryGetHeader(headerName.ToUpper(), out value));
            Assert.AreEqual(headerValue, value);

            CollectionAssert.AreEqual(new []
            {
                new HttpHeader(headerName, headerValue),
            }, request.Headers);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(headerValue, string.Join(",", httpHeaderValues));
        }
Exemplo n.º 4
0
        public async Task RequestIdCanBeOverriden()
        {
            var mockHandler = new MockHttpClientHandler(httpRequestMessage => { });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.RequestId = "123";
            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("http://example.com:340"));

            var response = await ExecuteRequest(request, transport);

            Assert.AreEqual(request.RequestId, response.RequestId);
        }
Exemplo n.º 5
0
        public async Task SettingContentHeaderDoesNotSetContent(string headerName, string headerValue, bool contentHeader)
        {
            HttpContent httpMessageContent = null;
            var         mockHandler        = new MockHttpClientHandler(httpRequestMessage => { httpMessageContent = httpRequestMessage.Content; });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com:340"));
            request.AddHeader(headerName, headerValue);

            await ExecuteRequest(request, transport);

            Assert.Null(httpMessageContent);
        }
Exemplo n.º 6
0
        public async Task RequestAndResponseHasRequestId()
        {
            var mockHandler = new MockHttpClientHandler(httpRequestMessage => { });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            Assert.IsNotEmpty(request.RequestId);
            Assert.True(Guid.TryParse(request.RequestId, out _));
            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("http://example.com:340"));

            var response = await ExecuteRequest(request, transport);

            Assert.AreEqual(request.RequestId, response.RequestId);
        }
Exemplo n.º 7
0
        public async Task SettingHeaderOverridesDefaultContentLength()
        {
            long contentLength = 0;
            var  mockHandler   = new MockHttpClientHandler(
                httpRequestMessage => contentLength = httpRequestMessage.Content.Headers.ContentLength.Value);

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com"));
            request.Content = HttpPipelineRequestContent.Create(new byte[10]);
            request.AddHeader("Content-Length", "50");

            await ExecuteRequest(request, transport);

            Assert.AreEqual(50, contentLength);
        }
Exemplo n.º 8
0
        public async Task ContentLengthIsSetForArrayContent(HttpPipelineRequestContent content, int expectedLength)
        {
            long contentLength = 0;
            var  mockHandler   = new MockHttpClientHandler(
                httpRequestMessage => contentLength = httpRequestMessage.Content.Headers.ContentLength.Value
                );

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com"));
            request.Content = content;

            await ExecuteRequest(request, transport);

            Assert.AreEqual(expectedLength, contentLength);
        }
Exemplo n.º 9
0
        public async Task SettingHeaderOverridesDefaultHost()
        {
            string host        = null;
            var    mockHandler = new MockHttpClientHandler(
                httpRequestMessage => {
                host = httpRequestMessage.Headers.Host;
            });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com:340"));
            request.AddHeader("Host", "example.org");

            await ExecuteRequest(request, transport);

            Assert.AreEqual("example.org", host);
        }
Exemplo n.º 10
0
        public async Task CanGetAndSetMethod(HttpVerb method, string expectedMethod)
        {
            HttpMethod httpMethod  = null;
            var        mockHandler = new MockHttpClientHandler(
                httpRequestMessage => {
                httpMethod = httpRequestMessage.Method;
            });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(method, new Uri("http://example.com:340"));

            Assert.AreEqual(method, request.Method);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(expectedMethod, httpMethod.Method);
        }
Exemplo n.º 11
0
        public async Task CanGetAndSetUri()
        {
            Uri requestUri  = null;
            var mockHandler = new MockHttpClientHandler(
                httpRequestMessage => {
                requestUri = httpRequestMessage.RequestUri;
            });

            var expectedUri = new Uri("http://example.com:340");
            var transport   = new HttpClientTransport(new HttpClient(mockHandler));
            var request     = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, expectedUri);

            Assert.AreEqual(expectedUri, request.Uri);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(expectedUri, requestUri);
        }
Exemplo n.º 12
0
        public async Task HostHeaderSetFromUri()
        {
            string host        = null;
            Uri    uri         = null;
            var    mockHandler = new MockHttpClientHandler(
                httpRequestMessage => {
                uri  = httpRequestMessage.RequestUri;
                host = httpRequestMessage.Headers.Host;
            });

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com:340"));

            await ExecuteRequest(request, transport);

            // HttpClientHandler would correctly set Host header from Uri when it's not set explicitly
            Assert.AreEqual("http://example.com:340/", uri.ToString());
            Assert.Null(host);
        }
Exemplo n.º 13
0
        public async Task ContentStreamIsReturnedSynchronously()
        {
            var content = new AsyncContent()
            {
                MemoryStream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 })
            };
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            };
            var mockHandler = new MockHttpClientHandler(httpRequestMessage => Task.FromResult(httpResponseMessage));

            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            HttpPipelineRequest request = transport.CreateRequest(null);

            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("http://example.com:340"));

            HttpPipelineResponse response = await ExecuteRequest(request, transport);

            byte[]     data      = new byte[5];
            Stream     stream    = response.ResponseContentStream;
            Task <int> firstRead = stream.ReadAsync(data, 0, 5);

            Assert.False(firstRead.IsCompleted);

            content.CreateContentReadStreamAsyncCompletionSource.SetResult(null);
            Assert.AreEqual(5, await firstRead);

            // Exercise stream features
            stream.Position = 3;
            stream.Seek(-1, SeekOrigin.Current);
            var secondReadLength = await stream.ReadAsync(data, 0, 5);

            Assert.AreEqual(3, secondReadLength);
            Assert.False(stream.CanWrite);
            Assert.True(stream.CanSeek);
            Assert.True(stream.CanRead);
            Assert.Throws <NotSupportedException>(() => stream.Write(null, 0, 0));
            Assert.Throws <NotSupportedException>(() => stream.SetLength(5));
        }
Exemplo n.º 14
0
        public async Task CanGetAndSetContent()
        {
            byte[] requestBytes = null;
            var    mockHandler  = new MockHttpClientHandler(
                async httpRequestMessage => {
                requestBytes = await httpRequestMessage.Content.ReadAsByteArrayAsync();
            });

            var bytes     = Encoding.ASCII.GetBytes("Hello world");
            var content   = HttpPipelineRequestContent.Create(bytes);
            var transport = new HttpClientTransport(new HttpClient(mockHandler));
            var request   = transport.CreateRequest(null);

            request.SetRequestLine(HttpVerb.Get, new Uri("http://example.com:340"));
            request.Content = content;

            Assert.AreEqual(content, request.Content);

            await ExecuteRequest(request, transport);

            CollectionAssert.AreEqual(bytes, requestBytes);
        }
Exemplo n.º 15
0
        public async Task SendingRequestProducesEvents()
        {
            var handler = new MockHttpClientHandler(httpRequestMessage =>
            {
                var response     = new HttpResponseMessage((HttpStatusCode)500);
                response.Content = new ByteArrayContent(new byte[] { 6, 7, 8, 9, 0 });
                response.Headers.Add("Custom-Response-Header", "Improved value");
                return(Task.FromResult(response));
            });
            var    transport = new HttpClientTransport(new HttpClient(handler));
            var    pipeline  = new HttpPipeline(transport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (var request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                request.AddHeader("Date", "3/26/2019");
                request.AddHeader("Custom-Header", "Value");
                request.Content = HttpPipelineRequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId       = request.RequestId;

                var response = await pipeline.SendRequestAsync(request, CancellationToken.None);

                Assert.AreEqual(500, response.Status);
            }

            var e = _listener.SingleEventById(1);

            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Request", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("https://contoso.a.io/", e.GetProperty <string>("uri"));
            Assert.AreEqual("GET", e.GetProperty <string>("method"));
            StringAssert.Contains($"Date:3/26/2019{Environment.NewLine}", e.GetProperty <string>("headers"));
            StringAssert.Contains($"Custom-Header:Value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(2);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("RequestContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(5);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Response", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(6);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("ResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(8);
            Assert.AreEqual(EventLevel.Error, e.Level);
            Assert.AreEqual("ErrorResponse", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(9);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("ErrorResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));
        }
        public async Task SendingRequestProducesEvents()
        {
            var handler = new MockHttpClientHandler(httpRequestMessage => {
                var response     = new HttpResponseMessage((HttpStatusCode)500);
                response.Content = new ByteArrayContent(new byte[] { 6, 7, 8, 9, 0 });
                response.Headers.Add("Custom-Response-Header", "Improved value");
                return(Task.FromResult(response));
            });
            var transport = new HttpClientTransport(new HttpClient(handler));
            var options   = new HttpPipelineOptions(transport)
            {
                LoggingPolicy = LoggingPolicy.Shared
            };

            var    pipeline = options.Build("test", "1.0.0");
            string requestId;

            using (var request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpVerb.Get, new Uri("https://contoso.a.io"));
                request.AddHeader("Date", "3/26/2019");
                request.AddHeader("Custom-Header", "Value");
                request.Content = HttpPipelineRequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId       = request.RequestId;

                var response = await pipeline.SendRequestAsync(request, CancellationToken.None);

                Assert.AreEqual(500, response.Status);
            }

            Assert.True(_listener.EventData.Any(e =>
                                                e.EventId == 1 &&
                                                e.Level == EventLevel.Informational &&
                                                e.EventName == "Request" &&
                                                GetStringProperty(e, "requestId").Equals(requestId) &&
                                                GetStringProperty(e, "uri").Equals("https://contoso.a.io/") &&
                                                GetStringProperty(e, "method").Equals("GET") &&
                                                GetStringProperty(e, "headers").Contains($"Date:3/26/2019{Environment.NewLine}") &&
                                                GetStringProperty(e, "headers").Contains($"Custom-Header:Value{Environment.NewLine}")
                                                ));

            Assert.True(_listener.EventData.Any(e =>
                                                e.EventId == 2 &&
                                                e.Level == EventLevel.Verbose &&
                                                e.EventName == "RequestContent" &&
                                                GetStringProperty(e, "requestId").Equals(requestId) &&
                                                ((byte[])GetProperty(e, "content")).SequenceEqual(new byte[] { 1, 2, 3, 4, 5 }))
                        );

            Assert.True(_listener.EventData.Any(e =>
                                                e.EventId == 5 &&
                                                e.Level == EventLevel.Informational &&
                                                e.EventName == "Response" &&
                                                GetStringProperty(e, "requestId").Equals(requestId) &&
                                                (int)GetProperty(e, "status") == 500 &&
                                                GetStringProperty(e, "headers").Contains($"Custom-Response-Header:Improved value{Environment.NewLine}")
                                                ));

            Assert.True(_listener.EventData.Any(e =>
                                                e.EventId == 6 &&
                                                e.Level == EventLevel.Verbose &&
                                                e.EventName == "ResponseContent" &&
                                                GetStringProperty(e, "requestId").Equals(requestId) &&
                                                ((byte[])GetProperty(e, "content")).SequenceEqual(new byte[] { 6, 7, 8, 9, 0 }))
                        );

            Assert.True(_listener.EventData.Any(e =>
                                                e.EventId == 8 &&
                                                e.Level == EventLevel.Error &&
                                                e.EventName == "ErrorResponse" &&
                                                GetStringProperty(e, "requestId").Equals(requestId) &&
                                                (int)GetProperty(e, "status") == 500 &&
                                                GetStringProperty(e, "headers").Contains($"Custom-Response-Header:Improved value{Environment.NewLine}")
                                                ));

            Assert.True(_listener.EventData.Any(e =>
                                                e.EventId == 9 &&
                                                e.Level == EventLevel.Informational &&
                                                e.EventName == "ErrorResponseContent" &&
                                                GetStringProperty(e, "requestId").Equals(requestId) &&
                                                ((byte[])GetProperty(e, "content")).SequenceEqual(new byte[] { 6, 7, 8, 9, 0 }))
                        );
        }