public void NullContentResponse_DoesNotThrow()
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer?$skip=1");
            HttpConfiguration    config    = new HttpConfiguration();

            request.SetConfiguration(config);
            HttpControllerContext controllerContext = new HttpControllerContext(
                config,
                new HttpRouteData(new HttpRoute()),
                request);
            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(
                new HttpConfiguration(),
                "CustomerHighLevel",
                typeof(CustomerHighLevelController));
            HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(
                controllerDescriptor,
                typeof(CustomerHighLevelController).GetMethod("GetIEnumerableOfCustomer"));
            HttpActionContext         actionContext = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context       = new HttpActionExecutedContext(actionContext, null)
            {
                Response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = null
                }
            };

            // Act & Assert
            Assert.DoesNotThrow(() => attribute.OnActionExecuted(context));
        }
        public void Primitives_Can_Be_Used_For_Top_And_Skip(string filter)
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Primitive/?" + filter);
            HttpConfiguration    config    = new HttpConfiguration();

            request.SetConfiguration(config);
            HttpControllerContext     controllerContext    = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            HttpControllerDescriptor  controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "Primitive", typeof(PrimitiveController));
            HttpActionDescriptor      actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(PrimitiveController).GetMethod("GetIEnumerableOfInt"));
            HttpActionContext         actionContext        = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context = new HttpActionExecutedContext(actionContext, null);

            context.Response = new HttpResponseMessage(HttpStatusCode.OK);
            HttpContent expectedResponse = new ObjectContent(typeof(IEnumerable <int>), new List <int>(), new JsonMediaTypeFormatter());

            context.Response.Content = expectedResponse;

            // Act and Assert
            attribute.OnActionExecuted(context);
            HttpResponseMessage response = context.Response;

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedResponse, response.Content);
        }
        public void NonGenericEnumerableReturnType_ReturnsBadRequest()
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/?$skip=1");
            HttpConfiguration    config    = new HttpConfiguration();

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            request.SetConfiguration(config);
            HttpControllerContext     controllerContext    = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            HttpControllerDescriptor  controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerHighLevel", typeof(CustomerHighLevelController));
            HttpActionDescriptor      actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod("GetNonGenericEnumerable"));
            HttpActionContext         actionContext        = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(HttpStatusCode.OK);
            context.Response.Content = new ObjectContent(typeof(IEnumerable), new NonGenericEnumerable(), new JsonMediaTypeFormatter());

            // Act
            attribute.OnActionExecuted(context);
            string responseString = context.Response.Content.ReadAsStringAsync().Result;

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, context.Response.StatusCode);
            Assert.Contains("The query specified in the URI is not valid. Cannot create an EDM model as the action 'EnableQueryAttribute' " +
                            "on controller 'GetNonGenericEnumerable' has a return type 'CustomerHighLevel' that does not implement IEnumerable<T>.",
                            responseString);
        }
        public virtual void QueryableUsesConfiguredAssembliesResolver_For_MappingDerivedTypes()
        {
            // Arrange
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext(
                "http://localhost:8080/QueryCompositionCustomer/?$filter=Id eq 2",
                QueryCompositionCustomerController.CustomerList.AsQueryable());

            ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();

            modelBuilder.EntitySet <QueryCompositionCustomer>(typeof(QueryCompositionCustomer).Name);
            IEdmModel model = modelBuilder.GetEdmModel();

            model.SetAnnotationValue <ClrTypeAnnotation>(model.FindType("System.Web.Http.OData.Query.QueryCompositionCustomer"), null);

            bool called = false;
            Mock <IAssembliesResolver> assembliesResolver = new Mock <IAssembliesResolver>();

            assembliesResolver
            .Setup(r => r.GetAssemblies())
            .Returns(new DefaultAssembliesResolver().GetAssemblies())
            .Callback(() => { called = true; })
            .Verifiable();
            actionExecutedContext.Request.GetConfiguration().Services.Replace(typeof(IAssembliesResolver), assembliesResolver.Object);

            // Act
            attribute.OnActionExecuted(actionExecutedContext);

            // Assert
            Assert.True(called);
        }
