Ejemplo n.º 1
0
        public void Invoke_SetsResponseBody()
        {
            var response     = new HttpResponseMessage(HttpStatusCode.OK);
            var expectedBody = @"{""x"":""y""}";

            response.Content = new StringContent(expectedBody, Encoding.UTF8, "application/json");
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var responseStream       = new MemoryStream();

            environment["owin.ResponseBody"] = responseStream;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            responseStream.Seek(0, SeekOrigin.Begin);
            byte[] bodyBytes = new byte[9];
            int    charsRead = responseStream.Read(bodyBytes, 0, 9);

            // Assert that we can read 9 characters and no more characters after that
            Assert.Equal(9, charsRead);
            Assert.Equal(-1, responseStream.ReadByte());
            Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
        }
Ejemplo n.º 2
0
        public void Invoke_RespectsInputBufferingSetting(bool bufferInput)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: bufferInput, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody         = "This is the request body.";
            var requestBodyMock      = new Mock <MemoryStream>(Encoding.UTF8.GetBytes(expectedBody));

            requestBodyMock.CallBase = true;
            requestBodyMock.Setup(s => s.CanSeek).Returns(false);
            MemoryStream requestBody = requestBodyMock.Object;

            environment["owin.RequestBody"] = requestBody;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            if (bufferInput)
            {
                Assert.False(requestBody.CanRead);
                // Assert that the OWIN environment still has a request body that can be read
                var    owinRequestBody = environment["owin.RequestBody"] as Stream;
                byte[] bodyBytes       = new byte[25];
                int    charsRead       = owinRequestBody.Read(bodyBytes, 0, 25);
                Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
            }
            else
            {
                Assert.True(requestBody.CanRead);
            }
            // Assert that Web API gets the right body
            var request = handler.Request;

            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);
        }
Ejemplo n.º 3
0
        public void Invoke_RespectsOutputBufferingSetting(bool bufferOutput)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ObjectContent <string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: bufferOutput);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            if (bufferOutput)
            {
                Assert.True(responseHeaders.ContainsKey("Content-Length"));
            }
            else
            {
                Assert.False(responseHeaders.ContainsKey("Content-Length"));
            }
        }
        public void Invoke_ThrowsOnNullResponse()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);
            var mockContext = new Mock<IOwinContext>();
            mockContext.Setup(context => context.Request).Returns(new OwinRequest());

            Assert.Throws<InvalidOperationException>(
                () => adapter.Invoke(mockContext.Object).Wait(),
                "The OWIN context's Response property must not be null.");
        }
Ejemplo n.º 5
0
        public void Invoke_SetsOwinEnvironment()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Same(environment, request.GetOwinEnvironment());
        }
        public void Invoke_BuildsAppropriateRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;
            Assert.Equal(HttpMethod.Get, request.Method);
            Assert.Equal("http://localhost/vroot/api/customers", request.RequestUri.AbsoluteUri);
        }
        public void Invoke_BuildsUriWithHostAndPort()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost:12345", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(HttpMethod.Get, request.Method);
            Assert.Equal("http://localhost:12345/vroot/api/customers", request.RequestUri.AbsoluteUri);
        }
Ejemplo n.º 8
0
        public void Invoke_ThrowsOnNullResponse()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var adapter     = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);
            var mockContext = new Mock <IOwinContext>();

            mockContext.Setup(context => context.Request).Returns(new OwinRequest());

            Assert.Throws <InvalidOperationException>(
                () => adapter.Invoke(mockContext.Object).Wait(),
                "The OWIN context's Response property must not be null.");
        }
        public void Invoke_Throws_IfHostHeaderMissing()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var requestHeaders = environment["owin.RequestHeaders"] as IDictionary<string, string[]>;
            requestHeaders.Remove("Host");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            Assert.Throws<InvalidOperationException>(
                () => adapter.Invoke(environment).Wait(),
                "The OWIN environment does not contain a value for the required 'Host' header.");
        }
