コード例 #1
0
ファイル: MockContainer.cs プロジェクト: droyad/OData.WebApi
        private void InitializeConfiguration(Action <IContainerBuilder> action)
        {
            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = HttpRouteCollectionExtensions.RouteName;

            _rootContainer = configuration.CreateODataRootContainer(routeName, action);
        }
コード例 #2
0
        /// <summary>
        /// Initializes a new instance of the routing configuration class.
        /// </summary>
        /// <returns>A new instance of the routing configuration class.</returns>
        public static HttpResponse Create(HttpStatusCode statusCode, string content = null)
        {
            // Add the options services.
            IRouteBuilder config = RoutingConfigurationFactory.CreateWithRootContainer("OData");

            // Create a new context and assign the services.
            HttpContext context = new DefaultHttpContext();

            context.RequestServices = config.ServiceProvider;
            //context.ODataFeature().RequestContainer = provider;

            // Get response and return it.
            HttpResponse response = context.Response;

            response.StatusCode = (int)statusCode;

            // Add content
            if (!string.IsNullOrEmpty(content))
            {
                byte[] byteArray = Encoding.ASCII.GetBytes(content);
                using (MemoryStream contentStream = new MemoryStream(byteArray))
                {
                    contentStream.CopyTo(response.Body);
                }
            }

            return(response);
        }
コード例 #3
0
        public SelectExpandTest()
        {
            _configuration = RoutingConfigurationFactory.CreateWithTypes(
                new[]
            {
                typeof(SelectExpandTestCustomersController), typeof(SelectExpandTestCustomersAliasController),
                typeof(PlayersController), typeof(NonODataSelectExpandTestCustomersController),
                typeof(AttributedSelectExpandCustomersController), typeof(SelectExpandTestCustomer),
                typeof(SelectExpandTestSpecialCustomer), typeof(SelectExpandTestCustomerWithAlias),
                typeof(SelectExpandTestOrder), typeof(SelectExpandTestSpecialOrder),
                typeof(SelectExpandTestSpecialOrderWithAlias),
                typeof(ReferenceNavigationPropertyExpandFilterController),
            });

            _configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            _configuration.Count().Filter().OrderBy().Expand().MaxTop(null).Select();

            _configuration.MapODataServiceRoute("odata", "odata", GetModel());
            _configuration.MapODataServiceRoute("odata-inheritance", "odata-inheritance", GetModelWithInheritance());
            _configuration.MapODataServiceRoute("odata-alias", "odata-alias", GetModelWithCustomerAlias());
            _configuration.MapODataServiceRoute(
                "odata-alias2-inheritance",
                "odata-alias2-inheritance",
                GetModelWithCustomerAliasAndInheritance());
            _configuration.MapODataServiceRoute("odata2", "odata2", GetModelWithOperations());
            _configuration.MapODataServiceRoute("odata-expandfilter", "odata-expandfilter", GetModelWithReferenceNavigationPropertyFilter());
            _configuration.Routes.MapHttpRoute("api", "api/{controller}", new { controller = "NonODataSelectExpandTestCustomers" });
            _configuration.EnableDependencyInjection();

            HttpServer server = new HttpServer(_configuration);

            _client = new HttpClient(server);
        }