Beispiel #5
0
        public void RunQueryableOnAllPossibleTypes(Type type, string queryString)
        {
            int    seed           = RandomSeedGenerator.GetRandomSeed();
            Random r              = new Random(seed);
            Type   generic        = typeof(IEnumerable <>);
            var    collectionType = generic.MakeGenericType(type);

            Type listType = typeof(List <>).MakeGenericType(type);
            var  array    = Activator.CreateInstance(listType);

            EnableQueryAttribute q = new EnableQueryAttribute();
            var configuration      = new HttpConfiguration();

            configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            configuration.Count().Filter().OrderBy().Expand().MaxTop(null).Select();
            configuration.Routes.MapHttpRoute("ApiDefault", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            configuration.EnableDependencyInjection();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://test/api/Objects?" + queryString);

            request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, configuration);
            var controllerContext = new HttpControllerContext(
                configuration,
                configuration.Routes.GetRouteData(request),
                request);
            var actionContext = new HttpActionContext(controllerContext, new ReflectedHttpActionDescriptor()
            {
                Configuration = configuration
            });
            var context = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            context.Response.Content = new ObjectContent(collectionType, array, new JsonMediaTypeFormatter());

            try
            {
                q.OnActionExecuted(context);

                Console.WriteLine(context.Response.Content.ReadAsStringAsync().Result);
                Assert.Equal(HttpStatusCode.OK, context.Response.StatusCode);
            }
            catch (ArgumentException ae)
            {
                // For example:
                // The type 'System.DateTime' of property 'NotAfter' in the
                // 'System.Security.Cryptography.X509Certificates.X509Certificate2' type is not a supported type.
                // Change to use 'System.DateTimeOffset' or ignore this type by calling
                // Ignore<System.Security.Cryptography.X509Certificates.X509Certificate2>()
                // on 'System.Web.OData.Builder.ODataModelBuilder'.
                Assert.True(ae.Message.Contains("The type 'System.DateTime' of property") ||
                            ae.Message.Contains("System.Windows.Forms.AxHost") ||
                            ae.Message.Contains("Found more than one dynamic property container in type"),

                            "The exception should contains \"The type 'System.DateTime' of property\", or " +
                            "\"System.Windows.Forms.AxHost\" or" +
                            "\"Found more than one dynamic property container in type\", but actually, it is:" +
                            ae.Message);
            }
        }
        public void OnActionExecuted_SingleResult_Returns400_IfQueryContainsNonSelectExpand()
        {
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext("http://localhost/?$top=10", new Customer());
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();

            attribute.OnActionExecuted(actionExecutedContext);

            Assert.Equal(HttpStatusCode.BadRequest, actionExecutedContext.Response.StatusCode);
        }
        public void OnActionExecuted_SingleResult_WithMoreThanASingleQueryResult_ThrowsInvalidOperationException()
        {
            // Arrange
            var          customers = CustomerList.AsQueryable();
            SingleResult result    = SingleResult.Create(customers);
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext("http://localhost/", result);
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();

            // Act and Assert
            Assert.Throws <InvalidOperationException>(() => attribute.OnActionExecuted(actionExecutedContext));
        }
        public void OnActionExecuted_SingleResult_ReturnsSingleItemEvenIfThereIsNoSelectExpand()
        {
            Customer     customer     = new Customer();
            SingleResult singleResult = new SingleResult <Customer>(new Customer[] { customer }.AsQueryable());
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext("http://localhost/", singleResult);
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();

            attribute.OnActionExecuted(actionExecutedContext);

            Assert.Equal(HttpStatusCode.OK, actionExecutedContext.Response.StatusCode);
            Assert.Equal(customer, (actionExecutedContext.Response.Content as ObjectContent).Value);
        }
        public void QueryableOnActionUnknownOperatorStartingDollarSignThrows()
        {
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext(
                "http://localhost:8080/QueryCompositionCustomer?$orderby=Name desc&$unknown=12",
                QueryCompositionCustomerController.CustomerList.AsQueryable());

            var exception = Assert.Throws <HttpResponseException>(() => attribute.OnActionExecuted(actionExecutedContext));

            // EnableQueryAttribute will validate and throws
            Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
        }
        public void QueryableOnActionUnknownOperatorIsAllowed()
        {
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext(
                "http://localhost:8080/?$orderby=$it desc&unknown=12",
                Enumerable.Range(0, 5).AsQueryable());

            // unsupported operator - ignored
            attribute.OnActionExecuted(actionExecutedContext);

            List <int> result = actionExecutedContext.Response.Content.ReadAsAsync <List <int> >().Result;

            Assert.Equal(new[] { 4, 3, 2, 1, 0 }, result);
        }
        public void OnActionExecuted_SingleResult_WithEmptyQueryResult_SetsNotFoundResponse()
        {
            // Arrange
            var          customers = Enumerable.Empty <Customer>().AsQueryable();
            SingleResult result    = SingleResult.Create(customers);
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext("http://localhost/", result);
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();

            // Act
            attribute.OnActionExecuted(actionExecutedContext);

            // Assert
            Assert.Equal(HttpStatusCode.NotFound, actionExecutedContext.Response.StatusCode);
        }
        public void OnActionExecuted_Works_WithPath()
        {
            // Arrange
            Customer     customer     = new Customer();
            SingleResult singleResult = new SingleResult <Customer>(new[] { customer }.AsQueryable());
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext("http://localhost/", singleResult);
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();
            HttpRequestMessage        request = actionExecutedContext.Request;

            request.ODataProperties().Path = new ODataPath(new EntitySetPathSegment("Customer"));

            // Act
            attribute.OnActionExecuted(actionExecutedContext);

            // Assert
            Assert.Equal(HttpStatusCode.OK, actionExecutedContext.Response.StatusCode);
            Assert.Equal(customer, ((ObjectContent)actionExecutedContext.Response.Content).Value);
        }
        public void OnActionExecuted_SingleResult_WithMoreThanASingleQueryResult_ReturnsBadRequest()
        {
            // Arrange
            var          customers = CustomerList.AsQueryable();
            SingleResult result    = SingleResult.Create(customers);
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext("http://localhost/", result);
            EnableQueryAttribute      attribute             = new EnableQueryAttribute();

            // Act
            attribute.OnActionExecuted(actionExecutedContext);
            string responseString = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, actionExecutedContext.Response.StatusCode);
            Assert.Contains("The query specified in the URI is not valid. The action 'Bar' on controller 'FooController' " +
                            "returned a SingleResult containing more than one element. SingleResult must have zero or one elements.",
                            responseString);
        }
        public void OnActionExecuted_SingleResult_WithEmptyQueryResult_SetsContentNullIfODataPathIsPresent()
        {
            // Arrange
            var          customers = Enumerable.Empty <Customer>().AsQueryable();
            SingleResult result    = SingleResult.Create(customers);
            HttpActionExecutedContext actionExecutedContext = GetActionExecutedContext("http://localhost/", result);

            actionExecutedContext.Request.ODataProperties().Path = new ODataPath(new EntitySetPathSegment("C"));
            EnableQueryAttribute attribute = new EnableQueryAttribute();

            // Act
            attribute.OnActionExecuted(actionExecutedContext);

            // Assert
            ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;

            Assert.NotNull(content);
            Assert.Null(content.Value);
        }
        public void CountValueReturnsAsContent_CountRequest()
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(
                HttpMethod.Get,
                "http://localhost/DollarCountEntities(5)/StringCollectionProp/$count");

            request.ODataProperties().Path = new ODataPath(new CountPathSegment());
            HttpConfiguration config       = new HttpConfiguration();

            request.SetConfiguration(config);
            HttpControllerContext controllerContext = new HttpControllerContext(
                config,
                new HttpRouteData(new HttpRoute()),
                request);
            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(
                new HttpConfiguration(),
                "DollarCountEntities",
                typeof(ODataCountTest.DollarCountEntitiesController));
            HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(
                controllerDescriptor,
                typeof(ODataCountTest.DollarCountEntitiesController).GetMethod("GetStringCollectionProp"));
            HttpActionContext         actionContext = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context       = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(HttpStatusCode.OK);
            context.Response.Content = new ObjectContent(
                typeof(IEnumerable <string>),
                new[] { "123", "abc", "A1B2" },
                new JsonMediaTypeFormatter());

            // Act
            attribute.OnActionExecuted(context);

            // Assert
            Assert.Equal(HttpStatusCode.OK, context.Response.StatusCode);
            Assert.True(context.Response.Content is ObjectContent);
            Assert.Equal(3L, ((ObjectContent)context.Response.Content).Value);
        }
        public void UnknownQueryNotStartingWithDollarSignWorks()
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/?select");
            HttpConfiguration    config    = new HttpConfiguration();

            request.SetConfiguration(config);
            HttpControllerContext     controllerContext    = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            HttpControllerDescriptor  controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerHighLevel", typeof(CustomerHighLevelController));
            HttpActionDescriptor      actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod("Get"));
            HttpActionContext         actionContext        = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(HttpStatusCode.OK);
            context.Response.Content = new ObjectContent(typeof(IEnumerable <Customer>), new List <Customer>(), new JsonMediaTypeFormatter());

            // Act and Assert
            attribute.OnActionExecuted(context);

            Assert.Equal(HttpStatusCode.OK, context.Response.StatusCode);
        }
        public void NonObjectContentResponse_ThrowsArgumentException()
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer?$skip=1");
            HttpConfiguration    config    = new HttpConfiguration();

            request.SetConfiguration(config);
            HttpControllerContext     controllerContext    = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            HttpControllerDescriptor  controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerHighLevel", typeof(CustomerHighLevelController));
            HttpActionDescriptor      actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod("GetIEnumerableOfCustomer"));
            HttpActionContext         actionContext        = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(HttpStatusCode.OK);
            context.Response.Content = new StreamContent(new MemoryStream());

            // Act & Assert
            Assert.ThrowsArgument(
                () => attribute.OnActionExecuted(context),
                "actionExecutedContext",
                "Queries can not be applied to a response content of type 'System.Net.Http.StreamContent'. The response content must be an ObjectContent.");
        }
        public void NonGenericEnumerableReturnTypeThrows()
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer/?$skip=1");
            HttpConfiguration    config    = new HttpConfiguration();

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            request.SetConfiguration(config);
            HttpControllerContext     controllerContext    = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            HttpControllerDescriptor  controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerHighLevel", typeof(CustomerHighLevelController));
            HttpActionDescriptor      actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod("GetNonGenericEnumerable"));
            HttpActionContext         actionContext        = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(HttpStatusCode.OK);
            context.Response.Content = new ObjectContent(typeof(IEnumerable), new NonGenericEnumerable(), new JsonMediaTypeFormatter());

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => attribute.OnActionExecuted(context),
                "Cannot create an EDM model as the action 'EnableQueryAttribute' on controller 'GetNonGenericEnumerable' has a return type 'CustomerHighLevel' that does not implement IEnumerable<T>.");
        }
        public void DifferentReturnTypeWorks(string methodName, object responseObject, bool isNoOp)
        {
            // Arrange
            EnableQueryAttribute attribute = new EnableQueryAttribute();
            HttpRequestMessage   request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customer?$orderby=Name");
            HttpConfiguration    config    = new HttpConfiguration();

            request.SetConfiguration(config);
            HttpControllerContext     controllerContext    = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            HttpControllerDescriptor  controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "CustomerHighLevel", typeof(CustomerHighLevelController));
            HttpActionDescriptor      actionDescriptor     = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(CustomerHighLevelController).GetMethod(methodName));
            HttpActionContext         actionContext        = new HttpActionContext(controllerContext, actionDescriptor);
            HttpActionExecutedContext context = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(HttpStatusCode.OK);
            context.Response.Content = new ObjectContent(typeof(IEnumerable <Customer>), responseObject, new JsonMediaTypeFormatter());

            // Act and Assert
            attribute.OnActionExecuted(context);

            Assert.Equal(HttpStatusCode.OK, context.Response.StatusCode);
            Assert.True(context.Response.Content is ObjectContent);
            Assert.Equal(isNoOp, ((ObjectContent)context.Response.Content).Value == responseObject);
        }
