public void PostResponse_Throws_IfODataPathDoesNotStartWithEntitySet() { ApiController controller = new Mock<ApiController>().Object; var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customers"); controller.Configuration = new HttpConfiguration(); request.SetODataPath(new ODataPath(new MetadataPathSegment())); controller.Request = request; Assert.Throws<InvalidOperationException>( () => EntitySetControllerHelpers.PostResponse<Customer, int>(controller, new Customer(), 5), "A Location header could not be generated because the request's OData path does not start with an entity set path segment."); }
private HttpRequestMessage GetSampleRequest() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/employees"); HttpConfiguration configuration = new HttpConfiguration(); string routeName = "Route"; configuration.Routes.MapODataRoute(routeName, null, GetSampleModel()); request.SetConfiguration(configuration); IEdmEntitySet entitySet = _model.EntityContainers().Single().FindEntitySet("employees"); request.SetEdmModel(_model); request.SetODataPath(new ODataPath(new EntitySetPathSegment(entitySet))); request.SetODataRouteName(routeName); return request; }
public void TryMatchMediaTypeWithBinaryRawValueMatchesRequest() { IEdmModel model = GetBinaryModel(); PropertyAccessPathSegment propertySegment = new PropertyAccessPathSegment((model.GetEdmType(typeof(RawValueEntity)) as IEdmEntityType).FindProperty("BinaryProperty")); ODataPath path = new ODataPath(new EntitySetPathSegment("RawValue"), new KeyValuePathSegment("1"), propertySegment, new ValuePathSegment()); ODataBinaryValueMediaTypeMapping mapping = new ODataBinaryValueMediaTypeMapping(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/RawValue(1)/BinaryProperty/$value"); request.SetEdmModel(model); request.SetODataPath(path); double mapResult = mapping.TryMatchMediaType(request); Assert.Equal(1.0, mapResult); }
public void TryMatchMediaTypeWithNonRawvalueRequestDoesntMatchRequest() { IEdmModel model = ODataTestUtil.GetEdmModel(); PropertyAccessPathSegment propertySegment = new PropertyAccessPathSegment((model.GetEdmType(typeof(FormatterPerson)) as IEdmEntityType).FindProperty("Age")); ODataPath path = new ODataPath(new EntitySetPathSegment("People"), new KeyValuePathSegment("1"), propertySegment); ODataPrimitiveValueMediaTypeMapping mapping = new ODataPrimitiveValueMediaTypeMapping(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/People(1)/Age/"); request.SetEdmModel(model); request.SetODataPath(path); double mapResult = mapping.TryMatchMediaType(request); Assert.Equal(0, mapResult); }
public override bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) { if (routeDirection != HttpRouteDirection.UriResolution) { return true; } object odataPathValue; if (!values.TryGetValue(ODataRouteConstants.ODataPath, out odataPathValue)) { return false; } var pathString = odataPathValue as string; if (pathString == null) pathString = string.Empty; ODataPath path = null; try { path = VersionAwarePathHandler.Parse(request, EdmModel, pathString); } catch (ODataException e) { throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid OData path", e)); } if (path != null) { values[ODataRouteConstants.ODataPath] = path.Segments.First(); // Set all the properties we need for routing, querying, formatting request.SetEdmModel(EdmModel); request.SetODataPathHandler(VersionAwarePathHandler); request.SetODataPath(path); request.SetODataRouteName(RouteName); request.SetODataRoutingConventions(RoutingConventions); if (!values.ContainsKey(ODataRouteConstants.Controller)) { // Select controller name using the routing conventions string controllerName = SelectControllerName(path, request); if (controllerName != null) { values[ODataRouteConstants.Controller] = controllerName; } } } return path != null; }
public void OnActionExecuted_DoesntChangeTheResponse_IfResponseIsntSuccessful() { IEdmModel model = new Mock<IEdmModel>().Object; ODataPath path = new ODataPath(new EntitySetPathSegment("FakeEntitySet"), new KeyValuePathSegment("FakeKey"), new PropertyAccessPathSegment("FakeProperty"), new ValuePathSegment()); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/"); request.SetEdmModel(model); request.SetODataPath(path); ODataNullValueAttribute odataNullValue = new ODataNullValueAttribute(); HttpResponseMessage response = SetUpResponse(HttpStatusCode.InternalServerError, null, typeof(object)); HttpActionExecutedContext context = SetUpContext(request, response); odataNullValue.OnActionExecuted(context); Assert.Equal(response, context.Response); }
public void OnActionExecuted_Generates404_IfContentIsNull() { IEdmModel model = new Mock<IEdmModel>().Object; ODataPath path = new ODataPath(new EntitySetPathSegment("FakeEntitySet"), new KeyValuePathSegment("FakeKey"), new PropertyAccessPathSegment("FakeProperty"), new ValuePathSegment()); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/"); request.SetEdmModel(model); request.SetODataPath(path); ODataNullValueAttribute odataNullValue = new ODataNullValueAttribute(); HttpResponseMessage response = SetUpResponse(HttpStatusCode.OK, null, typeof(object)); HttpActionExecutedContext context = SetUpContext(request, response); odataNullValue.OnActionExecuted(context); Assert.NotNull(context.Response); Assert.Equal(HttpStatusCode.NotFound, context.Response.StatusCode); }
/// <summary> /// Determines whether this instance equals a specified route. /// </summary> /// <param name="request">The request.</param> /// <param name="route">The route to compare.</param> /// <param name="parameterName">The name of the parameter.</param> /// <param name="values">A list of parameter values.</param> /// <param name="routeDirection">The route direction.</param> /// <returns> /// True if this instance equals a specified route; otherwise, false. /// </returns> public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) { if (request == null) { throw Error.ArgumentNull("request"); } if (values == null) { throw Error.ArgumentNull("values"); } if (routeDirection == HttpRouteDirection.UriResolution) { object odataPathRouteValue; if (values.TryGetValue(ODataRouteConstants.ODataPath, out odataPathRouteValue)) { string odataPath = odataPathRouteValue as string; if (odataPath == null) { // No odataPath means the path is empty; this is necessary for service documents odataPath = String.Empty; } ODataPath path = _pathHandler.Parse(odataPath); if (path != null) { request.SetODataPath(path); return true; } } return false; } else { // This constraint only applies to URI resolution return true; } }
private void AddRequestInfo(HttpRequestMessage request) { request.SetODataPath(new DefaultODataPathHandler().Parse(_model, GetODataPath( request.RequestUri.AbsoluteUri))); request.SetEdmModel(_model); request.SetFakeODataRouteName(); }
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 GetODataPayloadSerializer_ReturnsRawValueSerializer_ForValueRequests(Type type, EdmPrimitiveTypeKind edmPrimitiveTypeKind) { ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider(); HttpRequestMessage request = new HttpRequestMessage(); request.SetODataPath(new ODataPath(new ValuePathSegment())); var serializer = serializerProvider.GetODataPayloadSerializer(_edmModel, type, request); Assert.NotNull(serializer); Assert.Equal(ODataPayloadKind.Value, serializer.ODataPayloadKind); }
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 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 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 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_ThrowsEntitySetMissingDuringSerialization_IfODataPathEntitySetIsNull() { ODataPath path = new ODataPath(); HttpRequestMessage request = new HttpRequestMessage(); request.SetEdmModel(EdmCoreModel.Instance); request.SetODataPath(path); CreatedODataResult<TestEntity> createdODataResult = GetCreatedODataResult(request); // Act & Assert Assert.Throws<InvalidOperationException>(() => createdODataResult.GenerateLocationHeader(), "The related entity set could not be found from the OData path. The related entity set is required to serialize the payload."); }
public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpConfiguration cofiguration = new HttpConfiguration(); request.SetConfiguration(cofiguration); Dictionary<string, object> properties = new Dictionary<string, object> { { "Name", "Foo" } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); if (header.Equals("IfMatch")) { request.Headers.IfMatch.Add(etagHeaderValue); } else { request.Headers.IfNoneMatch.Add(etagHeaderValue); } ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration<Customer> customer = builder.Entity<Customer>(); customer.HasKey(c => c.Id); customer.Property(c => c.Id); customer.Property(c => c.Name).IsConcurrencyToken(); IEdmModel model = builder.GetEdmModel(); Mock<ODataPathSegment> mockSegment = new Mock<ODataPathSegment> { CallBase = true }; mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer))); mockSegment.Setup(s => s.GetEntitySet(null)).Returns((IEdmEntitySet)null); ODataPath odataPath = new ODataPath(new[] { mockSegment.Object }); request.SetODataPath(odataPath); ODataQueryContext context = new ODataQueryContext(model, typeof(Customer)); // Act ODataQueryOptions<Customer> query = new ODataQueryOptions<Customer>(context, request); ETag result = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch; dynamic dynamicResult = result; // Assert Assert.Equal("Foo", result["Name"]); Assert.Equal("Foo", dynamicResult.Name); }
public void GetETagTEntity_Returns_ETagInHeader() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpConfiguration cofiguration = new HttpConfiguration(); request.SetConfiguration(cofiguration); Dictionary<string, object> properties = new Dictionary<string, object> { { "City", "Foo" } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); CustomersModelWithInheritance model = new CustomersModelWithInheritance(); Mock<ODataPathSegment> mockSegment = new Mock<ODataPathSegment> { CallBase = true }; mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.Customer); mockSegment.Setup(s => s.GetEntitySet(null)).Returns((IEdmEntitySet)null); ODataPath odataPath = new ODataPath(new[] { mockSegment.Object }); request.SetODataPath(odataPath); // Act ETag<Customer> result = request.GetETag<Customer>(etagHeaderValue); dynamic dynamicResult = result; // Assert Assert.Equal("Foo", result["City"]); Assert.Equal("Foo", dynamicResult.City); }
public void PrimitiveTypesSerializeAsOData(Type valueType, object value, MediaTypeHeaderValue mediaType, string resourceName) { string expectedEntity = Resources.GetString(resourceName); Assert.NotNull(expectedEntity); ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder(); modelBuilder.EntitySet<WorkItem>("WorkItems"); IEdmModel model = modelBuilder.GetEdmModel(); string actualEntity; using (HttpConfiguration configuration = CreateConfiguration()) using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/WorkItems(10)/ID")) { request.SetConfiguration(configuration); IEdmProperty property = model.EntityContainers().Single().EntitySets().Single().ElementType.Properties().First(); request.SetEdmModel(model); request.SetODataPath(new ODataPath(new PropertyAccessPathSegment(property))); request.SetFakeODataRouteName(); ODataMediaTypeFormatter formatter = CreateFormatter(request); formatter.SupportedMediaTypes.Add(mediaType); Type type = (value != null) ? value.GetType() : typeof(Nullable<int>); using (ObjectContent content = new ObjectContent(type, value, formatter)) { actualEntity = content.ReadAsStringAsync().Result; } } bool isJson = resourceName.EndsWith(".json"); if (isJson) { JsonAssert.Equal(expectedEntity, actualEntity); } else { Assert.Xml.Equal(expectedEntity, actualEntity); } }
public virtual bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) { if (request == null) { throw Error.ArgumentNull("request"); } if (values == null) { throw Error.ArgumentNull("values"); } if (routeDirection == HttpRouteDirection.UriResolution) { object odataPathRouteValue; if (values.TryGetValue(ODataRouteConstants.ODataPath, out odataPathRouteValue)) { string odataPath = odataPathRouteValue as string; if (odataPath == null) { // No odataPath means the path is empty; this is necessary for service documents odataPath = String.Empty; } ODataPath path; try { path = PathHandler.Parse(EdmModel, odataPath); } catch (ODataException e) { throw new HttpResponseException( request.CreateErrorResponse(HttpStatusCode.NotFound, SRResources.ODataPathInvalid, e)); } if (path != null) { // Set all the properties we need for routing, querying, formatting request.SetEdmModel(EdmModel); request.SetODataPathHandler(PathHandler); request.SetODataPath(path); request.SetODataRouteName(RouteName); request.SetODataRoutingConventions(RoutingConventions); if (!values.ContainsKey(ODataRouteConstants.Controller)) { // Select controller name using the routing conventions string controllerName = SelectControllerName(path, request); if (controllerName != null) { values[ODataRouteConstants.Controller] = controllerName; } } return true; } } return false; } else { // This constraint only applies to URI resolution return true; } }