[InlineData("GET", "http://localhost/Customers(42)/NS.SpecialCustomer/IsSpecialUpgraded()", "IsSpecialUpgraded_42")] // function bound to derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.Routes
                .MapODataRoute("odata", "", model.Model)
                .MapODataRouteAttributes(config);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
        public void Ctor_ThatBuildsNestedContext_CopiesProperties()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataSerializerContext context = new ODataSerializerContext
            {
                EntitySet = model.Customers,
                MetadataLevel = ODataMetadataLevel.FullMetadata,
                Model = model.Model,
                Path = new ODataPath(),
                Request = new HttpRequestMessage(),
                RootElementName = "somename",
                SelectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true),
                SkipExpensiveAvailabilityChecks = true,
                Url = new UrlHelper()
            };
            EntityInstanceContext entity = new EntityInstanceContext { SerializerContext = context };
            SelectExpandClause selectExpand = new SelectExpandClause(new SelectItem[0], allSelected: true);
            IEdmNavigationProperty navProp = model.Customer.NavigationProperties().First();

            // Act
            ODataSerializerContext nestedContext = new ODataSerializerContext(entity, selectExpand, navProp);

            // Assert
            Assert.Equal(context.MetadataLevel, nestedContext.MetadataLevel);
            Assert.Same(context.Model, nestedContext.Model);
            Assert.Same(context.Path, nestedContext.Path);
            Assert.Same(context.Request, nestedContext.Request);
            Assert.Equal(context.RootElementName, nestedContext.RootElementName);
            Assert.Equal(context.SkipExpensiveAvailabilityChecks, nestedContext.SkipExpensiveAvailabilityChecks);
            Assert.Same(context.Url, nestedContext.Url);
        }
        public void SelectAction_Returns_ExpectedMethodOnDerivedType(string method, string[] methodsInController,
            string expectedSelectedAction)
        {
            // Arrange
            string key = "42";
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var specialOrdersProperty = model.SpecialCustomer.FindProperty("SpecialOrders") as IEdmNavigationProperty;

            ODataPath odataPath = new ODataPath(new EntitySetPathSegment(model.Customers), new KeyValuePathSegment(key),
                new CastPathSegment(model.SpecialCustomer), new LinksPathSegment(), new NavigationPathSegment(specialOrdersProperty));

            HttpControllerContext controllerContext = CreateControllerContext(method);
            var actionMap = GetMockActionMap(methodsInController);

            // Act
            string selectedAction = new LinksRoutingConvention().SelectAction(odataPath, controllerContext, actionMap);

            // Assert
            Assert.Equal(expectedSelectedAction, selectedAction);
            if (expectedSelectedAction == null)
            {
                Assert.Empty(controllerContext.RouteData.Values);
            }
            else
            {
                Assert.Equal(2, controllerContext.RouteData.Values.Count);
                Assert.Equal(key, controllerContext.RouteData.Values["key"]);
                Assert.Equal(specialOrdersProperty.Name, controllerContext.RouteData.Values["navigationProperty"]);
            }
        }
        public void Property_Value_WorksWithUnTypedContext()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
            InlineCountQueryOption inlineCount = new InlineCountQueryOption("allpages", context);

            // Act & Assert
            Assert.Equal(InlineCountValue.AllPages, inlineCount.Value);
        }
