Exemplo n.º 1
0
 public async Task ProcessBatchAsync_Throws_IfRequestIsNull()
 {
     UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());
     await ExceptionAssert.ThrowsArgumentNullAsync(
         () => batchHandler.ProcessBatchAsync(null, CancellationToken.None),
         "request");
 }
Exemplo n.º 2
0
        public void ProcessBatchAsync_CallsRegisterForDispose()
        {
            List <IDisposable> expectedResourcesForDisposal = new List <IDisposable>();
            MockHttpServer     server = new MockHttpServer(request =>
            {
                var tmpContent = new StringContent(String.Empty);
                request.RegisterForDispose(tmpContent);
                expectedResourcesForDisposal.Add(tmpContent);
                return(new HttpResponseMessage {
                    Content = new StringContent(request.RequestUri.AbsoluteUri)
                });
            });
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
            HttpRequestMessage          batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
                    new MultipartContent("mixed") // ChangeSet
                    {
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/"))
                    }
                }
            };

            var response             = batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result;
            var resourcesForDisposal = batchRequest.GetResourcesForDisposal();

            foreach (var expectedResource in expectedResourcesForDisposal)
            {
                Assert.Contains(expectedResource, resourcesForDisposal);
            }
        }
Exemplo n.º 3
0
 public async Task ExecuteOperation_Throws_IfReaderIsNull()
 {
     UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());
     await ExceptionAssert.ThrowsArgumentNullAsync(
         () => batchHandler.ExecuteOperationAsync(null, Guid.NewGuid(), new HttpRequestMessage(), CancellationToken.None),
         "batchReader");
 }
Exemplo n.º 4
0
        public void ExecuteChangeSetAsync_ReturnsSingleErrorResponse()
        {
            MockHttpServer server = new MockHttpServer(request =>
            {
                if (request.Method == HttpMethod.Post)
                {
                    return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));
                }
                return(Task.FromResult(new HttpResponseMessage()));
            });
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
            HttpRequestMessage          batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    new MultipartContent("mixed") // ChangeSet
                    {
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Put, "http://example.com/values")),
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")),
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Delete, "http://example.com/values")),
                    }
                }
            };
            ODataMessageReader reader = batchRequest.Content.GetODataMessageReaderAsync(new ODataMessageReaderSettings {
                BaseUri = new Uri("http://example.com")
            }).Result;
            ODataBatchReader batchReader = reader.CreateODataBatchReader();

            var response = batchHandler.ExecuteChangeSetAsync(batchReader, Guid.NewGuid(), batchRequest, CancellationToken.None).Result;

            var changesetResponse = Assert.IsType <ChangeSetResponseItem>(response);

            Assert.Equal(1, changesetResponse.Responses.Count());
            Assert.Equal(HttpStatusCode.BadRequest, changesetResponse.Responses.First().StatusCode);
        }
Exemplo n.º 5
0
        public void ExecuteChangeSet_Throws_IfReaderIsNull()
        {
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());

            Assert.ThrowsArgumentNull(
                () => batchHandler.ExecuteChangeSetAsync(null, Guid.NewGuid(), new HttpRequestMessage(), CancellationToken.None).Wait(),
                "batchReader");
        }
Exemplo n.º 6
0
        public void ValidateRequest_Throws_IfResponsesIsNull()
        {
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());

            Assert.ThrowsArgumentNull(
                () => batchHandler.ValidateRequest(null),
                "request");
        }
Exemplo n.º 7
0
        public void CreateResponseMessageAsync_Throws_IfResponsesAreNull()
        {
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());

            Assert.ThrowsArgumentNull(
                () => batchHandler.CreateResponseMessageAsync(null, new HttpRequestMessage(), CancellationToken.None).Wait(),
                "responses");
        }
Exemplo n.º 8
0
        public void ValidateRequest_Throws_IfResponsesIsNull()
        {
            // Arrange
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();

            // Act & Assert
            ExceptionAssert.ThrowsArgumentNull(() => batchHandler.ValidateRequest(null), "request");
        }
