Exemplo n.º 1
0
        public static void VerifySelectOperationWithAutoRedirectMode(string requestUri, string operationName, UriAndMethodOperationSelector httpOperationSelector, bool shouldAutoRedirect)
        {
            string             matchedOperationName;
            bool               matchDifferByTrailingSlash;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);
            bool               result  = httpOperationSelector.TrySelectOperation(request, out matchedOperationName, out matchDifferByTrailingSlash);

            Assert.IsTrue(result);
            Assert.AreEqual(matchedOperationName, operationName, String.Format("request {0} should match the operation {1}", requestUri, operationName));
            Assert.AreEqual(matchDifferByTrailingSlash, shouldAutoRedirect);

            Uri        originalUri = new Uri(requestUri);
            UriBuilder uriBuilder  = new UriBuilder(originalUri);

            uriBuilder.Path = originalUri.AbsolutePath.EndsWith("/") ? uriBuilder.Path.TrimEnd('/') : uriBuilder.Path + "/";
            Uri backSlashAlteredUri = uriBuilder.Uri;

            if (!shouldAutoRedirect)
            {
                matchedOperationName = httpOperationSelector.SelectOperation(request);
                Assert.AreEqual(matchedOperationName, operationName, String.Format("request {0} should match the operation {1}", requestUri, operationName));
            }
            else
            {
                ExceptionAssert.Throws <HttpResponseException>(
                    () => httpOperationSelector.SelectOperation(request),
                    (responseException) =>
                {
                    HttpResponseMessage expectedResponse = StandardHttpResponseMessageBuilder.CreateTemporaryRedirectResponse(request, originalUri, backSlashAlteredUri);
                    HttpAssert.AreEqual(expectedResponse, responseException.Response);
                });
            }
        }
Exemplo n.º 2
0
        public async Task CreateItem_MissingItem_Returns201()
        {
            var item = new HUnit
            {
                Id   = Guid.NewGuid().ToString("N"),
                Data = "create-item-missing-item-returns-201"
            };
            var response = await SendRequestToServer <HUnit>(HttpMethod.Post, "tables/hunits", item);

            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            var actual = await GetValueFromResponse <HUnit>(response);

            Assert.AreEqual(item.Id, actual.Id);
            Assert.AreEqual(item.Data, actual.Data);
            Assert.IsTrue(actual.Version.Length > 0);
            HttpAssert.IsWithin(DateTimeOffset.UtcNow, actual.UpdatedAt, 1000);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);

            var dbItem = GetItemFromDb <HUnit>(item.Id);

            Assert.IsNotNull(dbItem);
            Assert.AreEqual(item.Data, dbItem.Data);
        }
Exemplo n.º 3
0
        public async Task CreateItem_MissingId_Returns201_AndCreatesId()
        {
            var item = new HUnit
            {
                Data = "create-item-missing-id-returns-201"
            };
            var response = await SendRequestToServer <HUnit>(HttpMethod.Post, "tables/hunits", item);

            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            var actual = await GetValueFromResponse <HUnit>(response);

            Assert.IsNotNull(actual.Id);                // Check existence of Id
            Assert.IsNotNull(new Guid(actual.Id));      // Make sure it is a real GUID
            Assert.AreEqual(item.Data, actual.Data);
            Assert.IsTrue(actual.Version.Length > 0);
            HttpAssert.IsWithin(DateTimeOffset.UtcNow, actual.UpdatedAt, 1000);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);

            var dbItem = GetItemFromDb <HUnit>(actual.Id);

            Assert.IsNotNull(dbItem);
            Assert.AreEqual(item.Data, dbItem.Data);
        }
Exemplo n.º 4
0
        public async Task ReplaceItem_PreconditionsSucceed_Returns200()
        {
            var item         = GetItemFromDb <HUnit>("hunit-8");
            var originalData = item.Data; item.Data = "Replaced";
            var response     = await SendRequestToServer <HUnit>(HttpMethod.Put, $"/tables/hunits/{item.Id}", item, new Dictionary <string, string>
            {
                { "If-Match", ETag.FromByteArray(item.Version) }
            });

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var actual = await GetValueFromResponse <HUnit>(response);

            Assert.AreEqual(item.Id, actual.Id);
            Assert.AreEqual(item.Data, actual.Data);
            Assert.IsTrue(actual.Version.Length > 0);
            HttpAssert.IsWithin(DateTimeOffset.UtcNow, actual.UpdatedAt, 1000);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);

            var dbItem = GetItemFromDb <HUnit>(item.Id);

            Assert.IsNotNull(dbItem);
            Assert.AreEqual(item.Data, dbItem.Data);
        }