Esempio n. 5
0
        public void ApplyTo_WithUnTypedContext_Throws_InvalidOperation()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
            SkipQueryOption skip = new SkipQueryOption("42", context);
            IQueryable queryable = new Mock<IQueryable>().Object;

            // Act & Assert
            Assert.Throws<NotSupportedException>(() => skip.ApplyTo(queryable, new ODataQuerySettings()),
                "The query option is not bound to any CLR type. 'ApplyTo' is only supported with a query option bound to a CLR type.");
        }
        public void ApplyTo_OnSingleEntity_WithUnTypedContext_Throws_InvalidOperation()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
            SelectExpandQueryOption selectExpand = new SelectExpandQueryOption(select: "ID", expand: null, context: context, queryTranslator: null);
            object entity = new object();

            // Act & Assert
            Assert.Throws<NotSupportedException>(() => selectExpand.ApplyTo(entity, new ODataQuerySettings()),
                "The query option is not bound to any CLR type. 'ApplyTo' is only supported with a query option bound to a CLR type.");
        }
        public void ValidateThrowException_IfNotNavigable()
        {
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            model.Model.SetAnnotationValue(model.Customer, new ClrTypeAnnotation(typeof(Customer)));
            ODataQueryContext queryContext = new ODataQueryContext(model.Model, typeof(Customer));
            model.Model.SetAnnotationValue(model.Customer.FindProperty("Orders"), new QueryableRestrictionsAnnotation(new QueryableRestrictions{NotNavigable=true}));

            string select = "Orders";
            SelectExpandQueryValidator validator = new SelectExpandQueryValidator();
            SelectExpandQueryOption selectExpandQueryOption = new SelectExpandQueryOption(select, null, queryContext);
            Assert.Throws<ODataException>(
                () => validator.Validate(selectExpandQueryOption, new ODataValidationSettings()),
                "The property 'Orders' cannot be used for navigation.");
        }
        public SelectExpandBinderTest()
        {
            _settings = new ODataQuerySettings { HandleNullPropagation = HandleNullPropagationOption.False };
            _model = new CustomersModelWithInheritance();
            _model.Model.SetAnnotationValue<ClrTypeAnnotation>(_model.Customer, new ClrTypeAnnotation(typeof(Customer)));
            _model.Model.SetAnnotationValue<ClrTypeAnnotation>(_model.SpecialCustomer, new ClrTypeAnnotation(typeof(SpecialCustomer)));
            _context = new ODataQueryContext(_model.Model, typeof(Customer));
            _binder = new SelectExpandBinder(_settings, new SelectExpandQueryOption("*", "", _context));

            Customer customer = new Customer();
            Order order = new Order { Customer = customer };
            customer.Orders.Add(order);

            _queryable = new[] { customer }.AsQueryable();
        }
        public void Ctor_TakingOrderByClause_InitializesProperty_Property()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            IEdmProperty property = model.Customer.FindProperty("ID");
            EntityRangeVariable variable = new EntityRangeVariable("it", model.Customer.AsReference(), model.Customers);
            SingleValuePropertyAccessNode node = new SingleValuePropertyAccessNode(new EntityRangeVariableReferenceNode("it", variable), property);
            OrderByClause orderBy = new OrderByClause(thenBy: null, expression: node, direction: OrderByDirection.Ascending, rangeVariable: variable);

            // Act
            OrderByPropertyNode orderByNode = new OrderByPropertyNode(orderBy);

            // Assert
            Assert.Equal(property, orderByNode.Property);
        }
        public void ValidateThrowException_IfBaseOrDerivedClassPropertyNotNavigable(string className, string propertyName)
        {
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            model.Model.SetAnnotationValue(model.SpecialCustomer, new ClrTypeAnnotation(typeof(Customer)));
            ODataQueryContext queryContext = new ODataQueryContext(model.Model, typeof(Customer));
            EdmEntityType classType = (className == "Customer") ? model.Customer : model.SpecialCustomer;
            model.Model.SetAnnotationValue(classType.FindProperty(propertyName), new QueryableRestrictionsAnnotation(new QueryableRestrictions { NotNavigable = true }));

            string select = "NS.SpecialCustomer/" + propertyName;
            SelectExpandQueryValidator validator = new SelectExpandQueryValidator();
            SelectExpandQueryOption selectExpandQueryOption = new SelectExpandQueryOption(select, null, queryContext);
            Assert.Throws<ODataException>(
                () => validator.Validate(selectExpandQueryOption, new ODataValidationSettings()),
                String.Format(CultureInfo.InvariantCulture, "The property '{0}' cannot be used for navigation.", propertyName));
        }
        public void CreateCollection_CopmplexType_Succeeds()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            OrderByClause orderByNode = ODataUriParser.ParseOrderBy("Street desc, City asc", model.Model, model.Address);

            // Act
            ICollection<OrderByNode> nodes = OrderByNode.CreateCollection(orderByNode);

            // Assert
            Assert.Equal(2, nodes.Count());
            Assert.Equal("Street", (nodes.ToList()[0] as OrderByPropertyNode).Property.Name);
            Assert.Equal(OrderByDirection.Descending, nodes.ToList()[0].Direction);
            Assert.Equal("City", (nodes.ToList()[1] as OrderByPropertyNode).Property.Name);
            Assert.Equal(OrderByDirection.Ascending, nodes.ToList()[1].Direction);
        }
        public void Ctor_ThatBuildsNestedContext_InitializesRightValues()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            SelectExpandClause selectExpand = new SelectExpandClause(new SelectItem[0], allSelected: true);
            IEdmNavigationProperty navProp = model.Customer.NavigationProperties().First();
            ODataSerializerContext context = new ODataSerializerContext { EntitySet = model.Customers, Model = model.Model };
            EntityInstanceContext entity = new EntityInstanceContext { SerializerContext = context };

            // Act
            ODataSerializerContext nestedContext = new ODataSerializerContext(entity, selectExpand, navProp);

            // Assert
            Assert.Same(entity, nestedContext.ExpandedEntity);
            Assert.Same(navProp, nestedContext.NavigationProperty);
            Assert.Same(selectExpand, nestedContext.SelectExpandClause);
            Assert.Same(model.Orders, nestedContext.EntitySet);
        }
        public void SelectAction_ReturnsFunctionName_ForFunctionOnEntity()
        {
            // Arrange
            FunctionRoutingConvention functionConvention = new FunctionRoutingConvention();
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataPath odataPath = new DefaultODataPathHandler().Parse(model.Model, "Customers(1)/IsUpgraded");
            HttpRequestContext requestContext = new HttpRequestContext();
            HttpControllerContext controllerContext = new HttpControllerContext
                {
                    Request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/"),
                    RequestContext = requestContext,
                    RouteData = new HttpRouteData(new HttpRoute())
                };
            controllerContext.Request.SetRequestContext(requestContext);
            ILookup<string, HttpActionDescriptor> actionMap = new HttpActionDescriptor[1].ToLookup(desc => "IsUpgraded");

            // Act
            string function = functionConvention.SelectAction(odataPath, controllerContext, actionMap);

            // Assert
            Assert.Equal("IsUpgraded", function);
            Assert.Equal(1, controllerContext.Request.GetRouteData().Values.Count);
            Assert.Equal("1", controllerContext.Request.GetRouteData().Values["key"]);
        }
        public void Ctor_FollowingConventions_GeneratesFeedSelfLinkFollowingConventions()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            HttpRequestMessage request = GetODataRequest(model.Model);

            // Act
            EntitySetLinkBuilderAnnotation linkBuilder = new EntitySetLinkBuilderAnnotation(model.Customers, model.Model);
            Uri result = linkBuilder.BuildFeedSelfLink(new FeedContext { EntitySet = model.Customers, Url = request.GetUrlHelper() });

            // Assert
            Assert.Equal("http://localhost/Customers", result.AbsoluteUri);
        }
        public void Ctor_FollowingConventions_GeneratesNavigationLinkWithCast_ForDerivedNavigationProperty()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            HttpRequestMessage request = GetODataRequest(model.Model);
            ODataSerializerContext serializerContext = new ODataSerializerContext { Model = model.Model, EntitySet = model.Customers, Url = request.GetUrlHelper() };
            EntityInstanceContext instanceContext = new EntityInstanceContext(serializerContext, model.SpecialCustomer.AsReference(), new { ID = 42 });
            IEdmNavigationProperty ordersProperty = model.SpecialCustomer.NavigationProperties().First(p => p.Name == "SpecialOrders");

            // Act
            EntitySetLinkBuilderAnnotation linkBuilder = new EntitySetLinkBuilderAnnotation(model.Customers, model.Model);
            Uri result = linkBuilder.BuildNavigationLink(instanceContext, ordersProperty, ODataMetadataLevel.Default);

            // Assert
            Assert.Equal("http://localhost/Customers(42)/NS.SpecialCustomer/SpecialOrders", result.AbsoluteUri);
        }
        public void Ctor_FollowingConventions_GeneratesSelfLinkWithoutCast_IfDerivedTypesHaveNoNavigationProperty()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            IEdmEntitySet specialCustomers = new EdmEntitySet(model.Container, "SpecialCustomers", model.SpecialCustomer);
            HttpRequestMessage request = GetODataRequest(model.Model);
            ODataSerializerContext serializerContext = new ODataSerializerContext { Model = model.Model, EntitySet = specialCustomers, Url = request.GetUrlHelper() };
            EntityInstanceContext instanceContext = new EntityInstanceContext(serializerContext, model.Customer.AsReference(), new { ID = 42 });

            // Act
            EntitySetLinkBuilderAnnotation linkBuilder = new EntitySetLinkBuilderAnnotation(specialCustomers, model.Model);
            string result = linkBuilder.BuildIdLink(instanceContext, ODataMetadataLevel.Default);

            // Assert
            Assert.Equal("http://localhost/SpecialCustomers(42)", result);
        }
        public void CreateODataFeed_SetsNextPageLink_WhenWritingTruncatedCollection_ForExpandedProperties()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            IEdmCollectionTypeReference customersType = new EdmCollectionTypeReference(new EdmCollectionType(model.Customer.AsReference()), isNullable: false);
            ODataFeedSerializer serializer = new ODataFeedSerializer(new DefaultODataSerializerProvider());
            SelectExpandClause selectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true);
            IEdmNavigationProperty ordersProperty = model.Customer.NavigationProperties().First();
            EntityInstanceContext entity = new EntityInstanceContext
            {
                SerializerContext = new ODataSerializerContext { EntitySet = model.Customers, Model = model.Model }
            };
            ODataSerializerContext nestedContext = new ODataSerializerContext(entity, selectExpandClause, ordersProperty);
            TruncatedCollection<Order> orders = new TruncatedCollection<Order>(new[] { new Order(), new Order() }, pageSize: 1);

            Mock<EntitySetLinkBuilderAnnotation> linkBuilder = new Mock<EntitySetLinkBuilderAnnotation>();
            linkBuilder.Setup(l => l.BuildNavigationLink(entity, ordersProperty, ODataMetadataLevel.Default)).Returns(new Uri("http://navigation-link/"));
            model.Model.SetEntitySetLinkBuilder(model.Customers, linkBuilder.Object);
            model.Model.SetEntitySetLinkBuilder(model.Orders, new EntitySetLinkBuilderAnnotation());

            // Act
            ODataFeed feed = serializer.CreateODataFeed(orders, _customersType, nestedContext);

            // Assert
            Assert.Equal("http://navigation-link/?$skip=1", feed.NextPageLink.AbsoluteUri);
        }
        public void Property_SelectExpandClause_WorksWithUnTypedContext()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
            SelectExpandQueryOption selectExpand = new SelectExpandQueryOption(select: "ID", expand: null, context: context);

            // Act & Assert
            Assert.NotNull(selectExpand.SelectExpandClause);
        }
        public void SelectAction_SetsRouteData_ForGetLinkRequests()
        {
            // Arrange
            string key = "42";
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var specialOrdersProperty = model.SpecialCustomer.FindProperty("SpecialOrders") as IEdmNavigationProperty;

            ODataPath odataPath = new ODataPath(new EntitySetPathSegment(model.Customers), new KeyValuePathSegment(key),
                new CastPathSegment(model.SpecialCustomer), new LinksPathSegment(), new NavigationPathSegment(specialOrdersProperty));

            HttpControllerContext controllerContext = CreateControllerContext("GET");
            var actionMap = new[] { GetMockActionDescriptor("GetLink") }.ToLookup(a => a.ActionName);

            // Act
            new LinksRoutingConvention().SelectAction(odataPath, controllerContext, actionMap);
            var routeData = controllerContext.RouteData;

            // Assert
            Assert.Equal(key, routeData.Values["key"]);
            Assert.Equal("SpecialOrders", routeData.Values["navigationProperty"]);
        }
        public void Property_OrderByNodes_WorksWithUnTypedContext()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
            OrderByQueryOption orderBy = new OrderByQueryOption("ID desc", context);

            // Act & Assert
            Assert.NotNull(orderBy.OrderByNodes);
        }