Exemplo n.º 9
0
        public void Parameter_Constructor()
        {
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());

            Assert.NotNull(batchHandler.Invoker);
            Assert.NotNull(batchHandler.MessageQuotas);
            Assert.Null(batchHandler.ODataRouteName);
        }
Exemplo n.º 10
0
        public void ProcessBatchAsync_Throws_IfRequestIsNull()
        {
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());

            Assert.ThrowsArgumentNull(
                () => batchHandler.ProcessBatchAsync(null, CancellationToken.None).Wait(),
                "request");
        }
Exemplo n.º 11
0
        public async Task ProcessBatchAsync_Throws_IfContextIsNull()
        {
            // Arrange
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();
            RequestDelegate             next         = null;

            // Act & Assert
            await ExceptionAssert.ThrowsArgumentNullAsync(() => batchHandler.ProcessBatchAsync(null, next), "context");
        }
Exemplo n.º 12
0
        public async Task ExecuteChangeSetAsync_CopiesPropertiesFromRequest_WithoutExcludedProperties()
        {
            // Arrange
            RequestDelegate handler = context =>
            {
                context.Features[typeof(UnbufferedODataBatchHandlerTest)] = "bar";
                return(Task.FromResult(context.Response));
            };

            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();

            string      batchRequest = @"--cb7bb9ee-dce2-4c94-bf11-b742b2bc6072
Content-Type: multipart/mixed; boundary=""09f27d33-41ea-4334-8ace-1738bd2793a9""

--09f27d33-41ea-4334-8ace-1738bd2793a9
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1328966982

POST /values HTTP/1.1
Host: example.com
Content-Type: text/plain; charset=utf-8

foo
--09f27d33-41ea-4334-8ace-1738bd2793a9--

--cb7bb9ee-dce2-4c94-bf11-b742b2bc6072--
";
            HttpRequest request      = RequestFactory.Create("Post", "http://example.com/$batch", opt => opt.AddModel(EdmCoreModel.Instance));
            HttpContext httpContext  = request.HttpContext;

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            request.Body          = new MemoryStream(requestBytes);
            request.ContentType   = "multipart/mixed;boundary=\"09f27d33-41ea-4334-8ace-1738bd2793a9\"";
            request.ContentLength = 431;
            httpContext.ODataFeature().PrefixName = "";
            IServiceProvider sp = request.GetSubServiceProvider();

            IODataRequestMessage oDataRequestMessage = ODataMessageWrapperHelper.Create(request.Body, request.Headers, sp);
            ODataMessageReader   oDataMessageReader  = new ODataMessageReader(oDataRequestMessage, new ODataMessageReaderSettings {
                BaseUri = new Uri("http://example.com")
            });

            ODataBatchReader batchReader = await oDataMessageReader.CreateODataBatchReaderAsync();

            List <ODataBatchResponseItem> responses = new List <ODataBatchResponseItem>();

            // Act
            var response = await batchHandler.ExecuteChangeSetAsync(batchReader, Guid.NewGuid(), request, handler);

            // Arrange
            ChangeSetResponseItem changeSetResponseItem = Assert.IsType <ChangeSetResponseItem>(response);
            HttpContext           changeSetContext      = Assert.Single(changeSetResponseItem.Contexts);

            Assert.Equal("bar", changeSetContext.Features[typeof(UnbufferedODataBatchHandlerTest)]);
        }
Exemplo n.º 13
0
        public void Parameter_Constructor()
        {
            // Arrange
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();

            // Act & Assert
            Assert.False(batchHandler.ContinueOnError);
            Assert.NotNull(batchHandler.MessageQuotas);
            Assert.Null(batchHandler.PrefixName);
        }
Exemplo n.º 14
0
        public async Task CreateResponseMessageAsync_Throws_IfResponsesAreNull()
        {
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());
            HttpRequestMessage          request      = new HttpRequestMessage();

            request.EnableHttpDependencyInjectionSupport();
            await ExceptionAssert.ThrowsArgumentNullAsync(
                () => batchHandler.CreateResponseMessageAsync(null, request, CancellationToken.None),
                "responses");
        }