Exemplo n.º 5
0
        public async Task ReplaceItem_ValidId_Returns200()
        {
            var item = new HUnit()
            {
                Id = "hunit-6", Data = "Replaced"
            };
            var response = await SendRequestToServer <HUnit>(HttpMethod.Put, $"/tables/hunits/{item.Id}", item);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var actual = await GetValueFromResponse <HUnit>(response);

            Assert.AreEqual(item.Id, actual.Id);
            Assert.AreEqual(item.Data, actual.Data);
            Assert.IsTrue(actual.Version.Length > 0);
            HttpAssert.IsWithin(DateTimeOffset.UtcNow, actual.UpdatedAt, 1000);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);

            var dbItem = GetItemFromDb <HUnit>(item.Id);

            Assert.IsNotNull(dbItem);
            Assert.AreEqual(item.Data, dbItem.Data);
        }
        public void GetHttpResponseMessageCallsPipelineInfo()
        {
            HttpRequestMessage  request  = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage()
            {
                RequestMessage = request
            };

            HttpOperationHandler[]    handlers  = new HttpOperationHandler[0];
            SHttpOperationDescription operation = new SHttpOperationDescription()
            {
                ReturnValue = HttpParameter.ResponseMessage
            };
            OperationHandlerPipelineInfo  pipelineInfo     = new OperationHandlerPipelineInfo(handlers, handlers, operation);
            MOperationHandlerPipelineInfo molePipelineInfo = new MOperationHandlerPipelineInfo(pipelineInfo);

            molePipelineInfo.GetEmptyPipelineValuesArray = () => new object[0];
            molePipelineInfo.SetHttpRequestMessageHttpRequestMessageObjectArray = (req, values) => { };
            molePipelineInfo.GetHttpResponseMessageObjectArray = (values) => response;
            OperationHandlerPipelineContext context = new OperationHandlerPipelineContext(pipelineInfo, request);

            HttpResponseMessage responseReturned = context.GetHttpResponseMessage();

            Assert.IsNotNull(responseReturned, "HttpResponseMessage was not returned.");
            HttpAssert.AreEqual(response, responseReturned);
        }
        public void Constructor()
        {
            HttpOperationHandler[]    handlers  = new HttpOperationHandler[0];
            SHttpOperationDescription operation = new SHttpOperationDescription()
            {
                ReturnValue = HttpParameter.ResponseMessage
            };
            OperationHandlerPipelineInfo  pipelineInfo     = new OperationHandlerPipelineInfo(handlers, handlers, operation);
            MOperationHandlerPipelineInfo molePipelineInfo = new MOperationHandlerPipelineInfo(pipelineInfo);
            HttpRequestMessage            requestAtCall    = null;

            object[] valuesAtCall = null;

            molePipelineInfo.GetEmptyPipelineValuesArray = () => new object[0];
            molePipelineInfo.SetHttpRequestMessageHttpRequestMessageObjectArray = (req, values) =>
            {
                requestAtCall = req;
                valuesAtCall  = values;
            };
            HttpRequestMessage request = new HttpRequestMessage();

            OperationHandlerPipelineContext context = new OperationHandlerPipelineContext(pipelineInfo, request);

            Assert.IsNotNull(requestAtCall, "HttpRequestMessage was not set in pipeline info.");
            Assert.IsNotNull(valuesAtCall, "Values were not set in pipeline info.");
            HttpAssert.AreEqual(request, requestAtCall);
        }
Exemplo n.º 8
0
        public async Task PatchItem_PreconditionsFail_Returns412()
        {
            var item = await GetItemFromDb <HUnit>("hunit-13");

            var patchDoc = @"[{ ""op"": ""replace"", ""path"": ""/Data"", ""value"": ""Replaced"" }]";
            var response = await SendRequestToServer(HttpMethod.Patch, $"/tables/hunits/{item.Id}", patchDoc, new Dictionary <string, string>
            {
                { "If-None-Match", ETag.FromByteArray(item.Version) }
            });

            Assert.AreEqual(HttpStatusCode.PreconditionFailed, response.StatusCode);

            var actual = await GetValueFromResponse <HUnit>(response);

            Assert.AreEqual(item.Id, actual.Id);
            Assert.AreEqual(item.Data, actual.Data);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);

            var dbItem = await GetItemFromDb <HUnit>(item.Id);

            Assert.IsNotNull(dbItem);
            Assert.AreEqual(item.Data, dbItem.Data);
        }