コード例 #4
0
        /// <summary>
        /// Initializes a new instance of the routing configuration class.
        /// </summary>
        /// <returns>A new instance of the routing configuration class.</returns>
        public static HttpRequest Create(IRouteBuilder routeBuilder = null, string routeName = null)
        {
            // Add the options services.
            string useRouteName = (routeName == null) ? "OData" : routeName;

            if (routeBuilder == null)
            {
                routeBuilder = RoutingConfigurationFactory.CreateWithRootContainer(useRouteName);
            }

            // Create a new context and assign the services.
            HttpContext context = new DefaultHttpContext();

            context.RequestServices = routeBuilder.ServiceProvider;

            // Ensure there is route data for the routing tests.
            var routeContext = new RouteContext(context);

            context.Features[typeof(IRoutingFeature)] = new RoutingFeature()
            {
                RouteData = routeContext.RouteData,
            };

            // Assign the route and get the request container, which will initialize
            // the request container if one does not exists.
            context.Request.ODataFeature().RouteName = useRouteName;
            IPerRouteContainer perRouteContainer     = routeBuilder.ServiceProvider.GetRequiredService <IPerRouteContainer>();

            if (!perRouteContainer.HasODataRootContainer(useRouteName))
            {
                Action <IContainerBuilder> builderAction   = ODataRouteBuilderExtensions.ConfigureDefaultServices(routeBuilder, null);
                IServiceProvider           serviceProvider = perRouteContainer.CreateODataRootContainer(useRouteName, builderAction);
            }

            // Add some routing info
            IRouter   defaultRoute = routeBuilder.Routes.FirstOrDefault();
            RouteData routeData    = new RouteData();

            if (defaultRoute != null)
            {
                routeData.Routers.Add(defaultRoute);
            }
            else
            {
                var resolver = routeBuilder.ServiceProvider.GetRequiredService <IInlineConstraintResolver>();
                routeData.Routers.Add(new ODataRoute(routeBuilder.DefaultHandler, useRouteName, null, new ODataPathRouteConstraint(useRouteName), resolver));
            }

            var mockAction = new Mock <ActionDescriptor>();
            ActionDescriptor actionDescriptor = mockAction.Object;

            ActionContext actionContext = new ActionContext(context, routeData, actionDescriptor);

            IActionContextAccessor actionContextAccessor = context.RequestServices.GetRequiredService <IActionContextAccessor>();

            actionContextAccessor.ActionContext = actionContext;

            // Get request and return it.
            return(context.Request);
        }
コード例 #5
0
        public async Task SendAsync_ReturnsNotFoundForNullEntityResponse()
        {
            // Arrange
            Mock <MediaTypeFormatter> formatter = new Mock <MediaTypeFormatter>();

            formatter.Setup(f => f.CanWriteType(It.IsAny <Type>())).Returns(true);

            HttpResponseMessage originalResponse = new HttpResponseMessage(HttpStatusCode.OK);

            originalResponse.Content = new ObjectContent(typeof(string), null, formatter.Object);

            ODataNullValueMessageHandler handler = new ODataNullValueMessageHandler
            {
                InnerHandler = new TestMessageHandler(originalResponse)
            };

            var                configuration = RoutingConfigurationFactory.Create();
            ODataPath          path          = new DefaultODataPathHandler().Parse(BuildModel(), "http://localhost/any", "Customers(3)");
            HttpRequestMessage request       = RequestFactory.Create(HttpMethod.Get, "http://localhost/any", configuration);

            request.ODataContext().Path = path;

            // Act
            HttpResponseMessage response = await handler.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
コード例 #6
0
        public async Task ExtensionResolver_Works_EnumPrefixFree_QueryOption(string query, bool enableEnumPrefix, HttpStatusCode statusCode, string output)
        {
            // Arrange
            IEdmModel        model    = GetEdmModel();
            var              config   = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(ParserExtenstionCustomersController) });
            ODataUriResolver resolver = new ODataUriResolver();

            if (enableEnumPrefix)
            {
                resolver = new StringAsEnumResolver();
            }

            config.MapODataServiceRoute("odata", "odata",
                                        builder =>
                                        builder.AddService(ServiceLifetime.Singleton, sp => model)
                                        .AddService <IEnumerable <IODataRoutingConvention> >(ServiceLifetime.Singleton, sp =>
                                                                                             ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata", config))
                                        .AddService(ServiceLifetime.Singleton, sp => resolver));
            HttpClient client = new HttpClient(new HttpServer(config));

            // Act
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
                                                                String.Format("http://localhost/odata/ParserExtenstionCustomers?{0}", query));
            HttpResponseMessage response = await client.SendAsync(request);

            // Assert
            Assert.Equal(statusCode, response.StatusCode);

            if (statusCode == HttpStatusCode.OK)
            {
                JObject content = await response.Content.ReadAsAsync <JObject>();

                Assert.Equal(output, String.Join(",", content["value"].Select(e => e["Id"])));
            }
        }