Exemplo n.º 15
0
        public async Task ExecuteChangeSet_Throws_IfReaderIsNull()
        {
            // Arrange
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();
            HttpContext httpContext = new DefaultHttpContext();

            // Act & Assert
            await ExceptionAssert.ThrowsArgumentNullAsync(() => batchHandler.ExecuteChangeSetAsync(null, Guid.NewGuid(), httpContext.Request, null),
                                                          "batchReader");
        }
Exemplo n.º 16
0
        public async Task ExecuteOperation_Throws_IfReaderIsNull()
        {
            // Arrange
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();
            Mock <HttpRequest>          request      = new Mock <HttpRequest>();

            // Act & Assert
            await ExceptionAssert.ThrowsArgumentNullAsync(
                () => batchHandler.ExecuteOperationAsync(null, Guid.NewGuid(), request.Object, null),
                "batchReader");
        }
Exemplo n.º 17
0
        public void ExecuteOperation_Throws_IfRequestIsNull()
        {
            var httpContent = new StringContent(String.Empty, Encoding.UTF8, "multipart/mixed");

            httpContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("boundary", Guid.NewGuid().ToString()));
            var reader = httpContent.GetODataMessageReaderAsync(new ODataMessageReaderSettings(), CancellationToken.None).Result;
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(new HttpServer());

            Assert.ThrowsArgumentNull(
                () => batchHandler.ExecuteOperationAsync(reader.CreateODataBatchReader(), Guid.NewGuid(), null, CancellationToken.None).Wait(),
                "originalRequest");
        }
Exemplo n.º 18
0
        public async Task CreateResponseMessageAsync_Throws_IfResponsesAreNull()
        {
            // Arrange
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();
            HttpContext context = new DefaultHttpContext();

            context.ODataFeature().PrefixName = "odata";
            context.RequestServices = BuildServiceProvider(opt => opt.AddModel("odata", EdmCoreModel.Instance));

            // Act & Assert
            await ExceptionAssert.ThrowsArgumentNullAsync(() => batchHandler.CreateResponseMessageAsync(null, context.Request),
                                                          "responses");
        }
Exemplo n.º 19
0
        public void ExecuteChangeSetAsync_CopiesPropertiesFromRequest_WithoutExcludedProperties()
        {
            MockHttpServer server = new MockHttpServer(request =>
            {
                return(new HttpResponseMessage
                {
                    RequestMessage = request
                });
            });
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
            HttpRequestMessage          batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    new MultipartContent("mixed") // ChangeSet
                    {
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")
                        {
                            Content = new StringContent("foo")
                        })
                    }
                }
            };

            batchRequest.Properties.Add("foo", "bar");
            batchRequest.SetRouteData(new HttpRouteData(new HttpRoute()));
            batchRequest.RegisterForDispose(new StringContent(String.Empty));
            ODataMessageReader reader = batchRequest.Content
                                        .GetODataMessageReaderAsync(new ODataMessageReaderSettings {
                BaseUri = new Uri("http://example.com")
            }, CancellationToken.None)
                                        .Result;
            ODataBatchReader batchReader            = reader.CreateODataBatchReader();
            List <ODataBatchResponseItem> responses = new List <ODataBatchResponseItem>();
            Guid batchId = Guid.NewGuid();

            batchReader.Read();

            var response = batchHandler.ExecuteChangeSetAsync(batchReader, Guid.NewGuid(), batchRequest, CancellationToken.None).Result;

            var changeSetResponses = ((ChangeSetResponseItem)response).Responses;

            foreach (var changeSetResponse in changeSetResponses)
            {
                var changeSetRequest = changeSetResponse.RequestMessage;
                Assert.Equal("bar", changeSetRequest.Properties["foo"]);
                Assert.Null(changeSetRequest.GetRouteData());
                Assert.Same(changeSetRequest, changeSetRequest.GetUrlHelper().Request);
                Assert.Empty(changeSetRequest.GetResourcesForDisposal());
            }
        }