Beispiel #20
0
        public void RunQueryableOnAllPossibleTypes(Type type, string queryString)
        {
            int    seed           = RandomSeedGenerator.GetRandomSeed();
            Random r              = new Random(seed);
            Type   generic        = typeof(IEnumerable <>);
            var    collectionType = generic.MakeGenericType(type);

            Type listType = typeof(List <>).MakeGenericType(type);
            var  array    = Activator.CreateInstance(listType);

            EnableQueryAttribute q = new EnableQueryAttribute();
            var configuration      = new HttpConfiguration();

            configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            configuration.Routes.MapHttpRoute("ApiDefault", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            var request = new HttpRequestMessage(HttpMethod.Get, "http://test/api/Objects?" + queryString);

            request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, configuration);
            var controllerContext = new HttpControllerContext(
                configuration,
                configuration.Routes.GetRouteData(request),
                request);
            var actionContext = new HttpActionContext(controllerContext, new ReflectedHttpActionDescriptor()
            {
                Configuration = configuration
            });
            var context = new HttpActionExecutedContext(actionContext, null);

            context.Response         = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            context.Response.Content = new ObjectContent(collectionType, array, new JsonMediaTypeFormatter());

            q.OnActionExecuted(context);

            Console.WriteLine(context.Response.Content.ReadAsStringAsync().Result);
            Assert.Equal(HttpStatusCode.OK, context.Response.StatusCode);
        }