コード例 #7
0
        public async Task ExtensionResolver_Works_EnumPrefixFree(string parameter, bool enableEnumPrefix, HttpStatusCode statusCode)
        {
            // Arrange
            IEdmModel        model    = GetEdmModel();
            var              config   = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(ParserExtenstionCustomersController) });
            ODataUriResolver resolver = new ODataUriResolver();

            if (enableEnumPrefix)
            {
                resolver = new StringAsEnumResolver();
            }

            config.MapODataServiceRoute("odata", "odata",
                                        builder =>
                                        builder.AddService(ServiceLifetime.Singleton, sp => model)
                                        .AddService <IEnumerable <IODataRoutingConvention> >(ServiceLifetime.Singleton, sp =>
                                                                                             ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata", config))
                                        .AddService(ServiceLifetime.Singleton, sp => resolver));
            HttpClient client = new HttpClient(new HttpServer(config));

            // Act
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
                                                                String.Format("http://localhost/odata/ParserExtenstionCustomers/Default.GetCustomerByGender({0})", parameter));
            HttpResponseMessage response = await client.SendAsync(request);

            // Assert
            Assert.Equal(statusCode, response.StatusCode);

            if (statusCode == HttpStatusCode.OK)
            {
                Assert.Equal("GetCustomerByGender/Male", (response.Content as ObjectContent <string>).Value);
            }
        }
コード例 #8
0
ファイル: MockContainer.cs プロジェクト: droyad/OData.WebApi
        private void InitializeConfiguration(Action <IContainerBuilder> action)
        {
            var                        configuration     = RoutingConfigurationFactory.Create();
            string                     routeName         = HttpRouteCollectionExtensions.RouteName;
            IPerRouteContainer         perRouteContainer = configuration.ServiceProvider.GetRequiredService <IPerRouteContainer>();
            Action <IContainerBuilder> builderAction     = ODataRouteBuilderExtensions.ConfigureDefaultServices(configuration, action);

            _rootContainer = perRouteContainer.CreateODataRootContainer(routeName, builderAction);
        }
コード例 #9
0
        private static HttpClient GetClient(DependencyInjectionModel instance)
        {
            var       config = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(DependencyInjectionModelsController) });
            IEdmModel model  = GetEdmModel();

            config.MapODataServiceRoute("odata", "odata", builder =>
                                        builder.AddService(ServiceLifetime.Singleton, sp => instance)
                                        .AddService(ServiceLifetime.Singleton, sp => model)
                                        .AddService <IEnumerable <IODataRoutingConvention> >(ServiceLifetime.Singleton, sp =>
                                                                                             ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata", config)));
            return(new HttpClient(new HttpServer(config)));
        }
コード例 #10
0
        public void GetBinding_DoesnotThrowForNonPrimitives()
        {
            var  config        = RoutingConfigurationFactory.Create();
            Type parameterType = typeof(FormatterOrder);
            Mock <ParameterInfo> parameterInfoMock = new Mock <ParameterInfo>();

            parameterInfoMock.Setup(info => info.ParameterType).Returns(parameterType);
            ReflectedHttpParameterDescriptor parameter = new ReflectedHttpParameterDescriptor();

            parameter.Configuration = config;
            parameter.ParameterInfo = parameterInfoMock.Object;

            ExceptionAssert.DoesNotThrow(() => new FromODataUriAttribute().GetBinding(parameter));
        }
コード例 #11
0
        public void MapODataServiceRoute_ConfigEnsureInitialized_DoesNotThrowForValidPathTemplateWithAttributeRouting()
        {
            // Arrange
            var builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <Customer>("Customers");
            IEdmModel model         = builder.GetEdmModel();
            var       configuration = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(CustomersController) });

            configuration.MapODataServiceRoute(model);

            // Act & Assert
            ExceptionAssert.DoesNotThrow(() => configuration.EnsureInitialized());
        }
コード例 #12
0
        public SelectExpandNestedDollarCountTest()
        {
            _configuration = RoutingConfigurationFactory.CreateWithTypes(
                new[]
            {
                typeof(MsCustomersController), typeof(MetadataController)
            });
            _configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            _configuration.Count().OrderBy().Filter().Expand().MaxTop(null);
            _configuration.MapODataServiceRoute("odata", "odata", GetModel());
            HttpServer server = new HttpServer(_configuration);

            _client = new HttpClient(server);
        }