Exemplo n.º 20
0
        public async Task ExecuteOperationAsync_CopiesPropertiesFromRequest_WithoutExcludedProperties()
        {
            // Arrange
            RequestDelegate handler = context =>
            {
                context.Features[typeof(UnbufferedODataBatchHandlerTest)] = "foo";
                return(Task.FromResult(context.Response));
            };

            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();
            string batchRequest = @"--75148e61-e67a-4bb7-ac0f-78fa30d0da30
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 318941389

GET / HTTP/1.1
Host: example.com


--75148e61-e67a-4bb7-ac0f-78fa30d0da30--
";

            HttpRequest request     = RequestFactory.Create("Post", "http://example.com/$batch", opt => opt.AddModel(EdmCoreModel.Instance));
            HttpContext httpContext = request.HttpContext;

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            request.Body          = new MemoryStream(requestBytes);
            request.ContentType   = "multipart/mixed;boundary=\"75148e61-e67a-4bb7-ac0f-78fa30d0da30\"";
            request.ContentLength = 431;
            httpContext.ODataFeature().PrefixName = "";
            IServiceProvider sp = request.GetSubServiceProvider();

            IODataRequestMessage oDataRequestMessage = ODataMessageWrapperHelper.Create(httpContext.Request.Body, request.Headers, sp);
            ODataMessageReader   oDataMessageReader  = new ODataMessageReader(oDataRequestMessage, new ODataMessageReaderSettings {
                BaseUri = new Uri("http://example.com")
            });

            ODataBatchReader batchReader = await oDataMessageReader.CreateODataBatchReaderAsync();

            List <ODataBatchResponseItem> responses = new List <ODataBatchResponseItem>();
            await batchReader.ReadAsync();

            // Act
            var response = await batchHandler.ExecuteOperationAsync(batchReader, Guid.NewGuid(), httpContext.Request, handler);

            // Assert
            OperationResponseItem operationResponseItem = Assert.IsType <OperationResponseItem>(response);

            Assert.Equal("foo", operationResponseItem.Context.Features[typeof(UnbufferedODataBatchHandlerTest)]);
        }
Exemplo n.º 21
0
        public async Task ExecuteChangeSet_Throws_IfRequestIsNull()
        {
            // Arrange
            ODataMessageInfo            messageInfo  = new ODataMessageInfo();
            ODataMessageReaderSettings  settings     = new ODataMessageReaderSettings();
            Mock <ODataInputContext>    inputContext = new Mock <ODataInputContext>(ODataFormat.Batch, messageInfo, settings);
            Mock <ODataBatchReader>     batchReader  = new Mock <ODataBatchReader>(inputContext.Object, false);
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();

            // Act & Assert
            await ExceptionAssert.ThrowsArgumentNullAsync(
                () => batchHandler.ExecuteChangeSetAsync(batchReader.Object, Guid.NewGuid(), null, null),
                "originalRequest");
        }
Exemplo n.º 22
0
        public async Task ProcessBatchAsync_CallsInvokerForEachRequest()
        {
            // Arrange
            MockHttpServer server = new MockHttpServer(async request =>
            {
                string responseContent = request.RequestUri.AbsoluteUri;
                if (request.Content != null)
                {
                    string content = await request.Content.ReadAsStringAsync();
                    if (!String.IsNullOrEmpty(content))
                    {
                        responseContent += "," + content;
                    }
                }
                return(new HttpResponseMessage {
                    Content = new StringContent(responseContent)
                });
            });
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
            HttpRequestMessage          batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
                    new MultipartContent("mixed") // ChangeSet
                    {
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")
                        {
                            Content = new StringContent("foo")
                        })
                    }
                }
            };

            batchRequest.EnableHttpDependencyInjectionSupport();

            // Act
            var response = await batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None);

            // Assert
            var batchContent   = Assert.IsType <ODataBatchContent>(response.Content);
            var batchResponses = batchContent.Responses.ToArray();

            Assert.Equal(2, batchResponses.Length);
            var response0 = (OperationResponseItem)batchResponses[0];
            var response1 = (ChangeSetResponseItem)batchResponses[1];

            Assert.Equal("http://example.com/", await response0.Response.Content.ReadAsStringAsync());
            Assert.Equal("http://example.com/values,foo", await response1.Responses.First().Content.ReadAsStringAsync());
        }