Ejemplo n.º 10
0
        public void Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers/" + decodedId);
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);
            var route   = new HttpRoute("api/customers/{id}");

            adapter.Invoke(new OwinContext(environment)).Wait();
            IHttpRouteData routeData = route.GetRouteData("/vroot", handler.Request);

            Assert.NotNull(routeData);
            Assert.Equal(decodedId, routeData.Values["id"]);
        }
Ejemplo n.º 11
0
        public void Invoke_BuildsUriWithHostAndPort()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost:12345", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(HttpMethod.Get, request.Method);
            Assert.Equal("http://localhost:12345/vroot/api/customers", request.RequestUri.AbsoluteUri);
        }
Ejemplo n.º 12
0
        public void Invoke_CallsMessageHandler_WithEnvironmentUser()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var user = new Mock <IPrincipal>().Object;

            environment["server.User"] = user;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            Assert.Equal(user, handler.User);
        }
Ejemplo n.º 13
0
        public void Invoke_CallsMessageHandler_WithEnvironmentCancellationToken()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var cancellationToken    = new CancellationToken();

            environment["owin.CallCancelled"] = cancellationToken;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            Assert.Equal(cancellationToken, handler.CancellationToken);
        }
Ejemplo n.º 14
0
        public void Invoke_DoesNotCallNext_IfMessageHandlerDoesNotAddNoRouteMatchedProperty()
        {
            var mockNext = new Mock <OwinMiddleware>(MockBehavior.Strict, null);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub()
            {
                Response = response, AddNoRouteMatchedKey = false
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: mockNext.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            Assert.DoesNotThrow(
                () => adapter.Invoke(new OwinContext(environment)).Wait());
        }
Ejemplo n.º 15
0
        public void Invoke_Throws_IfMessageHandlerReturnsNull()
        {
            HttpResponseMessage response = null;
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            Assert.Throws <InvalidOperationException>(
                () => adapter.Invoke(new OwinContext(environment)).Wait(),
                "The message handler did not return a response message.");
        }
Ejemplo n.º 16
0
        public void Invoke_SetsRequestBodyOnRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody         = "This is the request body.";

            environment["owin.RequestBody"] = new MemoryStream(Encoding.UTF8.GetBytes(expectedBody));
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);
        }
Ejemplo n.º 17
0
        public void Invoke_SetsClientCertificate()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var clientCert           = new Mock <X509Certificate2>().Object;

            environment["ssl.ClientCertificate"] = clientCert;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(clientCert, request.GetClientCertificate());
        }
Ejemplo n.º 18
0
        public void Invoke_AddsZeroContentLengthHeader_WhenThereIsNoContent()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var handler  = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal("0", responseHeaders["Content-Length"][0]);
        }
Ejemplo n.º 19
0
        public void Invoke_SetsRequestIsLocalProperty(bool?isLocal, bool expectedRequestLocal)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");

            if (isLocal.HasValue)
            {
                environment["server.IsLocal"] = isLocal.Value;
            }
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(expectedRequestLocal, request.IsLocal());
        }