コード例 #13
0
        public async Task AGet_Minimial()
        {
            // Arrange
            var configuration = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(AccountsController) });

            configuration.MapODataServiceRoute("odata", "odata", GetEdmModel());

            HttpClient client = new HttpClient(new HttpServer(configuration));

            // Act
            HttpResponseMessage response = await client.GetAsync(_requestRooturl + "Accounts?$expand=PayoutPI&$format=application/json;odata.metadata=minimal");

            // Assert
            Assert.True(response.IsSuccessStatusCode);
        }
コード例 #14
0
        /// <summary>
        /// Initializes a new instance of the routing configuration class.
        /// </summary>
        /// <returns>A new instance of the routing configuration class.</returns>
        public static HttpRequest CreateFromModel(IEdmModel model, string uri = "http://localhost", string routeName = "Route", ODataPath path = null)
        {
            var configuration = RoutingConfigurationFactory.CreateWithRootContainer(routeName);

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, uri, configuration, routeName);

            if (path != null)
            {
                request.ODataFeature().Path = path;
            }

            return(request);
        }
コード例 #15
0
        /// <summary>
        /// Initializes a new instance of the routing configuration class.
        /// </summary>
        /// <returns>A new instance of the routing configuration class.</returns>
        internal static IWebApiAssembliesResolver Create(MockAssembly assembly = null)
        {
            IRouteBuilder builder = RoutingConfigurationFactory.Create();

            ApplicationPartManager applicationPartManager = builder.ApplicationBuilder.ApplicationServices.GetRequiredService <ApplicationPartManager>();

            applicationPartManager.ApplicationParts.Clear();

            if (assembly != null)
            {
                AssemblyPart part = new AssemblyPart(assembly);
                applicationPartManager.ApplicationParts.Add(part);
            }

            return(new WebApiAssembliesResolver(applicationPartManager));
        }
コード例 #16
0
        public QueryableLimitationTest()
        {
            _configuration = RoutingConfigurationFactory.CreateWithTypes(new[]
            {
                typeof(QueryLimitCustomersController),
                typeof(OpenCustomersController),
                typeof(MetadataController)
            });

            _model = GetEdmModel();

            _configuration.Count().OrderBy().Filter().Expand().MaxTop(null);
            _configuration.MapODataServiceRoute("odata", "odata", _model);
            HttpServer server = new HttpServer(_configuration);

            _client = new HttpClient(server);
        }
コード例 #17
0
        public void MapODataServiceRoute_ConfigEnsureInitialized_DoesNotThrowForInvalidPathTemplateWithoutAttributeRouting()
        {
            // Arrange
            var builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <Customer>("Customers").EntityType.Ignore(c => c.Name);
            IEdmModel model         = builder.GetEdmModel();
            var       configuration = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(CustomersController) });

            configuration.MapODataServiceRoute(
                "RouteName",
                "RoutePrefix",
                model,
                new DefaultODataPathHandler(),
                ODataRoutingConventions.CreateDefault());

            // Act & Assert
            ExceptionAssert.DoesNotThrow(() => configuration.EnsureInitialized());
        }
コード例 #18
0
        public void GetBinding_ReturnsSameBindingTypeAsODataModelBinderProvider()
        {
            var  config        = RoutingConfigurationFactory.Create();
            Type parameterType = typeof(Guid);
            Mock <ParameterInfo> parameterInfoMock = new Mock <ParameterInfo>();

            parameterInfoMock.Setup(info => info.ParameterType).Returns(parameterType);

            ReflectedHttpParameterDescriptor parameter = new ReflectedHttpParameterDescriptor();

            parameter.Configuration = config;
            parameter.ParameterInfo = parameterInfoMock.Object;

            HttpParameterBinding binding = new FromODataUriAttribute().GetBinding(parameter);

            ModelBinderParameterBinding modelBinding = Assert.IsType <ModelBinderParameterBinding>(binding);

            Assert.Equal(new ODataModelBinderProvider().GetBinder(config, parameterType).GetType(), modelBinding.Binder.GetType());
        }
