public void GetEdmType_Returns_EdmTypeInitializedByCtor() { IEdmTypeReference elementType = new EdmEntityTypeReference(new EdmEntityType("NS", "Entity"), isNullable: false); IEdmCollectionTypeReference collectionType = new EdmCollectionTypeReference(new EdmCollectionType(elementType), isNullable: false); var edmObject = new EdmEntityObjectCollection(collectionType); Assert.Same(collectionType, edmObject.GetEdmType()); }
public void GetPropertyValue_ThrowsInvalidOperation_IfPropertyIsNotFound() { IEdmEntityTypeReference entityType = new EdmEntityTypeReference(new EdmEntityType("NS", "Name"), isNullable: false); Mock<IEdmStructuredObject> edmObject = new Mock<IEdmStructuredObject>(); edmObject.Setup(o => o.GetEdmType()).Returns(entityType); EntityInstanceContext instanceContext = new EntityInstanceContext(_serializerContext, entityType, edmObject.Object); Assert.Throws<InvalidOperationException>( () => instanceContext.GetPropertyValue("NotPresentProperty"), "The EDM instance of type '[NS.Name Nullable=False]' is missing the property 'NotPresentProperty'."); }
[InlineData("ID,Orders/ID,Orders/Customer/ID", "Orders,Orders/Customer", true, "ID")] // deep expand and selects public void GetPropertiesToBeSelected_Selects_ExpectedProperties_OnCustomer( string select, string expand, bool specialCustomer, string structuralPropertiesToSelect) { // Arrange SelectExpandClause selectExpandClause = new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers); IEdmEntityTypeReference entityType = new EdmEntityTypeReference((specialCustomer ? _model.SpecialCustomer : _model.Customer), false); // Act SelectExpandNode selectExpandNode = new SelectExpandNode(selectExpandClause, entityType, _model.Model); var result = selectExpandNode.SelectedStructuralProperties; // Assert Assert.Equal(structuralPropertiesToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n))); }
public void BuildSelectExpandNode_ThrowsODataException_IfUnknownSelectItemPresent() { SelectExpandClause selectExpandClause = new SelectExpandClause(new SelectItem[] { new Mock<SelectItem>().Object }, allSelected: false); IEdmEntityTypeReference entityType = new EdmEntityTypeReference(_model.Customer, false); Assert.Throws<ODataException>( () => new SelectExpandNode(selectExpandClause, entityType, _model.Model), "$select does not support selections of type 'SelectItemProxy'."); }
public void WriteObjectInline_Can_WriteCollectionOfIEdmObjects() { // Arrange IEdmTypeReference edmType = new EdmEntityTypeReference(new EdmEntityType("NS", "Name"), isNullable: false); IEdmCollectionTypeReference feedType = new EdmCollectionTypeReference(new EdmCollectionType(edmType), isNullable: false); Mock<IEdmObject> edmObject = new Mock<IEdmObject>(); edmObject.Setup(e => e.GetEdmType()).Returns(edmType); var mockWriter = new Mock<ODataWriter>(); Mock<ODataEdmTypeSerializer> customSerializer = new Mock<ODataEdmTypeSerializer>(ODataPayloadKind.Entry); customSerializer.Setup(s => s.WriteObjectInline(edmObject.Object, edmType, mockWriter.Object, _writeContext)).Verifiable(); Mock<ODataSerializerProvider> serializerProvider = new Mock<ODataSerializerProvider>(); serializerProvider.Setup(s => s.GetEdmTypeSerializer(edmType)).Returns(customSerializer.Object); ODataFeedSerializer serializer = new ODataFeedSerializer(serializerProvider.Object); // Act serializer.WriteObjectInline(new[] { edmObject.Object }, feedType, mockWriter.Object, _writeContext); // Assert customSerializer.Verify(); }
/// <summary> /// Deserializes the given <paramref name="entryWrapper"/> under the given <paramref name="readContext"/>. /// </summary> /// <param name="entryWrapper">The OData entry to deserialize.</param> /// <param name="entityType">The entity type of the entry to deserialize.</param> /// <param name="readContext">The deserializer context.</param> /// <returns>The deserialized entity.</returns> public virtual object ReadEntry(ODataEntryWithNavigationLinks entryWrapper, IEdmEntityTypeReference entityType, ODataDeserializerContext readContext) { if (entryWrapper == null) { throw Error.ArgumentNull("entryWrapper"); } if (readContext == null) { throw Error.ArgumentNull("readContext"); } if (!String.IsNullOrEmpty(entryWrapper.Entry.TypeName) && entityType.FullName() != entryWrapper.Entry.TypeName) { // received a derived type in a base type deserializer. delegate it to the appropriate derived type deserializer. IEdmModel model = readContext.Model; if (model == null) { throw Error.Argument("readContext", SRResources.ModelMissingFromReadContext); } IEdmEntityType actualType = model.FindType(entryWrapper.Entry.TypeName) as IEdmEntityType; if (actualType == null) { throw new ODataException(Error.Format(SRResources.EntityTypeNotInModel, entryWrapper.Entry.TypeName)); } if (actualType.IsAbstract) { string message = Error.Format(SRResources.CannotInstantiateAbstractEntityType, entryWrapper.Entry.TypeName); throw new ODataException(message); } IEdmTypeReference actualEntityType = new EdmEntityTypeReference(actualType, isNullable: false); ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(actualEntityType); if (deserializer == null) { throw new SerializationException( Error.Format(SRResources.TypeCannotBeDeserialized, actualEntityType.FullName(), typeof(ODataMediaTypeFormatter).Name)); } object resource = deserializer.ReadInline(entryWrapper, actualEntityType, readContext); EdmStructuredObject structuredObject = resource as EdmStructuredObject; if (structuredObject != null) { structuredObject.ExpectedEdmType = entityType.EntityDefinition(); } return resource; } else { object resource = CreateEntityResource(entityType, readContext); ApplyEntityProperties(resource, entryWrapper, entityType, readContext); return resource; } }
public void GetDefaultValue_NonNullableEntity() { IEdmTypeReference nonNullableEntityType = new EdmEntityTypeReference(new EdmEntityType("NS", "Entity"), isNullable: false); var result = EdmStructuredObject.GetDefaultValue(nonNullableEntityType); var entityObject = Assert.IsType<EdmEntityObject>(result); Assert.Equal(nonNullableEntityType, entityObject.GetEdmType(), new EdmTypeReferenceEqualityComparer()); }
public void GetDefaultValue_NonNullableEntityCollection() { IEdmTypeReference elementType = new EdmEntityTypeReference(new EdmEntityType("NS", "Entity"), isNullable: true); IEdmCollectionTypeReference entityCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(elementType), isNullable: false); var result = EdmStructuredObject.GetDefaultValue(entityCollectionType); var entityCollectionObject = Assert.IsType<EdmEntityObjectCollection>(result); Assert.Equal(entityCollectionType, entityCollectionObject.GetEdmType(), new EdmTypeReferenceEqualityComparer()); }
public void ApplyProperty_IgnoresKeyProperty_WhenPatchKeyModeIsIgnore() { // Arrange ODataProperty property = new ODataProperty { Name = "Key1", Value = "Value1" }; EdmEntityType entityType = new EdmEntityType("namespace", "name"); entityType.AddKeys(new EdmStructuralProperty(entityType, "Key1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string)))); EdmEntityTypeReference entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false); ODataDeserializerProvider provider = new DefaultODataDeserializerProvider(EdmCoreModel.Instance); var resource = new Mock<IDelta>(MockBehavior.Strict); // Act ODataEntryDeserializer.ApplyProperty(property, entityTypeReference, resource.Object, provider, new ODataDeserializerContext { IsPatchMode = true, PatchKeyMode = PatchKeyMode.Ignore }); // Assert resource.Verify(); }
public void BuildSelectExpandNode_ThrowsODataException_IfUnknownSelectionIsPresent() { Selection unknownSelection = new Mock<Selection>().Object; SelectExpandClause selectExpandClause = new SelectExpandClause(unknownSelection, _emptyExpansion); IEdmEntityTypeReference entityType = new EdmEntityTypeReference(_model.Customer, false); Assert.Throws<ODataException>( () => SelectExpandNode.BuildSelectExpandNode(selectExpandClause, entityType, _model.Model), "$select does not support selections of type 'SelectionProxy'."); }
[InlineData("*", null, "")] // select * -> select no actions //[InlineData("ModelWithInheritance.Upgrade", null, "upgrade")] // select single actions -> select requested action //[InlineData("ModelWithInheritance.Upgrade,ModelWithInheritance.Upgrade", null, "upgrade")] // select duplicate actions -> de-duplicate //[InlineData("ModelWithInheritance.*", null, "upgrade")] // select wild card actions -> select all public void GetActionsToBeSelected_Selects_ExpectedActions( string select, string expand, string actionsToSelect) { // Arrange SelectExpandClause selectExpandClause = ODataUriParser.ParseSelectAndExpand(select, expand, _model.Model, _model.Customer, _model.Customers); IEdmEntityTypeReference entityType = new EdmEntityTypeReference(_model.Customer, false); // Act SelectExpandNode selectExpandNode = SelectExpandNode.BuildSelectExpandNode(selectExpandClause, entityType, _model.Model); var result = selectExpandNode.SelectedActions; // Assert Assert.Equal(actionsToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n))); }
[InlineData(null, "NS.SpecialCustomer/SpecialOrders", true, "SpecialOrders")] // expand derived navigation property on derived type -> expand requested public void GetNavigationPropertiesToBeExpanded_Expands_ExpectedProperties( string select, string expand, bool specialCustomer, string navigationPropertiesToExpand) { // Arrange SelectExpandClause selectExpandClause = ODataUriParser.ParseSelectAndExpand(select, expand, _model.Model, _model.Customer, _model.Customers); IEdmEntityTypeReference entityType = new EdmEntityTypeReference((specialCustomer ? _model.SpecialCustomer : _model.Customer), false); // Act SelectExpandNode selectExpandNode = SelectExpandNode.BuildSelectExpandNode(selectExpandClause, entityType, _model.Model); var result = selectExpandNode.ExpandedNavigationProperties.Keys; // Assert Assert.Equal(navigationPropertiesToExpand, String.Join(",", result.Select(p => p.Name).OrderBy(n => n))); }
public void ToDictionary_AppliesMappingToAllProperties_IfInstanceIsNotNull() { // Arrange EdmEntityType entityType = new EdmEntityType("NS", "Name"); entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32); EdmModel model = new EdmModel(); model.AddElement(entityType); model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity))); IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false); SelectExpandWrapper<TestEntity> testWrapper = new SelectExpandWrapper<TestEntity> { Instance = new TestEntity { SampleProperty = 42 }, ModelID = ModelContainer.GetModelID(model) }; Mock<IPropertyMapper> mapperMock = new Mock<IPropertyMapper>(); mapperMock.Setup(m => m.MapProperty("SampleProperty")).Returns("Sample"); Func<IEdmModel, IEdmStructuredType, IPropertyMapper> mapperProvider = (IEdmModel m, IEdmStructuredType t) => mapperMock.Object; // Act var result = testWrapper.ToDictionary(mapperProvider); // Assert Assert.Equal(42, result["Sample"]); }
public void ToDictionary_Throws_IfMappingIsNullOrEmpty_ForAGivenProperty(string propertyMapping) { // Arrange EdmEntityType entityType = new EdmEntityType("NS", "Name"); entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32); EdmModel model = new EdmModel(); model.AddElement(entityType); model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity))); IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false); SelectExpandWrapper<TestEntity> testWrapper = new SelectExpandWrapper<TestEntity> { Instance = new TestEntity { SampleProperty = 42 }, ModelID = ModelContainer.GetModelID(model) }; Mock<IPropertyMapper> mapperMock = new Mock<IPropertyMapper>(); mapperMock.Setup(m => m.MapProperty("SampleProperty")).Returns(propertyMapping); Func<IEdmModel, IEdmStructuredType, IPropertyMapper> mapperProvider = (IEdmModel m, IEdmStructuredType t) => mapperMock.Object; // Act & Assert Assert.Throws<InvalidOperationException>(() => testWrapper.ToDictionary(mapperProvider), "The key mapping for the property 'SampleProperty' can't be null or empty."); }
public void ToDictionary_Throws_IfMapperProvider_ReturnsNullPropertyMapper() { // Arrange EdmEntityType entityType = new EdmEntityType("NS", "Name"); entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32); EdmModel model = new EdmModel(); model.AddElement(entityType); model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity))); IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false); SelectExpandWrapper<TestEntity> wrapper = new SelectExpandWrapper<TestEntity> { Instance = new TestEntity { SampleProperty = 42 }, ModelID = ModelContainer.GetModelID(model) }; Func<IEdmModel, IEdmStructuredType, IPropertyMapper> mapperProvider = (IEdmModel m, IEdmStructuredType t) => null; // Act & Assert Assert.Throws<InvalidOperationException>(() => wrapper.ToDictionary(mapperProvider: mapperProvider), "The mapper provider must return a valid 'System.Web.Http.OData.Query.IPropertyMapper' instance for the given 'NS.Name' IEdmType."); }
private static IEdmFunctionImport AddBindableAction(EdmEntityContainer container, string name, IEdmEntityType bindingType, bool isCollection) { var action = container.AddFunctionImport(name, returnType: null, entitySet: null, sideEffecting: true, composable: false, bindable: true); IEdmTypeReference bindingParamterType = new EdmEntityTypeReference(bindingType, isNullable: false); if (isCollection) { bindingParamterType = new EdmCollectionTypeReference( new EdmCollectionType(bindingParamterType), isNullable: false); } action.AddParameter("bindingParameter", bindingParamterType); return action; }
public void Posting_NonDerivedType_To_Action_Expecting_BaseType_Throws() { StringContent content = new StringContent("{ '__metadata' : { 'type' : 'System.Web.Http.OData.Builder.TestModels.Motorcycle' } }"); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose"); IODataRequestMessage oDataRequest = new ODataMessageWrapper(content.ReadAsStreamAsync().Result, content.Headers); ODataMessageReader reader = new ODataMessageReader(oDataRequest, new ODataMessageReaderSettings(), _model); ODataDeserializerProvider deserializerProvider = new DefaultODataDeserializerProvider(); IEdmEntityTypeReference _motorcycle = new EdmEntityTypeReference(_model.SchemaElements.OfType<IEdmEntityType>().Single(t => t.Name == "Car"), isNullable: false); ODataDeserializerContext context = new ODataDeserializerContext(); context.Path = new ODataPath(new ActionPathSegment(_model.EntityContainers().Single().FunctionImports().Single(f => f.Name == "PostMotorcycle_When_Expecting_Car"))); Assert.Throws<ODataException>( () => new ODataEntityDeserializer(_motorcycle, deserializerProvider).Read(reader, context), "An entry with type 'System.Web.Http.OData.Builder.TestModels.Motorcycle' was found, " + "but it is not assignable to the expected type 'System.Web.Http.OData.Builder.TestModels.Car'. " + "The type specified in the entry must be equal to either the expected type or a derived type."); }
[InlineData("ID,Name,Orders/ID", "Orders", true, "ID")] // expand and select properties on expand on derived type -> select requested public void GetPropertiesToBeSelected_Selects_ExpectedProperties_OnExpandedOrders( string select, string expand, bool specialOrder, string structuralPropertiesToSelect) { // Arrange SelectExpandClause selectExpandClause = ODataUriParser.ParseSelectAndExpand(select, expand, _model.Model, _model.Customer, _model.Customers); SelectExpandClause nestedSelectExpandClause = selectExpandClause.Expansion.ExpandItems.SingleOrDefault().SelectExpandOption; IEdmEntityTypeReference entityType = new EdmEntityTypeReference((specialOrder ? _model.SpecialOrder : _model.Order), false); // Act SelectExpandNode selectExpandNode = SelectExpandNode.BuildSelectExpandNode(nestedSelectExpandClause, entityType, _model.Model); var result = selectExpandNode.SelectedStructuralProperties; // Assert Assert.Equal(structuralPropertiesToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n))); }
public void ToDictionary_ContainsAllStructuralProperties_IfInstanceIsNotNull() { // Arrange EdmModel model = new EdmModel(); EdmEntityType entityType = new EdmEntityType("NS", "Name"); model.AddElement(entityType); model.SetAnnotationValue(entityType, new ClrTypeAnnotation(typeof(TestEntity))); entityType.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Int32); IEdmTypeReference edmType = new EdmEntityTypeReference(entityType, isNullable: false); SelectExpandWrapper<TestEntity> testWrapper = new SelectExpandWrapper<TestEntity> { Instance = new TestEntity { SampleProperty = 42 }, ModelID = ModelContainer.GetModelID(model) }; // Act var result = testWrapper.ToDictionary(); // Assert Assert.Equal(42, result["SampleProperty"]); }
public void ApplyProperty_ThrowsOnKeyProperty_WhenPatchKeyModeIsThrow() { // Arrange ODataProperty property = new ODataProperty { Name = "Key1", Value = "Value1" }; EdmEntityType entityType = new EdmEntityType("namespace", "name"); entityType.AddKeys(new EdmStructuralProperty(entityType, "Key1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string)))); EdmEntityTypeReference entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false); ODataDeserializerProvider provider = new DefaultODataDeserializerProvider(EdmCoreModel.Instance); var resource = new Mock<IDelta>(MockBehavior.Strict); // Act && Assert Assert.Throws<InvalidOperationException>( () => ODataEntryDeserializer.ApplyProperty(property, entityTypeReference, resource.Object, provider, new ODataDeserializerContext { IsPatchMode = true, PatchKeyMode = PatchKeyMode.Throw }), "Cannot apply PATCH on key property 'Key1' on entity type 'namespace.name' when 'PatchKeyMode' is 'Throw'."); }