Exemplo n.º 23
0
        public async Task ExecuteOperation_Throws_IfRequestIsNull()
        {
            // Arrange
            StringContent httpContent = new StringContent(string.Empty, Encoding.UTF8, "multipart/mixed");

            httpContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("boundary", Guid.NewGuid().ToString()));

            ODataMessageReader reader = await httpContent.GetODataMessageReaderAsync(new ODataMessageReaderSettings(), CancellationToken.None);

            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();

            // Act & Assert
            await ExceptionAssert.ThrowsArgumentNullAsync(
                () => batchHandler.ExecuteOperationAsync(reader.CreateODataBatchReader(), Guid.NewGuid(), null, null),
                "originalRequest");
        }
        public async Task ExecuteOperationAsync_CopiesPropertiesFromRequest_WithoutExcludedProperties()
        {
            MockHttpServer server = new MockHttpServer(request =>
            {
                return(new HttpResponseMessage
                {
                    RequestMessage = request
                });
            });
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
            HttpRequestMessage          batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
                }
            };

            batchRequest.Properties.Add("foo", "bar");
            batchRequest.SetRouteData(new HttpRouteData(new HttpRoute()));
            batchRequest.RegisterForDispose(new StringContent(String.Empty));
            ODataMessageReader reader = await batchRequest.Content
                                        .GetODataMessageReaderAsync(new ODataMessageReaderSettings { BaseUri = new Uri("http://example.com") }, CancellationToken.None);

            ODataBatchReader batchReader = await reader.CreateODataBatchReaderAsync();

            List <ODataBatchResponseItem> responses = new List <ODataBatchResponseItem>();
            Guid batchId = Guid.NewGuid();
            await batchReader.ReadAsync();

            var response = await batchHandler.ExecuteOperationAsync(batchReader, Guid.NewGuid(), batchRequest, CancellationToken.None);

            var operationResponse = ((OperationResponseItem)response).Response;
            var operationRequest  = operationResponse.RequestMessage;

            Assert.Equal("bar", operationRequest.Properties["foo"]);
            Assert.Null(operationRequest.GetRouteData());
            Assert.Same(operationRequest, operationRequest.GetUrlHelper().Request);
            Assert.Empty(operationRequest.GetResourcesForDisposal());
        }
Exemplo n.º 25
0
        public async Task ProcessBatchAsync_DisposesResponseInCaseOfException()
        {
            // Arrange
            List <MockHttpResponseMessage> responses = new List <MockHttpResponseMessage>();
            MockHttpServer server = new MockHttpServer(request =>
            {
                if (request.Method == HttpMethod.Put)
                {
                    throw new InvalidOperationException();
                }
                var response = new MockHttpResponseMessage();
                responses.Add(response);
                return(response);
            });
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
            HttpRequestMessage          batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
                    new MultipartContent("mixed") // ChangeSet
                    {
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")),
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Put, "http://example.com/values"))
                    }
                }
            };

            batchRequest.EnableHttpDependencyInjectionSupport();

            // Act & Assert
            await ExceptionAssert.ThrowsAsync <InvalidOperationException>(
                () => batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None));

            Assert.Equal(2, responses.Count);
            foreach (var response in responses)
            {
                Assert.True(response.IsDisposed);
            }
        }