Esempio n. 21
0
        public void Property_Value_WorksWithUnTypedContext()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataQueryContext context = new ODataQueryContext(model.Model, model.Customer);
            TopQueryOption top = new TopQueryOption("42", context);

            // Act & Assert
            Assert.Equal(42, top.Value);
        }
        public void GenerateLocationHeader_ThrowsTypeMustBeEntity_IfMappingTypeIsNotEntity()
        {
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataPath path = new ODataPath(new EntitySetPathSegment(model.Customers));
            HttpRequestMessage request = new HttpRequestMessage();
            request.SetEdmModel(model.Model);
            request.SetODataPath(path);
            model.Model.SetAnnotationValue(model.Address, new ClrTypeAnnotation(typeof(TestEntity)));
            CreatedODataResult<TestEntity> createdODataResult = GetCreatedODataResult(request);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() => createdODataResult.GenerateLocationHeader(),
                "NS.Address is not an entity type. Only entity types are supported.");
        }
        public void GenerateLocationHeader_ThrowsEntityTypeNotInModel_IfContentTypeIsNotThereInModel()
        {
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataPath path = new ODataPath(new EntitySetPathSegment(model.Customers));
            HttpRequestMessage request = new HttpRequestMessage();
            request.SetEdmModel(model.Model);
            request.SetODataPath(path);
            CreatedODataResult<TestEntity> createdODataResult = GetCreatedODataResult(request);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() => createdODataResult.GenerateLocationHeader(),
                "Cannot find the entity type 'System.Web.Http.OData.Results.CreatedODataResultTest+TestEntity' in the model.");
        }
        public void SelectAction_ReturnsNull_IfActionIsMissing()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataPath odataPath = new DefaultODataPathHandler().Parse(model.Model, "Customers(1)/IsLocal");
            ILookup<string, HttpActionDescriptor> emptyActionMap = new HttpActionDescriptor[0].ToLookup(desc => (string)null);
            HttpControllerContext controllerContext = new HttpControllerContext
                {
                    Request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/")
                };
            controllerContext.Request.SetRouteData(new HttpRouteData(new HttpRoute()));

            // Act
            string selectedAction = new FunctionRoutingConvention().SelectAction(odataPath, controllerContext, emptyActionMap);

            // Assert
            Assert.Null(selectedAction);
            Assert.Empty(controllerContext.Request.GetRouteData().Values);
        }
 public SelectExpandWrapperTest()
 {
     _model = new CustomersModelWithInheritance();
     _modelID = ModelContainer.GetModelID(_model.Model);
 }
        public void GenerateLocationHeader_ThrowsEditLinkNullForLocationHeader_IfEntitySetLinkBuilderReturnsNull()
        {
            // Arrange
            Mock<EntitySetLinkBuilderAnnotation> linkBuilder = new Mock<EntitySetLinkBuilderAnnotation>();
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            model.Model.SetAnnotationValue(model.Customer, new ClrTypeAnnotation(typeof(TestEntity)));
            model.Model.SetEntitySetLinkBuilder(model.Customers, linkBuilder.Object);
            ODataPath path = new ODataPath(new EntitySetPathSegment(model.Customers));
            HttpRequestMessage request = new HttpRequestMessage();
            request.SetEdmModel(model.Model);
            request.SetODataPath(path);
            CreatedODataResult<TestEntity> createdODataResult = GetCreatedODataResult(request);

            // Act
            Assert.Throws<InvalidOperationException>(() => createdODataResult.GenerateLocationHeader(),
                "The edit link builder for the entity set 'Customers' returned null. An edit link is required for the location header.");
        }
        public void SelectAction_SetsRelatedKey_ForDeleteLinkRequests()
        {
            // Arrange
            string key = "42";
            string relatedKey = "24";
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var specialOrdersProperty = model.SpecialCustomer.FindProperty("SpecialOrders") as IEdmNavigationProperty;

            ODataPath odataPath = new ODataPath(new EntitySetPathSegment(model.Customers), new KeyValuePathSegment(key),
                new CastPathSegment(model.SpecialCustomer), new LinksPathSegment(), new NavigationPathSegment(specialOrdersProperty),
                new KeyValuePathSegment(relatedKey));

            HttpControllerContext controllerContext = CreateControllerContext("DELETE");
            var actionMap = GetMockActionMap("DeleteLink");

            // Act
            new LinksRoutingConvention().SelectAction(odataPath, controllerContext, actionMap);
            var routeData = controllerContext.RouteData;

            // Assert
            Assert.Equal(key, routeData.Values["key"]);
            Assert.Equal("SpecialOrders", routeData.Values["navigationProperty"]);
            Assert.Equal(relatedKey, routeData.Values["relatedKey"]);
        }
        public void Property_LocationHeader_IsEvaluatedOnlyOnce()
        {
            // Arrange
            Uri editLink = new Uri("http://edit-link");
            Mock<EntitySetLinkBuilderAnnotation> linkBuilder = new Mock<EntitySetLinkBuilderAnnotation>();
            linkBuilder.Setup(b => b.BuildEditLink(It.IsAny<EntityInstanceContext>(), ODataMetadataLevel.Default, null))
                .Returns(editLink);

            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            model.Model.SetAnnotationValue(model.Customer, new ClrTypeAnnotation(typeof(TestEntity)));
            model.Model.SetEntitySetLinkBuilder(model.Customers, linkBuilder.Object);
            ODataPath path = new ODataPath(new EntitySetPathSegment(model.Customers));
            HttpRequestMessage request = new HttpRequestMessage();
            request.SetEdmModel(model.Model);
            request.SetODataPath(path);
            TestController controller = new TestController { Request = request, Configuration = new HttpConfiguration() };
            CreatedODataResult<TestEntity> createdODataResult = new CreatedODataResult<TestEntity>(_entity, controller);

            // Act
            Uri locationHeader = createdODataResult.LocationHeader;

            // Assert
            linkBuilder.Verify(
                (b) => b.BuildEditLink(It.IsAny<EntityInstanceContext>(), ODataMetadataLevel.Default, null),
                Times.Once());
        }
        public void GenerateLocationHeader_UsesEntitySetLinkBuilder_ToGenerateLocationHeader()
        {
            // Arrange
            string idLink = "http://id-link";
            Uri editLink = new Uri(idLink);
            Mock<EntitySetLinkBuilderAnnotation> linkBuilder = new Mock<EntitySetLinkBuilderAnnotation>();
            linkBuilder.Setup(b => b.BuildIdLink(It.IsAny<EntityInstanceContext>(), ODataMetadataLevel.Default))
                .Returns(idLink);
            linkBuilder.Setup(b => b.BuildEditLink(It.IsAny<EntityInstanceContext>(), ODataMetadataLevel.Default, idLink))
                .Returns(editLink);

            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            model.Model.SetAnnotationValue(model.Customer, new ClrTypeAnnotation(typeof(TestEntity)));
            model.Model.SetEntitySetLinkBuilder(model.Customers, linkBuilder.Object);
            ODataPath path = new ODataPath(new EntitySetPathSegment(model.Customers));
            HttpRequestMessage request = new HttpRequestMessage();
            request.SetEdmModel(model.Model);
            request.SetODataPath(path);
            CreatedODataResult<TestEntity> createdODataResult = GetCreatedODataResult(request);

            // Act
            var locationHeader = createdODataResult.GenerateLocationHeader();

            // Assert
            Assert.Same(editLink, locationHeader);
        }
 public SelectExpandQueryValidatorTest()
 {
     CustomersModelWithInheritance model = new CustomersModelWithInheritance();
     model.Model.SetAnnotationValue(model.Customer, new ClrTypeAnnotation(typeof(Customer)));
     _queryContext = new ODataQueryContext(model.Model, typeof(Customer));
 }