Ejemplo n.º 20
0
        public void Invoke_CallsNext_IfMessageHandlerReturns404WithNoRouteMatched()
        {
            var nextMock = new Mock <OwinMiddleware>(null);

            nextMock.Setup(middleware => middleware.Invoke(It.IsAny <OwinContext>())).Returns(TaskHelpers.Completed()).Verifiable();
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub()
            {
                Response = response, AddNoRouteMatchedKey = true
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: nextMock.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            nextMock.Verify();
        }
Ejemplo n.º 21
0
 public static Func<IDictionary<string, object>, Task> CreateWebApiAppFunc2(HttpConfiguration config, HttpMessageHandlerOptions options = null)
 {
     var bufferPolicy = new OwinBufferPolicySelector();
     config.Services.Replace(typeof(IHostBufferPolicySelector), bufferPolicy); // Done just so App can get access to it.   
     var app = new HttpServer(config);
     if (options == null)
     {
         options = new HttpMessageHandlerOptions()
         {
             MessageHandler = app,
             BufferPolicySelector = bufferPolicy,
             ExceptionLogger = new GlobalErrorLoggingService(),
             ExceptionHandler = new GlobalErrorHandlerService()
         };
     }
     var handler = new HttpMessageHandlerAdapter(new NotFoundMiddleware(), options);
     return (env) => handler.Invoke(new OwinContext(env));
 }
Ejemplo n.º 22
0
        public void Invoke_AddsTransferEncodingChunkedHeaderIfThereIsNoContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ObjectContent <string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
Ejemplo n.º 23
0
        public void Invoke_SetsResponseStatusCodeAndReasonPhrase()
        {
            var expectedReasonPhrase = "OH NO!";
            var response             = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
            {
                ReasonPhrase = expectedReasonPhrase
            };
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            Assert.Equal(503, environment["owin.ResponseStatusCode"]);
            Assert.Equal(expectedReasonPhrase, environment["owin.ResponseReasonPhrase"]);
        }
Ejemplo n.º 24
0
        public void Invoke_AddsTransferEncodingChunkedHeaderOverContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("Hello world")));
            response.Headers.TransferEncodingChunked = true;
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
Ejemplo n.º 25
0
        public void Invoke_AddsRequestHeadersToRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var requestHeaders       = environment["owin.RequestHeaders"] as IDictionary <string, string[]>;

            requestHeaders["Accept"]         = new string[] { "application/json", "application/xml" };
            requestHeaders["Content-Length"] = new string[] { "45" };
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(2, request.Headers.Count());
            Assert.Equal(new string[] { "application/json", "application/xml" }, request.Headers.Accept.Select(mediaType => mediaType.ToString()).ToArray());
            Assert.Equal("localhost", request.Headers.Host);
            Assert.Single(request.Content.Headers);
            Assert.Equal(45, request.Content.Headers.ContentLength);
        }
Ejemplo n.º 26
0
        public void Invoke_SetsResponseHeaders()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Headers.Location = new Uri("http://www.location.com/");
            response.Content          = new StringContent(@"{""x"":""y""}", Encoding.UTF8, "application/json");
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal(3, responseHeaders.Count);
            Assert.Equal("http://www.location.com/", Assert.Single(responseHeaders["Location"]));
            Assert.Equal("9", Assert.Single(responseHeaders["Content-Length"]));
            Assert.Equal("application/json; charset=utf-8", Assert.Single(responseHeaders["Content-Type"]));
        }
        public void Invoke_Throws_IfMessageHandlerReturnsNull()
        {
            HttpResponseMessage response = null;
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            Assert.Throws<InvalidOperationException>(
                () => adapter.Invoke(environment).Wait(),
                "The message handler did not return a response message.");
        }
        public void Invoke_CallsMessageHandler_WithEnvironmentUser()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var user = new Mock<IPrincipal>().Object;
            environment["server.User"] = user;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.Equal(user, handler.User);
        }
        public void Invoke_CallsMessageHandler_WithEnvironmentCancellationToken()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var cancellationToken = new CancellationToken();
            environment["owin.CallCancelled"] = cancellationToken;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.Equal(cancellationToken, handler.CancellationToken);
        }
        public void Invoke_SetsClientCertificate()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var clientCert = new Mock<X509Certificate2>().Object;
            environment["ssl.ClientCertificate"] = clientCert;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(clientCert, request.GetClientCertificate());
        }
        public void Invoke_AddsTransferEncodingChunkedHeaderOverContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("Hello world")));
            response.Headers.TransferEncodingChunked = true;
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
        public void ExceptionHandler_IfUsingListConstructor_ReturnsDefaultExceptionHandler()
        {
            // Arrange
            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())
            {
                IHostBufferPolicySelector bufferPolicySelector = CreateDummyBufferPolicy();
#pragma warning disable 0618
                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, messageHandler,
                    bufferPolicySelector);