Exemplo n.º 9
0
        public async Task PatchItem_PreconditionsSucceed_Returns200()
        {
            var item = await GetItemFromDb <HUnit>("hunit-14");

            var patchDoc = @"[{ ""op"": ""replace"", ""path"": ""/Data"", ""value"": ""Replaced"" }]";
            var response = await SendRequestToServer(HttpMethod.Patch, $"/tables/hunits/{item.Id}", patchDoc, new Dictionary <string, string>
            {
                { "If-Match", ETag.FromByteArray(item.Version) }
            });

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var actual = await GetValueFromResponse <HUnit>(response);

            Assert.AreEqual(item.Id, actual.Id);
            Assert.AreEqual("Replaced", actual.Data);
            Assert.IsTrue(actual.Version.Length > 0);
            HttpAssert.IsWithin(DateTimeOffset.UtcNow, actual.UpdatedAt, 1000);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);

            var dbItem = await GetItemFromDb <HUnit>(item.Id);

            Assert.IsNotNull(dbItem);
            Assert.AreEqual("Replaced", dbItem.Data);
        }
Exemplo n.º 10
0
        public async Task ReadItemAsync_SoftDelete_ValidItem_Returns200()
        {
            var response = await SendRequestToServer <Movie>(HttpMethod.Get, $"/tables/rmovies/rmovie-6", null);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var actual = await GetValueFromResponse <Movie>(response);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);
            Assert.IsTrue(Movie6.Equals(actual));
        }
        public void SelectOperationThrowsWithNoOperations()
        {
            Uri baseAddress = new Uri("http://localhost");
            List <HttpOperationDescription> operations = new List <HttpOperationDescription>();

            UriAndMethodOperationSelector selector = new UriAndMethodOperationSelector(baseAddress, operations);
            HttpRequestMessage            request  = new HttpRequestMessage();

            ExceptionAssert.Throws <HttpResponseException>(
                () => selector.SelectOperation(request),
                (responseException) =>
            {
                HttpResponseMessage expectedResponse = StandardHttpResponseMessageBuilder.CreateNotFoundResponse(request, null);
                HttpAssert.AreEqual(expectedResponse, responseException.Response);
            });
        }