Exemplo n.º 26
0
        public async Task ProcessBatchAsync_ContinueOnError(bool enableContinueOnError, string preferenceHeader, bool hasThirdResponse)
        {
            // Arrange
            RequestDelegate handler = async context =>
            {
                HttpRequest request         = context.Request;
                string      responseContent = request.GetDisplayUrl();
                string      content         = request.ReadBody();
                if (!string.IsNullOrEmpty(content))
                {
                    responseContent += "," + content;
                }

                HttpResponse response = context.Response;
                if (content.Equals("foo"))
                {
                    response.StatusCode = StatusCodes.Status400BadRequest;
                }
                await response.WriteAsync(responseContent);
            };

            string batchRequest = @"--d3df74a8-8212-4c2a-b4fb-d713a4ba383e
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1948857409

GET / HTTP/1.1
Host: example.com


--d3df74a8-8212-4c2a-b4fb-d713a4ba383e
Content-Type: multipart/mixed; boundary=""3c4d5753-d325-4806-8c80-38f4a5fbe523""

--3c4d5753-d325-4806-8c80-38f4a5fbe523
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1856004745

POST /values HTTP/1.1
Host: example.com
Content-Type: text/plain; charset=utf-8

foo
--3c4d5753-d325-4806-8c80-38f4a5fbe523--

--d3df74a8-8212-4c2a-b4fb-d713a4ba383e
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: -2010824035

POST /values HTTP/1.1
Host: example.com
Content-Type: text/plain; charset=utf-8

bar
--d3df74a8-8212-4c2a-b4fb-d713a4ba383e--
";

            HttpRequest request = RequestFactory.Create("Post", "http://example.com/$batch",
                                                        opt => opt.AddModel(EdmCoreModel.Instance).EnableContinueOnErrorHeader = enableContinueOnError);
            HttpContext httpContext = request.HttpContext;

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            request.Body          = new MemoryStream(requestBytes);
            request.ContentType   = "multipart/mixed;boundary=\"d3df74a8-8212-4c2a-b4fb-d713a4ba383e\"";
            request.ContentLength = 827;
            httpContext.ODataFeature().PrefixName = "";

            if (preferenceHeader != null)
            {
                httpContext.Request.Headers.Add("prefer", preferenceHeader);
            }

            httpContext.Response.Body = new MemoryStream();
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();

            batchHandler.PrefixName = "";

            // Act
            await batchHandler.ProcessBatchAsync(httpContext, handler);

            string responseBody = httpContext.Response.ReadBody();

            // Assert
            Assert.NotNull(responseBody);

            // #1 response
            Assert.Contains("http://example.com/", responseBody);

            // #2 bad response
            Assert.Contains("Bad Request", responseBody);
            Assert.Contains("http://example.com/values,foo", responseBody);

            // #3 response
            if (hasThirdResponse)
            {
                Assert.Contains("http://example.com/values,bar", responseBody);
            }
            else
            {
                Assert.DoesNotContain("http://example.com/values,bar", responseBody);
            }
        }
Exemplo n.º 27
0
        public async Task ExecuteChangeSetAsync_ReturnsSingleErrorResponse()
        {
            // Arrange
            RequestDelegate handler = context =>
            {
                if (context.Request.Method.ToUpperInvariant() == "POST")
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    return(Task.FromResult(context.Response));
                }

                return(Task.FromResult(context.Response));
            };

            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();
            string batchRequest = @"--86aef3eb-4af6-4750-a66d-df65e3f31ab0
Content-Type: multipart/mixed; boundary=""7a61b8c1-a80e-4e6b-bac7-2f65564e3fd6""

--7a61b8c1-a80e-4e6b-bac7-2f65564e3fd6
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: -1233709575

PUT /values HTTP/1.1
Host: example.com


--7a61b8c1-a80e-4e6b-bac7-2f65564e3fd6
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: -1854117385

POST /values HTTP/1.1
Host: example.com


--7a61b8c1-a80e-4e6b-bac7-2f65564e3fd6
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: -1665098746

DELETE /values HTTP/1.1
Host: example.com


--7a61b8c1-a80e-4e6b-bac7-2f65564e3fd6--