#pragma warning restore 0618

                // Act
                IExceptionHandler exceptionHandler = product.ExceptionHandler;

                // Assert
                Assert.IsType<DefaultExceptionHandler>(exceptionHandler);
            }
        }
        public void Invoke_SetsResponseHeaders()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Headers.Location = new Uri("http://www.location.com/");
            response.Content = new StringContent(@"{""x"":""y""}", Encoding.UTF8, "application/json");
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal(3, responseHeaders.Count);
            Assert.Equal("http://www.location.com/", Assert.Single(responseHeaders["Location"]));
            Assert.Equal("9", Assert.Single(responseHeaders["Content-Length"]));
            Assert.Equal("application/json; charset=utf-8", Assert.Single(responseHeaders["Content-Type"]));
        }
        public void Invoke_RespectsOutputBufferingSetting(bool bufferOutput)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ObjectContent<string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: bufferOutput);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            if (bufferOutput)
            {
                Assert.True(responseHeaders.ContainsKey("Content-Length"));
            }
            else
            {
                Assert.False(responseHeaders.ContainsKey("Content-Length"));
            }            
        }
        public void AppDisposing_IfUsingListConstructor_ReturnsDefaultExceptionHandler()
        {
            // Arrange
            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())
            {
                IHostBufferPolicySelector bufferPolicySelector = CreateDummyBufferPolicy();
#pragma warning disable 0618
                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, messageHandler,
                    bufferPolicySelector);
#pragma warning restore 0618

                // Act
                CancellationToken appDisposing = product.AppDisposing;

                // Assert
                Assert.Equal(CancellationToken.None, appDisposing);
            }
        }
        public void Invoke_CallsNext_IfMessageHandlerReturns404WithNoRouteMatched()
        {
            bool nextCalled = false;
            var next = new Func<IDictionary<string, object>, Task>(env =>
                {
                    nextCalled = true;
                    return TaskHelpers.Completed();
                });
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = true };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next, handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.True(nextCalled);
        }
 public static Func<IDictionary<string, object>, Task> CreateWebApiAppFunc(HttpConfiguration config)
 {
     var app = new HttpServer(config);
     var options = new HttpMessageHandlerOptions()
     {
         MessageHandler = app,
         BufferPolicySelector = new OwinBufferPolicySelector(),
         ExceptionLogger = new WebApiExceptionLogger(),
         ExceptionHandler = new WebApiExceptionHandler()
     };
     var handler = new HttpMessageHandlerAdapter(null, options);
     return (env) => handler.Invoke(new OwinContext(env));
 }
        public void Invoke_CallsNext_IfMessageHandlerReturns404WithNoRouteMatched()
        {
            var nextMock = new Mock<OwinMiddleware>(null);
            nextMock.Setup(middleware => middleware.Invoke(It.IsAny<OwinContext>())).Returns(TaskHelpers.Completed()).Verifiable();
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = true };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: nextMock.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            nextMock.Verify();
        }
        public void Invoke_DoesNotCallNext_IfMessageHandlerDoesNotAddNoRouteMatchedProperty()
        {
            var mockNext = new Mock<OwinMiddleware>(MockBehavior.Strict, null);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = false };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: mockNext.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            Assert.DoesNotThrow(
                () => adapter.Invoke(new OwinContext(environment)).Wait());
        }
        public void Invoke_SetsOwinEnvironment()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;
            Assert.Same(environment, request.GetOwinEnvironment());
        }
        public void BufferPolicySelector_IfUsingListConstructor_ReturnsSpecifiedInstance()
        {
            // Arrange
            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())
            {
                IHostBufferPolicySelector expectedBufferPolicySelector = CreateDummyBufferPolicy();
#pragma warning disable 0618
                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, messageHandler,
                    expectedBufferPolicySelector);