コード例 #19
0
        private static HttpConfiguration GetQueryOptionConfiguration(bool caseInsensitive)
        {
            var config = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(ParserExtenstionCustomersController) });
            ODataUriResolver resolver = new ODataUriResolver();

            if (caseInsensitive)
            {
                resolver = new CaseInsensitiveResolver();
            }

            config.Count().OrderBy().Filter().Expand().MaxTop(null).Select();
            config.MapODataServiceRoute("query", "query",
                                        builder =>
                                        builder.AddService(ServiceLifetime.Singleton, sp => GetEdmModel())
                                        .AddService <IEnumerable <IODataRoutingConvention> >(ServiceLifetime.Singleton, sp =>
                                                                                             ODataRoutingConventions.CreateDefaultWithAttributeRouting("query", config))
                                        .AddService(ServiceLifetime.Singleton, sp => resolver));
            return(config);
        }
コード例 #20
0
        public async Task DollarFormat_Applies_IfPresent(string path, string mediaTypeFormat)
        {
            // Arrange
            MediaTypeHeaderValue expected = MediaTypeHeaderValue.Parse(mediaTypeFormat);
            string    url           = string.Format("http://localhost/{0}?$format={1}", path, mediaTypeFormat);
            IEdmModel model         = GetEdmModel();
            var       configuration = RoutingConfigurationFactory.CreateWithTypes(
                new[] { typeof(FormatCustomersController), typeof(ThisController) });
            HttpServer server = new HttpServer(configuration);
            HttpClient client = new HttpClient(server);

            configuration.MapODataServiceRoute("odata", routePrefix: null, model: model);

            // Act
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
            HttpResponseMessage response = await client.SendAsync(request);

            // Assert
            ExceptionAssert.DoesNotThrow(() => response.EnsureSuccessStatusCode());
            Assert.Equal(expected, response.Content.Headers.ContentType);
        }
コード例 #21
0
        private static HttpConfiguration GetConfiguration(bool caseInsensitive, bool unqualifiedNameCall)
        {
            IEdmModel         model  = ODataRoutingModel.GetModel();
            HttpConfiguration config = RoutingConfigurationFactory.CreateWithTypes(new[]
            {
                typeof(MetadataController),
                typeof(ProductsController),
                typeof(RoutingCustomersController),
            });

            ODataUriResolver resolver = new ODataUriResolver();

            if (unqualifiedNameCall)
            {
                resolver = new UnqualifiedODataUriResolver();
                if (caseInsensitive)
                {
                    resolver = new UnqualifiedCaseInsensitiveResolver();
                }
            }
            else
            {
                if (caseInsensitive)
                {
                    resolver = new CaseInsensitiveResolver();
                }
            }

            config.Count().Filter().OrderBy().Expand().MaxTop(null).Select();
            config.MapODataServiceRoute("odata", "odata",
                                        builder =>
                                        builder.AddService(ServiceLifetime.Singleton, sp => model)
                                        .AddService <IEnumerable <IODataRoutingConvention> >(ServiceLifetime.Singleton, sp =>
                                                                                             ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata", config))
                                        .AddService(ServiceLifetime.Singleton, sp => resolver));
            return(config);
        }
コード例 #22
0
        public void Negotiate_CallGetPerRequestFormatterInstanceFirst()
        {
            HttpConfiguration  config              = RoutingConfigurationFactory.CreateWithRootContainer("odata");
            HttpRequestMessage request             = RequestFactory.Create(config, "odata");
            MediaTypeFormatter perRequestFormatter = new ODataMediaTypeFormatter(Enumerable.Empty <ODataPayloadKind>())
            {
                Request = request
            };
            Mock <MediaTypeFormatter> formatter = new Mock <MediaTypeFormatter>();

            formatter
            .Setup(f => f.GetPerRequestFormatterInstance(typeof(void), request, It.IsAny <MediaTypeHeaderValue>()))
            .Returns(perRequestFormatter);
            Mock <IContentNegotiator> innerContentNegotiator = new Mock <IContentNegotiator>();

            innerContentNegotiator
            .Setup(n => n.Negotiate(typeof(void), request, It.Is <IEnumerable <MediaTypeFormatter> >(f => f.First() == perRequestFormatter)))
            .Returns(new ContentNegotiationResult(perRequestFormatter, MediaTypeHeaderValue.Parse("application/json")));

            IContentNegotiator contentNegotiator = new PerRequestContentNegotiator(innerContentNegotiator.Object);
            var negotiationResult = contentNegotiator.Negotiate(typeof(void), request, new MediaTypeFormatter[] { formatter.Object });

            Assert.Same(perRequestFormatter, negotiationResult.Formatter);
        }