--86aef3eb-4af6-4750-a66d-df65e3f31ab0--";

            IEdmModel   model       = new EdmModel();
            HttpRequest request     = RequestFactory.Create("Post", "http://example.com/$batch", opt => opt.AddModel(model));
            HttpContext httpContext = request.HttpContext;

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            httpContext.Request.Body          = new MemoryStream(requestBytes);
            httpContext.Request.ContentType   = "multipart/mixed;boundary=\"86aef3eb-4af6-4750-a66d-df65e3f31ab0\"";
            httpContext.Request.ContentLength = 431;
            httpContext.ODataFeature().PrefixName = "";
            IServiceProvider sp = request.GetSubServiceProvider();

            IODataRequestMessage oDataRequestMessage = ODataMessageWrapperHelper.Create(httpContext.Request.Body, request.Headers, sp);
            ODataMessageReader   oDataMessageReader  = new ODataMessageReader(oDataRequestMessage, new ODataMessageReaderSettings {
                BaseUri = new Uri("http://example.com")
            });

            ODataBatchReader batchReader = await oDataMessageReader.CreateODataBatchReaderAsync();

            // Act
            var response = await batchHandler.ExecuteChangeSetAsync(batchReader, Guid.NewGuid(), httpContext.Request, handler);

            // Assert
            var changesetResponse = Assert.IsType <ChangeSetResponseItem>(response);
            var returnContext     = Assert.Single(changesetResponse.Contexts);

            Assert.Equal(StatusCodes.Status400BadRequest, returnContext.Response.StatusCode);
        }
Exemplo n.º 28
0
        public async Task ProcessBatchAsync_CallsInvokerForEachRequest()
        {
            // Arrange
            RequestDelegate next = async context =>
            {
                HttpRequest request         = context.Request;
                string      responseContent = request.GetDisplayUrl();
                string      content         = request.ReadBody();
                if (!string.IsNullOrEmpty(content))
                {
                    responseContent += "," + content;
                }

                await context.Response.WriteAsync(responseContent);
            };

            string batchRequest = @"--2d958200-beb1-4437-97c5-9d19f7a1d538
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1301336816

GET / HTTP/1.1
Host: example.com


--2d958200-beb1-4437-97c5-9d19f7a1d538
Content-Type: multipart/mixed; boundary=""6aef4f89-41ba-4da5-b733-9100d2318dfa""

--6aef4f89-41ba-4da5-b733-9100d2318dfa
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 1557260198

POST /values HTTP/1.1
Host: example.com
Content-Type: text/plain; charset=utf-8

foo
--6aef4f89-41ba-4da5-b733-9100d2318dfa--

--2d958200-beb1-4437-97c5-9d19f7a1d538--
";


            HttpRequest request     = RequestFactory.Create("Post", "http://example.com/$batch", opt => opt.AddModel("odata", EdmCoreModel.Instance));
            HttpContext httpContext = request.HttpContext;

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            request.Body          = new MemoryStream(requestBytes);
            request.ContentType   = "multipart/mixed; boundary=\"2d958200-beb1-4437-97c5-9d19f7a1d538\"";
            request.ContentLength = 603;
            httpContext.ODataFeature().PrefixName = "odata";
            httpContext.Response.Body = new MemoryStream();

            // Act
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();

            batchHandler.PrefixName = "odata";
            await batchHandler.ProcessBatchAsync(httpContext, next);

            // Assert
            string responseBody = httpContext.Response.ReadBody();

            Assert.Contains("http://example.com/", responseBody);
            Assert.Contains("http://example.com/values,foo", responseBody);
        }
Exemplo n.º 29
0
        public async Task ProcessBatchAsync_DisposesResponseInCaseOfException()
        {
            // Arrange
            RequestDelegate handler = context =>
            {
                HttpRequest request = context.Request;
                if (request.Method.ToLowerInvariant() == "put")
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                }
                else if (request.Method.ToLowerInvariant() == "post")
                {
                    context.Response.WriteAsync("POSTED VALUE");
                }
                else
                {
                    context.Response.WriteAsync("OTHER VALUE");
                }

                return(Task.FromResult(context.Response));
            };

            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler();
            string      batchRequest = @"
--97a4482b-26c6-4551-aed3-85f8b500bbbf
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: 794393547

GET / HTTP/1.1
Host: example.com


--97a4482b-26c6-4551-aed3-85f8b500bbbf
Content-Type: multipart/mixed;boundary=""be13321d-3c7b-4126-aa20-958b2c7a87e0""

--be13321d-3c7b-4126-aa20-958b2c7a87e0
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: -583046506

POST /values HTTP/1.1
Host: example.com


--be13321d-3c7b-4126-aa20-958b2c7a87e0
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: -811158921

PUT /values HTTP/1.1
Host: example.com