#pragma warning restore 0618

                // Act
                IHostBufferPolicySelector bufferPolicySelector = product.BufferPolicySelector;

                // Assert
                Assert.Same(expectedBufferPolicySelector, bufferPolicySelector);
            }
        }
        public void Invoke_SetsResponseStatusCodeAndReasonPhrase()
        {
            var expectedReasonPhrase = "OH NO!";
            var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { ReasonPhrase = expectedReasonPhrase };
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.Equal(HttpStatusCode.ServiceUnavailable, environment["owin.ResponseStatusCode"]);
            Assert.Equal(expectedReasonPhrase, environment["owin.ResponseReasonPhrase"]);
        }
        public void Invoke_AddsRequestHeadersToRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var requestHeaders = environment["owin.RequestHeaders"] as IDictionary<string, string[]>;
            requestHeaders["Accept"] = new string[] { "application/json", "application/xml" };
            requestHeaders["Content-Length"] = new string[] { "45" };
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(2, request.Headers.Count());
            Assert.Equal(new string[] { "application/json", "application/xml" }, request.Headers.Accept.Select(mediaType => mediaType.ToString()).ToArray());
            Assert.Equal("localhost", request.Headers.Host);
            Assert.Single(request.Content.Headers);
            Assert.Equal(45, request.Content.Headers.ContentLength);
        }
        public void Invoke_SetsResponseBody()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var expectedBody = @"{""x"":""y""}";
            response.Content = new StringContent(expectedBody, Encoding.UTF8, "application/json");
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var responseStream = new MemoryStream();
            environment["owin.ResponseBody"] = responseStream;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            responseStream.Seek(0, SeekOrigin.Begin);
            byte[] bodyBytes = new byte[9];
            int charsRead = responseStream.Read(bodyBytes, 0, 9);
            // Assert that we can read 9 characters and no more characters after that
            Assert.Equal(9, charsRead);
            Assert.Equal(-1, responseStream.ReadByte());
            Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
        }
        public void Invoke_SetsRequestBodyOnRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody = "This is the request body.";
            environment["owin.RequestBody"] = new MemoryStream(Encoding.UTF8.GetBytes(expectedBody));
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);
        }
        public void Invoke_AddsZeroContentLengthHeader_WhenThereIsNoContent()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal("0", responseHeaders["Content-Length"][0]);
        }
        public void Invoke_RespectsInputBufferingSetting(bool bufferInput)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: bufferInput, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody = "This is the request body.";
            var requestBodyMock = new Mock<MemoryStream>(Encoding.UTF8.GetBytes(expectedBody));
            requestBodyMock.CallBase = true;
            requestBodyMock.Setup(s => s.CanSeek).Returns(false);
            MemoryStream requestBody = requestBodyMock.Object;
            environment["owin.RequestBody"] = requestBody;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            if (bufferInput)
            {
                Assert.False(requestBody.CanRead);
                // Assert that the OWIN environment still has a request body that can be read
                var owinRequestBody = environment["owin.RequestBody"] as Stream;
                byte[] bodyBytes = new byte[25];
                int charsRead = owinRequestBody.Read(bodyBytes, 0, 25);
                Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
            }
            else
            {
                Assert.True(requestBody.CanRead);
            }
            // Assert that Web API gets the right body
            var request = handler.Request;
            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);

        }
        public void Invoke_AddsTransferEncodingChunkedHeaderIfThereIsNoContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ObjectContent<string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
        public void Invoke_SetsOwinEnvironment()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Same(environment, request.GetOwinEnvironment());
        }
        // Disabled tests until we can rely on a Microsoft.Owin implementation that provides a
        // URI that handles the following encoded characters: % \ ? #
        // Tracked by https://aspnetwebstack.codeplex.com/workitem/1054
        //[InlineData("%24")]
        //[InlineData(@"\")]
        //[InlineData("?#")]
        public void Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers/" + decodedId);
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);
            var route = new HttpRoute("api/customers/{id}");
            
            adapter.Invoke(environment).Wait();
            IHttpRouteData routeData = route.GetRouteData("/vroot", handler.Request);

            Assert.NotNull(routeData);
            Assert.Equal(decodedId, routeData.Values["id"]);
        }
        public void Invoke_SetsRequestIsLocalProperty(bool? isLocal, bool expectedRequestLocal)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            if (isLocal.HasValue)
            {
                environment["server.IsLocal"] = isLocal.Value;
            }
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(expectedRequestLocal, request.IsLocal());
        }