Exemplo n.º 12
0
        public void OnDeserializeRequestExecutesRequestPipeline()
        {
            SHttpOperationDescription operation = new SHttpOperationDescription()
            {
                CallBase = true, ReturnValue = HttpParameter.ResponseMessage
            };
            IEnumerable <HttpOperationHandler> emptyHandlers = Enumerable.Empty <HttpOperationHandler>();
            OperationHandlerPipeline           pipeline      = new OperationHandlerPipeline(emptyHandlers, emptyHandlers, operation);
            MOperationHandlerPipeline          molePipeline  = new MOperationHandlerPipeline(pipeline);

            molePipeline.BehaveAsDefaultValue();

            MOperationHandlerPipelineContext moleContext = new MOperationHandlerPipelineContext();

            HttpRequestMessage setRequest = null;

            object[] setValues = null;
            OperationHandlerPipelineContext setContext = null;

            molePipeline.ExecuteRequestPipelineHttpRequestMessageObjectArray = (request, values) =>
            {
                setRequest = request;
                setValues  = values;
                return(setContext = moleContext);
            };

            OperationHandlerFormatter formatter = new OperationHandlerFormatter(molePipeline);
            IDispatchMessageFormatter dispatchMessageFormatter = (IDispatchMessageFormatter)formatter;

            Uri uri = new Uri("http://somehost/Fred");
            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, uri);

            httpRequest.Content = new StringContent("");

            Message message = httpRequest.ToMessage();

            object[] parameters = new object[0];
            dispatchMessageFormatter.DeserializeRequest(message, parameters);

            HttpAssert.AreEqual(httpRequest, setRequest);
            Assert.IsNotNull(setValues, "Input values were not passed to the pipeline.");
            Assert.AreEqual(0, ((object[])setValues).Length, "Incorrect number of values.");
            Assert.IsNotNull(setContext, "Context was not set.");
        }
        public void SelectOperationThrowsWithUriMatchingButMethodNotMatching()
        {
            HttpOperationAssert.Execute <UriTemplateService>(
                (IEnumerable <HttpOperationDescription> operations) =>
            {
                Uri baseAddress = new Uri("http://localhost/baseAddress");
                UriAndMethodOperationSelector selector = new UriAndMethodOperationSelector(baseAddress, operations, TrailingSlashMode.Ignore);

                bool oneMethodNotAllowedFound = false;

                foreach (HttpOperationDescription operation in operations)
                {
                    List <HttpMethod> otherAllowedMethods = operations
                                                            .Where(otherOperation => otherOperation.GetUriTemplate().IsEquivalentTo(operation.GetUriTemplate()))
                                                            .Select(otherOperation => otherOperation.GetHttpMethod())
                                                            .ToList();

                    if (otherAllowedMethods.Count > 1)
                    {
                        UriTemplate uriTemplate  = operation.GetUriTemplate();
                        string expectedOperation = operation.Name;
                        string[] uriParameters   = uriTemplate.PathSegmentVariableNames
                                                   .Concat(uriTemplate.QueryValueVariableNames)
                                                   .ToArray();
                        Uri requestUri = uriTemplate.BindByPosition(baseAddress, uriParameters);

                        foreach (HttpMethod method in HttpTestData.AllHttpMethods.Except(otherAllowedMethods))
                        {
                            HttpRequestMessage request = new HttpRequestMessage(method, requestUri);
                            ExceptionAssert.Throws <HttpResponseException>(
                                () => selector.SelectOperation(request),
                                (responseException) =>
                            {
                                HttpResponseMessage expectedResponse = StandardHttpResponseMessageBuilder.CreateMethodNotAllowedResponse(request, otherAllowedMethods, null);
                                HttpAssert.AreEqual(expectedResponse, responseException.Response);
                                oneMethodNotAllowedFound = true;
                            });
                        }
                    }
                }

                Assert.IsTrue(oneMethodNotAllowedFound, "No interesting test cases actually executed.");
            });
        }
        public void SelectOperationThrowsWithMatchDifferingByTrailingSlash()
        {
            HttpOperationAssert.Execute <UriTemplateService>(
                (operations) =>
            {
                Uri baseAddress = new Uri("http://localhost/baseAddress");
                UriAndMethodOperationSelector selector = new UriAndMethodOperationSelector(baseAddress, operations, TrailingSlashMode.AutoRedirect);

                foreach (HttpOperationDescription operation in operations)
                {
                    UriTemplate uriTemplate  = operation.GetUriTemplate();
                    HttpMethod method        = operation.GetHttpMethod();
                    string expectedOperation = operation.Name;

                    string[] uriParameters = uriTemplate.PathSegmentVariableNames
                                             .Concat(uriTemplate.QueryValueVariableNames)
                                             .ToArray();
                    Uri requestUri          = uriTemplate.BindByPosition(baseAddress, uriParameters);
                    UriBuilder uriBuilder   = new UriBuilder(requestUri);
                    uriBuilder.Path         = requestUri.AbsolutePath.EndsWith("/") ? uriBuilder.Path.TrimEnd('/') : uriBuilder.Path + "/";
                    Uri backSlashAlteredUri = uriBuilder.Uri;

                    // Because UriTemplate.BindByPosition always adds a backslash for templates "" and "/",
                    //  the original requestUri is actually the correct backSlashAlteredUri in these cases.
                    if (uriTemplate.ToString() == "" || uriTemplate.ToString() == "/")
                    {
                        Uri temp            = requestUri;
                        requestUri          = backSlashAlteredUri;
                        backSlashAlteredUri = temp;
                    }

                    HttpRequestMessage request = new HttpRequestMessage(method, backSlashAlteredUri);

                    ExceptionAssert.Throws <HttpResponseException>(
                        () => selector.SelectOperation(request),
                        (responseException) =>
                    {
                        HttpResponseMessage expectedResponse = StandardHttpResponseMessageBuilder.CreateTemporaryRedirectResponse(request, backSlashAlteredUri, requestUri);
                        HttpAssert.AreEqual(expectedResponse, responseException.Response);
                    });
                }
            });
        }
Exemplo n.º 15
0
        public async Task ReadItemAsync_PreconditionsSucceed_Returns200()
        {
            var firstResponse = await SendRequestToServer <Movie>(HttpMethod.Get, $"/tables/movies/{Movie4.Id}", null);

            Assert.AreEqual(HttpStatusCode.OK, firstResponse.StatusCode);
            var firstActual = await GetValueFromResponse <Movie>(firstResponse);

            var response = await SendRequestToServer <Movie>(HttpMethod.Get, $"/tables/movies/{Movie4.Id}", null, new Dictionary <string, string>
            {
                { "If-Match", ETag.FromByteArray(firstActual.Version) }
            });

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            var actual = await GetValueFromResponse <Movie>(response);

            HttpAssert.AreEqual(actual.Version, response.Headers.ETag);
            HttpAssert.Match(actual.UpdatedAt, response.Content.Headers.LastModified);
            Assert.IsTrue(Movie4.Equals(actual));
        }