--be13321d-3c7b-4126-aa20-958b2c7a87e0--

--97a4482b-26c6-4551-aed3-85f8b500bbbf--
";
            HttpRequest request      = RequestFactory.Create("Post", "http://example.com/$batch", opt => opt.AddModel(EdmCoreModel.Instance));
            HttpContext httpContext  = request.HttpContext;

            byte[] requestBytes = Encoding.UTF8.GetBytes(batchRequest);
            request.Body          = new MemoryStream(requestBytes);
            request.ContentType   = "multipart/mixed;boundary=\"be13321d-3c7b-4126-aa20-958b2c7a87e0\"";
            request.ContentLength = 736;
            httpContext.ODataFeature().PrefixName = "";
            httpContext.Response.Body = new MemoryStream();
            batchHandler.PrefixName   = "";

            // Act
            await batchHandler.ProcessBatchAsync(httpContext, handler);

            // Assert
            string responseBody = httpContext.Response.ReadBody();

            Assert.Contains("POSTED VALUE", responseBody);
            Assert.Contains("400 Bad Request", responseBody);
            Assert.DoesNotContain("OTHER VALUE", responseBody);
        }
Exemplo n.º 30
0
        public async Task ProcessBatchAsync_ContinueOnError(bool enableContinueOnError)
        {
            // Arrange
            MockHttpServer server = new MockHttpServer(async request =>
            {
                string responseContent = request.RequestUri.AbsoluteUri;
                string content         = "";
                if (request.Content != null)
                {
                    content = await request.Content.ReadAsStringAsync();
                    if (!String.IsNullOrEmpty(content))
                    {
                        responseContent += "," + content;
                    }
                }
                HttpResponseMessage responseMessage = new HttpResponseMessage {
                    Content = new StringContent(responseContent)
                };
                if (content.Equals("foo"))
                {
                    responseMessage.StatusCode = HttpStatusCode.BadRequest;
                }
                return(responseMessage);
            });
            UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server);
            HttpRequestMessage          batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
                    new MultipartContent("mixed") // ChangeSet
                    {
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")
                        {
                            Content = new StringContent("foo")
                        })
                    },
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")
                    {
                        Content = new StringContent("bar")
                    }),
                }
            };
            var enableContinueOnErrorconfig = new HttpConfiguration();

            enableContinueOnErrorconfig.EnableODataDependencyInjectionSupport();
            enableContinueOnErrorconfig.EnableContinueOnErrorHeader();
            batchRequest.SetConfiguration(enableContinueOnErrorconfig);
            batchRequest.EnableHttpDependencyInjectionSupport();
            HttpRequestMessage batchRequestWithPrefContinueOnError = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch")
            {
                Content = new MultipartContent("mixed")
                {
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")),
                    new MultipartContent("mixed") // ChangeSet
                    {
                        ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")
                        {
                            Content = new StringContent("foo")
                        })
                    },
                    ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")
                    {
                        Content = new StringContent("bar")
                    }),
                }
            };

            batchRequestWithPrefContinueOnError.EnableHttpDependencyInjectionSupport();
            if (enableContinueOnError)
            {
                batchRequestWithPrefContinueOnError.SetConfiguration(enableContinueOnErrorconfig);
                batchRequestWithPrefContinueOnError.Headers.Add("prefer", "odata.continue-on-error");
            }

            // Act
            var response = await batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None);

            var batchContent   = Assert.IsType <ODataBatchContent>(response.Content);
            var batchResponses = batchContent.Responses.ToArray();
            var responseWithPrefContinueOnError = await batchHandler.ProcessBatchAsync(batchRequestWithPrefContinueOnError, CancellationToken.None);

            var batchContentWithPrefContinueOnError   = Assert.IsType <ODataBatchContent>(responseWithPrefContinueOnError.Content);
            var batchResponsesWithPrefContinueOnError = batchContentWithPrefContinueOnError.Responses.ToArray();

            // Assert
            Assert.Equal(2, batchResponses.Length);
            Assert.Equal(3, batchResponsesWithPrefContinueOnError.Length);
        }