public void CollectionWithHeterogenousItemsErrorTest()
        {
            EdmModel model = new EdmModel();

            var complexType1 = model.ComplexType("ComplexTypeWithStringAndInteger32")
                               .Property("Property1", EdmCoreModel.Instance.GetString(true) as EdmTypeReference)
                               .Property("Property2", EdmCoreModel.Instance.GetInt32(false) as EdmTypeReference);

            var complexType2 = model.ComplexType("ComplexTypeWithStringAndDateTime")
                               .Property("Property1", EdmCoreModel.Instance.GetString(true) as EdmTypeReference)
                               .Property("Property2", EdmPrimitiveTypeKind.DateTimeOffset);

            model.Fixup();

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Primitive collection containing items of different primitive types
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32")).Item(1).Item(true).Item(2).WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_CannotConvertPrimitiveValue", "True", "Edm.Int32")
                    }
                },
                // Complex collection containing items of different complex type (correct type attribute value)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName(complexType1.FullName()))
                                     .Item(PayloadBuilder.ComplexValue(complexType1.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", -1))
                                     .Item(PayloadBuilder.ComplexValue(complexType2.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", DateTimeOffset.Now))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(complexType1.ToTypeReference())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", "TestModel.ComplexTypeWithStringAndDateTime", "TestModel.ComplexTypeWithStringAndInteger32"),
                },
                // Complex collection containing items of different complex type (incorrect type attribute value)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName(complexType2.FullName()))
                                     .Item(PayloadBuilder.ComplexValue(complexType2.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", -1))
                                     .Item(PayloadBuilder.ComplexValue(complexType2.FullName()).PrimitiveProperty("Property1", "Foo").PrimitiveProperty("Property2", DateTimeOffset.Now))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(complexType2.ToTypeReference())),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_CannotConvertPrimitiveValue", "-1", "Edm.DateTimeOffset")
                    }
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor = testDescriptor.InProperty("RootProperty");
                testDescriptor.RunTest(testConfiguration);
            });
        }
示例#2
0
 /// <summary>
 /// Visits a primitive value.
 /// </summary>
 /// <param name="primitiveValue">The primitive value to visit.</param>
 protected override ODataPayloadElement VisitPrimitiveValue(object primitiveValue)
 {
     if (primitiveValue == null)
     {
         return(new PrimitiveValue(null, null));
     }
     else
     {
         return(new PrimitiveValue(EntityModelUtils.GetPrimitiveEdmType(primitiveValue.GetType()).FullEdmName(), primitiveValue));
     }
 }
示例#3
0
        /// <summary>
        /// Visits the payload element
        /// </summary>
        /// <param name="payloadElement">The payload element to visit</param>
        public override void Visit(ComplexMultiValue payloadElement)
        {
            EntityModelTypeAnnotation typeAnnotation = payloadElement.GetAnnotation <EntityModelTypeAnnotation>();

            if (payloadElement.FullTypeName == null && typeAnnotation != null)
            {
                payloadElement.FullTypeName = EntityModelUtils.GetCollectionTypeName(((IEdmCollectionTypeReference)typeAnnotation.EdmModelType).ElementType().FullName());
            }

            base.Visit(payloadElement);
        }
        public void ConvertToUriLiteralWhenIeee754CompatibleSetTrue()
        {
            string expectedWhenieee754ParamSetFalse = "[-9223372036854775808,9223372036854775807]";
            string expectedWhenieee754ParamSetTrue  = "[\"-9223372036854775808\",\"9223372036854775807\"]";

            ODataCollectionValue parameter = new ODataCollectionValue
            {
                TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Int64"),
                Items    = new object[] { Int64.MinValue, Int64.MaxValue }
            };

            string actualWhenieee754ParamSetFalse = ODataUriUtils.ConvertToUriLiteral(parameter, ODataVersion.V4, null, false);
            string actualWhenieee754ParamSetTrue  = ODataUriUtils.ConvertToUriLiteral(parameter, ODataVersion.V4, null, true);

            Assert.AreEqual(expectedWhenieee754ParamSetFalse, actualWhenieee754ParamSetFalse, "Ieee754Compatible was not properly set");
            Assert.AreEqual(expectedWhenieee754ParamSetTrue, actualWhenieee754ParamSetTrue, "Ieee754Compatible was not properly set");
        }
        /// <summary>
        /// Resolves the specified Edm Data Type from the payload model.
        /// </summary>
        /// <param name="fullTypeName">The full name of the type to resolve.</param>
        /// <returns>The EdmDataType that corresponds to the type name.</returns>
        private IEdmTypeReference ResolvePropertyEdmDataType(string fullTypeName)
        {
            if (string.IsNullOrEmpty(fullTypeName))
            {
                return(null);
            }

            bool propertyIsCollection = false;

            if (fullTypeName.StartsWith(EdmConstants.CollectionTypeQualifier))
            {
                fullTypeName         = EntityModelUtils.GetCollectionItemTypeName(fullTypeName);
                propertyIsCollection = true;
            }

            string namespaceName;
            string typeName;

            DataTypeUtils.ParseFullTypeName(fullTypeName, out typeName, out namespaceName);

            IEdmTypeReference edmDataType = null;

            var complexType = this.testDescriptor.PayloadEdmModel.FindType(fullTypeName);

            if (complexType != null)
            {
                edmDataType = complexType.ToTypeReference();
            }
            else
            {
                var primitiveType = EdmCoreModel.Instance.GetPrimitive(EdmCoreModel.Instance.GetPrimitiveTypeKind(typeName), true);
                ExceptionUtilities.CheckObjectNotNull(primitiveType, "Failed to resolve type: " + fullTypeName);
                edmDataType = primitiveType;
            }

            if (propertyIsCollection)
            {
                edmDataType = EdmCoreModel.GetCollection(edmDataType);
            }

            return(edmDataType);
        }
示例#6
0
        public void SpatialPropertyWithDisabledPrimitiveTypeConversionTest()
        {
            IEdmModel testModel = TestModels.BuildTestModel();

            var testValues = new object[]
            {
                GeographyFactory.Point(10, 20).Build(),
                GeometryFactory.Point(10, 20).Build()
            };

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors =
                TestValues.PrimitiveTypes.SelectMany(primitiveTypes => testValues.Select(testValue =>
            {
                PrimitiveDataType targetType       = EntityModelUtils.GetPrimitiveEdmType(primitiveTypes);
                ODataPayloadElement payloadElement = PayloadBuilder
                                                     .Property(null, PayloadBuilder.PrimitiveValue(testValue))
                                                     .ExpectedPropertyType(targetType);
                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                    PayloadEdmModel = testModel
                });
            }));

            // TODO: Task 1429690:Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                new bool[] { false, true },
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testDescriptor, disableStrictValidation, testConfig) =>
            {
                testConfig = new ReaderTestConfiguration(testConfig);
                testConfig.MessageReaderSettings.EnablePrimitiveTypeConversion = false;
                if (disableStrictValidation)
                {
                    testConfig = testConfig.CloneAndApplyBehavior(TestODataBehaviorKind.WcfDataServicesServer);
                }
                testDescriptor.RunTest(testConfig);
            });
        }
示例#7
0
        public void DuplicatePropertyNamesTest()
        {
            PropertyInstance primitiveProperty = PayloadBuilder.PrimitiveProperty("DuplicateProperty", 42);
            PropertyInstance complexProperty   = PayloadBuilder.Property("DuplicateProperty",
                                                                         PayloadBuilder.ComplexValue("TestModel.DuplicateComplexType").PrimitiveProperty("Name", "foo"));
            PropertyInstance collectionProperty = PayloadBuilder.Property("DuplicateProperty",
                                                                          PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")).WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(false))));

            PropertyInstance[] allProperties = new[] { primitiveProperty, complexProperty, collectionProperty };
            PropertyInstance[] propertiesWithPossibleDuplication = new[] { primitiveProperty, complexProperty };
            PropertyInstance[] propertiesWithNoDuplication       = new[] { collectionProperty };

            IEnumerable <DuplicatePropertySet> duplicatePropertySets;

            // Those which may allow duplication
            duplicatePropertySets = propertiesWithPossibleDuplication
                                    .Variations(2).Select(properties => new DuplicatePropertySet {
                Properties = properties, DuplicationPotentiallyAllowed = true
            });

            // Then for each in those which don't allow duplication try it against all the others
            duplicatePropertySets = duplicatePropertySets.Concat(propertiesWithNoDuplication.SelectMany(
                                                                     propertyWithNoDuplication => allProperties.SelectMany(otherProperty =>
                                                                                                                           new[]
            {
                new DuplicatePropertySet {
                    Properties = new [] { propertyWithNoDuplication, otherProperty }, DuplicationPotentiallyAllowed = false
                },
                new DuplicatePropertySet {
                    Properties = new [] { otherProperty, propertyWithNoDuplication }, DuplicationPotentiallyAllowed = false
                },
            })));

            this.CombinatorialEngineProvider.RunCombinations(
                duplicatePropertySets,
                new bool[] { false, true },
                new bool[] { true, false },
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (duplicatePropertySet, allowDuplicateProperties, useMetadata, testConfiguration) =>
            {
                EdmModel model  = new EdmModel();
                var complexType = model.ComplexType("DuplicateComplexType");
                complexType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
                model.Fixup();

                PropertyInstance firstProperty  = duplicatePropertySet.Properties.ElementAt(0);
                PropertyInstance secondProperty = duplicatePropertySet.Properties.ElementAt(1);

                // Non-metadata reading is not possible in JSON
                if (!useMetadata && (testConfiguration.Format == ODataFormat.Json))
                {
                    return;
                }

                // If we will have metadata then we can only allow combinations of the same kind
                if (useMetadata)
                {
                    if (firstProperty.ElementType != secondProperty.ElementType)
                    {
                        return;
                    }
                }

                // Copy the test config
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                if (allowDuplicateProperties)
                {
                    testConfiguration.MessageReaderSettings.EnableODataServerBehavior();
                }

                // Create a descriptor with the first property
                PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = firstProperty,
                    PayloadEdmModel = useMetadata ? model : null
                };

                // Now generate entity around it
                testDescriptor = testDescriptor.InComplexValue(5, 5);

                // Now add the second property to it
                ((ComplexInstance)testDescriptor.PayloadElement).Add(secondProperty);

                // [Astoria-ODataLib-Integration] Parsing of URLs on OData recognized places may fail, but Astoria server doesn't
                // Server does not read named stream links for Atom payload therefore the expected payload needs to be normalized
                if (testConfiguration.Format == ODataFormat.Atom)
                {
                    testDescriptor.ExpectedResultNormalizers.Add(config => (payloadElement => WcfDsServerPayloadElementNormalizer.Normalize(payloadElement, ODataFormat.Atom, testDescriptor.PayloadEdmModel as EdmModel)));
                }

                // We expect failure only if we don't allow duplicates or if the property kind doesn't allow duplicates ever
                if ((!duplicatePropertySet.DuplicationPotentiallyAllowed || !allowDuplicateProperties))
                {
                    testDescriptor.ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", "DuplicateProperty");
                }

                IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
                {
                    testDescriptor.InProperty("TopLevelProperty"),
                    testDescriptor.InProperty("ComplexProperty").InEntity(2, 2),
                    testDescriptor.InCollection(5, 5).InProperty("TopLevelCollection"),
                };

                this.CombinatorialEngineProvider.RunCombinations(
                    testDescriptors,
                    td =>
                {
                    var property = td.PayloadElement as PropertyInstance;
                    if (property != null && testConfiguration.Format == ODataFormat.Atom)
                    {
                        property.Name = null;
                    }
                    td.RunTest(testConfiguration);
                });
            });
        }
        public void CollectionWithHeterogenousItemsTest()
        {
            EdmModel       edmModel = new EdmModel();
            EdmComplexType edmComplexTypeMyComplexType = edmModel.ComplexType("MyComplexType", ModelNamespace);

            edmComplexTypeMyComplexType.Property("P1", EdmPrimitiveTypeKind.Int32, false).Property("P2", EdmPrimitiveTypeKind.String, true);
            edmModel.Fixup();

            var edmCollectionTypeOfIntegerType = new EdmCollectionType(EdmCoreModel.Instance.GetInt32(false));
            var edmCollectionTypeOfStringType  = new EdmCollectionType(EdmCoreModel.Instance.GetString(true));

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Primitive collection with complex item
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String"))
                                     .XmlValueRepresentation("<m:element><d:P1>0</d:P1><d:P2>Foo</d:P2></m:element>", EntityModelUtils.GetCollectionTypeName("Edm.String"), null)
                                     .WithTypeAnnotation(edmCollectionTypeOfStringType),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32"))
                                     .XmlValueRepresentation("<m:element>0</m:element><m:element><d:P1>0</d:P1><d:P2>Foo</d:P2></m:element>", EntityModelUtils.GetCollectionTypeName("Edm.Int32"), null)
                                     .WithTypeAnnotation(edmCollectionTypeOfIntegerType),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element"),
                },
                // Complex collection with primitive item
                // Note - the text nodes (of the primitive items) are ignored in complex values - leaving empty complex values
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.MyComplexType"))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.MyComplexType").PrimitiveProperty("P1", 987).AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.MyComplexType").PrimitiveProperty("P1", 123).AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                     .XmlValueRepresentation("<m:element>Foo<d:P1>987</d:P1></m:element><m:element><d:P1>123</d:P1>Bar</m:element>", EntityModelUtils.GetCollectionTypeName("TestModel.MyComplexType"), null),
                    PayloadEdmModel = edmModel,
                },
                // Primitive collection containing a primitive and a nested collection
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String"))
                                     .XmlValueRepresentation("<m:element>Foo</m:element><m:element><m:element>0</m:element><m:element>1</m:element></m:element>", EntityModelUtils.GetCollectionTypeName("Edm.String"), null)
                                     .WithTypeAnnotation(edmCollectionTypeOfStringType),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element"),
                },
            };

            testDescriptors = testDescriptors.Select(td => td.InProperty());

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void CollectionValueTest()
        {
            EdmModel       edmModel = new EdmModel();
            EdmComplexType edmComplexTypeMyComplexType = edmModel.ComplexType("MyComplexType", ModelNamespace);

            edmComplexTypeMyComplexType.Property("P1", EdmPrimitiveTypeKind.Int32, false).Property("P2", EdmPrimitiveTypeKind.String, true);
            edmModel.Fixup();

            var edmCollectionTypeOfIntegerType   = new EdmCollectionType(EdmCoreModel.Instance.GetInt32(false));
            var edmCollectionTypeOfMyComplexType = new EdmCollectionType(new EdmComplexTypeReference(edmComplexTypeMyComplexType, true));
            // Create payloads of the collection properties
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Empty element collection
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32"))
                                     .XmlValueRepresentation(new XNode[0])
                                     .WithTypeAnnotation(edmCollectionTypeOfIntegerType),
                    PayloadEdmModel = edmModel,
                },
                // Collections containing collections are not supported
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .XmlValueRepresentation("<m:element />", EntityModelUtils.GetCollectionTypeName(EntityModelUtils.GetCollectionTypeName("Edm.String")), null)
                                     .WithTypeAnnotation(edmCollectionTypeOfIntegerType),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_NestedCollectionsAreNotSupported"),
                },
            };

            var primitivePayloadsWithPadding = new CollectionPaddingPayloadTextCase <PrimitiveMultiValue>[]
            {
                new CollectionPaddingPayloadTextCase <PrimitiveMultiValue>
                {
                    XmlValue       = "{0}",
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32"))
                                     .WithTypeAnnotation(edmCollectionTypeOfIntegerType)
                },
                new CollectionPaddingPayloadTextCase <PrimitiveMultiValue>
                {
                    XmlValue       = "{0}<m:element>42</m:element>",
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32"))
                                     .Item(42)
                                     .WithTypeAnnotation(edmCollectionTypeOfIntegerType)
                },
                new CollectionPaddingPayloadTextCase <PrimitiveMultiValue>
                {
                    XmlValue       = "<m:element>42</m:element>{0}",
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32"))
                                     .Item(42)
                                     .WithTypeAnnotation(edmCollectionTypeOfIntegerType)
                },
            };

            var complexPayloadsWithPadding = new CollectionPaddingPayloadTextCase <ComplexMultiValue>[]
            {
                new CollectionPaddingPayloadTextCase <ComplexMultiValue>
                {
                    XmlValue       = "<m:element><d:P1>42</d:P1></m:element>{0}<m:element><d:P2>test</d:P2></m:element>",
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.MyComplexType"))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.MyComplexType").PrimitiveProperty("P1", 42).AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.MyComplexType").PrimitiveProperty("P2", "test").AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                     .WithTypeAnnotation(edmCollectionTypeOfMyComplexType)
                },
            };

            var xmlPadding = new CollectionXmlPadding[]
            {
                // Nothing
                new CollectionXmlPadding
                {
                    Padding = string.Empty,
                },
                // Whitespace only
                new CollectionXmlPadding
                {
                    Padding = "  \r\n\t",
                },
                // Insignificant nodes
                new CollectionXmlPadding
                {
                    Padding = "<!--s--> <?value?>",
                },
                // Element in no namespace
                new CollectionXmlPadding
                {
                    Padding = "<foo xmlns=''/>",
                },
                // Element in custom namespace
                new CollectionXmlPadding
                {
                    Padding = "<c:foo xmlns:c='uri' attr='1'><c:child/>text</c:foo>",
                },
                // Element in metadata namespace (should be ignored as well)
                new CollectionXmlPadding
                {
                    Padding = "<m:properties/>",
                },
                // Element in atom namespace (should also be ignored)
                new CollectionXmlPadding
                {
                    Padding = "<entry/>",
                },
                // Significant nodes - will be ignored
                new CollectionXmlPadding
                {
                    Padding = "some text <![CDATA[cdata]]>",
                },
                // Element in the d namespace should fail
                new CollectionXmlPadding
                {
                    Padding           = "<d:foo/>",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomPropertyAndValueDeserializer_InvalidCollectionElement", "foo", "http://docs.oasis-open.org/odata/ns/metadata"),
                },
                // Element in the d namespace should fail (wrong name)
                new CollectionXmlPadding
                {
                    Padding           = "<d:Element/>",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomPropertyAndValueDeserializer_InvalidCollectionElement", "Element", "http://docs.oasis-open.org/odata/ns/metadata"),
                },
            };

            testDescriptors = testDescriptors.Concat(this.CreatePayloadWithPaddingTestDescriptor(
                                                         primitivePayloadsWithPadding, xmlPadding, edmModel));

            testDescriptors = testDescriptors.Concat(this.CreatePayloadWithPaddingTestDescriptor(
                                                         complexPayloadsWithPadding, xmlPadding, edmModel));

            testDescriptors = testDescriptors.Select(td => td.InProperty());

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void CollectionNoMetadataTest()
        {
            string collectionOfStringTypeName = EntityModelUtils.GetCollectionTypeName("Edm.String");
            string collectionOfInt32TypeName  = EntityModelUtils.GetCollectionTypeName("Edm.Int32");
            string collectionOfComplexType    = EntityModelUtils.GetCollectionTypeName("TestModel.ComplexType");

            // Create payloads of the collection properties
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Single empty m:element in >=V3
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .XmlValueRepresentation("<m:element/>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Single m:element with no content in >= V3
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .XmlValueRepresentation("<m:element></m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Two m:element items in >= V3
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .Item("foo")
                                     .XmlValueRepresentation("<m:element></m:element><m:element>foo</m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Two m:element items with insiginificant nodes >= V3
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .Item("foo")
                                     .XmlValueRepresentation("  <m:element></m:element>\r\n<?value?><m:element>foo</m:element><!--some-->", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Two m:element items with text nodes >= V3
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .Item("foo")
                                     .XmlValueRepresentation("foo<m:element></m:element>bar<m:element>foo</m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Two m:element items with custom element >= V3
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .Item("foo")
                                     .XmlValueRepresentation("<m:foo/><m:element></m:element><m:bar>some</m:bar><m:element>foo</m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Two m:element items with custom element with m:element in it (which is to be ignored)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .Item("foo")
                                     .XmlValueRepresentation("<m:foo/><m:element></m:element><m:bar><m:element/></m:bar><m:element>foo</m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Two m:element items with custom element with d:prop in it (which is to be ignored)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .Item(string.Empty)
                                     .Item("foo")
                                     .XmlValueRepresentation("<m:foo/><m:element></m:element><m:bar><d:prop/></m:bar><m:element>foo</m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Nested m:element items (error)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .XmlValueRepresentation("<m:element><m:element>0</m:element><m:element>1</m:element></m:element>", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_InvalidItemTypeKind", "Collection"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },

                #region No collection type name tests
                // No collection type name and string items (with and without type names)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue().Item("foo").Item(new PrimitiveValue(/*fullTypeName*/ null, "bar"))
                                     .XmlValueRepresentation("<m:element m:type='Edm.String'>foo</m:element><m:element>bar</m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and Int32 items
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue().Item(1).Item(2)
                                     .XmlValueRepresentation("<m:element m:type='Edm.Int32'>1</m:element><m:element m:type='Edm.Int32'>2</m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and complex items
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("StringProperty", "abc"))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("StringProperty", "123"))
                                     .XmlValueRepresentation("<m:element m:type='TestModel.ComplexType'><d:StringProperty>abc</d:StringProperty></m:element><m:element m:type='TestModel.ComplexType'><d:StringProperty>123</d:StringProperty></m:element>", null, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and different item type kinds (complex instead of primitive)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue()
                                     .XmlValueRepresentation("<m:element>0</m:element><m:element><d:bar>2</d:bar></m:element>", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and item type kind does not match item type name (primitive and complex items)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .XmlValueRepresentation("<m:element></m:element><m:element><d:bar>2</d:bar></m:element>", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and item type names don't match (Edm.String and Edm.Int32)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .XmlValueRepresentation("<m:element></m:element><m:element m:type='Edm.Int32'>2</m:element>", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and item type names don't match (Edm.String and Edm.Int32); including some null items
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .XmlValueRepresentation("<m:element m:null='true' /><m:element></m:element><m:element m:null='true' /><m:element m:type='Edm.Int32'>2</m:element><m:element m:null='true' />", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and item type names don't match (TestModel.SomeComplexType and TestModel.OtherComplexType)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .XmlValueRepresentation("<m:element m:type='TestModel.SomeComplexType'><d:SomeProperty /></m:element><m:element m:type='TestModel.OtherComplexType'><d:OtherProperty /></m:element>", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "TestModel.OtherComplexType", "TestModel.SomeComplexType"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and item type names don't match (TestModel.SomeComplexType and TestModel.OtherComplexType); including some null items
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .XmlValueRepresentation("<m:element m:null='true' /><m:element m:type='TestModel.SomeComplexType'></m:element><m:element m:null='true' /><m:element m:type='TestModel.OtherComplexType'></m:element><m:element m:null='true' />", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "TestModel.OtherComplexType", "TestModel.SomeComplexType"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // No collection type name and different item type kinds (primitive instead of complex)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .XmlValueRepresentation("<m:element m:type='TestModel.SomeComplexType'><m:bar>2</m:bar></m:element><m:element>0</m:element>", null, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },

                #endregion No collection type name tests

                #region Collection with type name tests
                // Collection with type name and string items (without type names) >= V3
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(collectionOfStringTypeName).Item("test")
                                     .XmlValueRepresentation("<m:element>test</m:element>", collectionOfStringTypeName, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Collection with type name and string items (with and without type names)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(collectionOfStringTypeName).Item("foo").Item(new PrimitiveValue(/*fullTypeName*/ null, "bar"))
                                     .XmlValueRepresentation("<m:element m:type='Edm.String'>foo</m:element><m:element>bar</m:element>", collectionOfStringTypeName, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Collection with type name and Int32 items (with type names)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(collectionOfInt32TypeName).Item(1).Item(2)
                                     .XmlValueRepresentation("<m:element m:type='Edm.Int32'>1</m:element><m:element m:type='Edm.Int32'>2</m:element>", collectionOfInt32TypeName, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Collection with type name and Int32 items (without type names)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(collectionOfInt32TypeName)
                                     .Item(new PrimitiveValue(/*fullTypeName*/ null, 1))
                                     .Item(new PrimitiveValue(/*fullTypeName*/ null, 2))
                                     .XmlValueRepresentation("<m:element>1</m:element><m:element>2</m:element>", collectionOfInt32TypeName, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Collection with type name and complex items (with type names)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(collectionOfComplexType)
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("bar", "1"))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("bar", "2"))
                                     .XmlValueRepresentation("<m:element m:type='TestModel.ComplexType'><d:bar>1</d:bar></m:element><m:element m:type='TestModel.ComplexType'><d:bar>2</d:bar></m:element>", collectionOfComplexType, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Collection with type name and complex items (without type names)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(collectionOfComplexType)
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("bar", "1").AddAnnotation(new SerializationTypeNameTestAnnotation {
                        TypeName = null
                    }))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("bar", "2").AddAnnotation(new SerializationTypeNameTestAnnotation {
                        TypeName = null
                    }))
                                     .XmlValueRepresentation("<m:element><d:bar>1</d:bar></m:element><m:element><d:bar>2</d:bar></m:element>", collectionOfComplexType, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Primitive collection with type name and different item type kinds (complex instead of primitive)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(collectionOfInt32TypeName)
                                     .XmlValueRepresentation("<m:element m:type='Edm.Int32'>0</m:element><m:element m:type='TestModel.SomeComplexType'><d:bar>2</d:bar></m:element>", collectionOfInt32TypeName, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Primitive collection with type name and different item type kinds (invalid element in primitive)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(collectionOfInt32TypeName)
                                     .XmlValueRepresentation("<m:element m:type='Edm.Int32'>0</m:element><m:element><d:bar>2</d:bar></m:element>", collectionOfInt32TypeName, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Complex collection type with type name and different item type kinds (primitive instead of complex)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(collectionOfComplexType)
                                     .XmlValueRepresentation("<m:element m:type='TestModel.ComplexType'><d:bar>2</d:bar></m:element><m:element m:type='Edm.Int32'>0</m:element>", collectionOfComplexType, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Complex collection type with type name and mixed content - primitive value at the same level as complex value
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(collectionOfComplexType)
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("bar", "2").AddAnnotation(new SerializationTypeNameTestAnnotation {
                        TypeName = null
                    }))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("bar", "3").AddAnnotation(new SerializationTypeNameTestAnnotation {
                        TypeName = null
                    }))
                                     .XmlValueRepresentation("<m:element><d:bar>2</d:bar></m:element><m:element>0<d:bar>3</d:bar></m:element>", collectionOfComplexType, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Primitive collection with type name and inconsistent item type names
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(collectionOfInt32TypeName).Item(new PrimitiveValue(/*fullTypeName*/ null, 0)).Item(1)
                                     .XmlValueRepresentation("<m:element>0</m:element><m:element m:type='Edm.Int32'>1</m:element>", collectionOfInt32TypeName, null),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                // Complex collection type with type name and inconsistent item type names
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(collectionOfComplexType)
                                     .XmlValueRepresentation("<m:element m:type='TestModel.SomeComplexType'><d:foo>1</d:foo></m:element><m:element><d:bar>2</d:bar></m:element>", collectionOfComplexType, null),
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "TestModel.SomeComplexType", "TestModel.ComplexType"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                },
                #endregion Collection with type name and inconsistent payload items
            };

            // Wrap it in property (manually to prevent any type annotations)
            testDescriptors = testDescriptors.Select(td => td.InProperty());

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
示例#11
0
        public void PrimitiveTopLevelValueWithDisabledTypeConversionTest()
        {
            IEdmModel testModel = TestModels.BuildTestModel();

            IEnumerable <ReaderContentTypeTestDescriptor> testDescriptors = primitiveValueConversionTestCases
                                                                            .SelectMany(testCase => TestValues.PrimitiveTypes
                                                                                        .SelectMany(nonNullableTargetType => new bool[] { true, false }
                                                                                                    .SelectMany(includeNullableType => new bool[] { true, false }
                                                                                                                .Select(useExpectedType =>
            {
                PrimitiveDataType targetType = EntityModelUtils.GetPrimitiveEdmType(nonNullableTargetType);
                if (includeNullableType)
                {
                    targetType = targetType.Nullable();
                }

                ODataPayloadElement resultValue;
                if (nonNullableTargetType == typeof(byte[]))
                {
                    resultValue = testCase.ConversionValues.Where(cv => cv.ClrValue.GetType() == typeof(byte[])).Single().DeepCopy();
                }
                else
                {
                    resultValue = testCase.ConversionValues.Where(cv => cv.ClrValue.GetType() == typeof(string)).Single().DeepCopy();
                }

                ODataPayloadElement payloadElement;
                if (useExpectedType)
                {
                    payloadElement = PayloadBuilder.PrimitiveValue(testCase.SourceString).ExpectedPrimitiveValueType(targetType);
                }
                else
                {
                    payloadElement = PayloadBuilder.PrimitiveValue(testCase.SourceString);
                }

                return(new ReaderContentTypeTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                    ExpectedResultPayloadElement = (testConfig) => resultValue,
                    ContentType = ComputeContentType(nonNullableTargetType),
                    ExpectedFormat = ODataFormat.RawValue,
                });
            }))));

            // add variants that use a metadata provider
            testDescriptors = testDescriptors.Concat(testDescriptors.Select(td => new ReaderContentTypeTestDescriptor(td)
            {
                PayloadEdmModel = testModel
            }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                // restricting the set of default format configurations to limiti runtime of the tests
                this.ReaderTestConfigurationProvider.DefaultFormatConfigurations.Where(tc => tc.MessageReaderSettings.EnableMessageStreamDisposal && !tc.IsRequest),
                (testDescriptor, testConfig) =>
            {
                testConfig = new ReaderTestConfiguration(testConfig);
                testConfig.MessageReaderSettings.EnablePrimitiveTypeConversion = false;

                testDescriptor.RunTest(testConfig);
            });
        }
        public void StreamPropertiesNegativeTests()
        {
            EdmModel model = new EdmModel();

            EdmComplexType edmComplexType = new EdmComplexType("TestModel", "MyComplexType");

            edmComplexType.AddStructuralProperty("Stream1", EdmCoreModel.Instance.GetStream(false));
            model.AddElement(edmComplexType);

            EdmEntityType edmEntityType = new EdmEntityType("TestModel", "EntityTypeForStreams");

            edmEntityType.AddStructuralProperty("Complex", new EdmComplexTypeReference(edmComplexType, false));
            edmEntityType.AddStructuralProperty("Collection", EdmCoreModel.GetCollection(new EdmComplexTypeReference(edmComplexType, false)));
            edmEntityType.AddStructuralProperty("Int32Collection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
            edmEntityType.AddStructuralProperty("NamedStreamCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetStream(false)));
            model.AddElement(edmEntityType);

            var edmEntityContainer = new EdmEntityContainer("TestModel", "DefaultContainer");

            model.AddElement(edmEntityContainer);

            var entitySet = edmEntityContainer.AddEntitySet("EntitySetForStreams", edmEntityType);

            var testCases = new[] {
                // Note that negative test cases to validate the content of an ODataStreamReferenceValue are in WriteInputValidationTests.cs.
                // TODO: We need to add these test cases for writing top level properties and metadata as well.
                new { // named stream properties are not allowed on complex types
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Complex",
                        Value = new ODataComplexValue()
                        {
                            TypeName   = "TestModel.MyComplexType",
                            Properties = new[]
                            {
                                new ODataProperty()
                                {
                                    Name  = "Stream1",
                                    Value = new ODataStreamReferenceValue()
                                    {
                                        EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                    }
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                },
                new { // named stream properties are not allowed on complex collection types
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Collection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("TestModel.MyComplexType"),
                            Items    = new[]
                            {
                                new ODataComplexValue()
                                {
                                    TypeName   = "TestModel.MyComplexType",
                                    Properties = new[]
                                    {
                                        new ODataProperty()
                                        {
                                            Name  = "Stream1",
                                            Value = new ODataStreamReferenceValue()
                                            {
                                                EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                },
                // TODO: Add the following case for the top-level collection writer as well.
                new { // named stream collection properties are not allowed.
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Int32Collection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Int32"),
                            Items    = new[]
                            {
                                new ODataStreamReferenceValue()
                                {
                                    EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                },
                new { // named stream collection properties are not allowed - with valid type.
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "NamedStreamCollection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Stream"),
                            Items    = new[]
                            {
                                new ODataStreamReferenceValue()
                                {
                                    EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("EdmLibraryExtensions_CollectionItemCanBeOnlyPrimitiveEnumComplex"),
                },
            };

            var testDescriptors = testCases.SelectMany(testCase =>
            {
                ODataEntry entry = new ODataEntry()
                {
                    TypeName          = "TestModel.EntityTypeForStreams",
                    Properties        = new ODataProperty[] { testCase.NamedStreamProperty },
                    SerializationInfo = new ODataFeedAndEntrySerializationInfo()
                    {
                        NavigationSourceEntityTypeName = "TestModel.EntityTypeForStreams",
                        ExpectedTypeName     = "TestModel.EntityTypeForStreams",
                        NavigationSourceName = "MySet"
                    }
                };
                return(new []
                {
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        entry,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testCase.ExpectedExceptionWithoutModel
                    })
                    {
                        Model = null,
                    },
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        entry,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testCase.ExpectedExceptionWithModel
                    })
                    {
                        Model = model,
                        PayloadEdmElementContainer = entitySet,
                        PayloadEdmElementType = edmEntityType,
                    },
                });
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testDescriptor.Model == null && testConfiguration.Format == ODataFormat.Json)
                {
                    return;
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
示例#13
0
            /// <summary>
            /// Visits a collection item.
            /// </summary>
            /// <param name="collectionValue">The collection to visit.</param>
            protected override ODataPayloadElement VisitCollectionValue(ODataCollectionValue collectionValue)
            {
                if (collectionValue == null)
                {
                    return(new PrimitiveMultiValue(null, true));
                }

                bool?isPrimitiveCollection = null;

                // Try to parse the type name and if the item type name is a primitive EDM type, then this is a primitive collection.
                string typeName = collectionValue.TypeName;

                if (typeName != null)
                {
                    string itemTypeName = EntityModelUtils.GetCollectionItemTypeName(typeName);
                    isPrimitiveCollection = itemTypeName != null && EntityModelUtils.GetPrimitiveEdmType(itemTypeName) != null;
                }

                List <object> items = new List <object>();

                foreach (object item in collectionValue.Items)
                {
                    if (!isPrimitiveCollection.HasValue)
                    {
                        ODataComplexValue complexItemValue = item as ODataComplexValue;

                        // If the first item is a complex value, then the collection is of complex kind.
                        // Note that if the first item is null, we assume primitive collection, since we can't really decide (and it's an invalid thing anyway)
                        isPrimitiveCollection = complexItemValue == null;
                    }

                    if (isPrimitiveCollection.Value)
                    {
                        items.Add((PrimitiveValue)this.Visit(item));
                    }
                    else
                    {
                        ODataComplexValue complexItemValue = item as ODataComplexValue;
                        ExceptionUtilities.Assert(
                            item == null || complexItemValue != null,
                            "The collection was determined to be of complex values but one of its items is not an ODataComplexValue.");
                        items.Add((ComplexInstance)this.Visit(complexItemValue));
                    }
                }

                if (!isPrimitiveCollection.HasValue)
                {
                    // If we could not tell until now (possible only if there was no type name and no items)
                    // assume primitive collection.
                    isPrimitiveCollection = true;
                }

                if (isPrimitiveCollection == true)
                {
                    PrimitiveMultiValue primitiveCollection = new PrimitiveMultiValue(typeName, false);
                    foreach (object item in items)
                    {
                        primitiveCollection.Add((PrimitiveValue)item);
                    }

                    this.ConvertSerializationTypeNameAnnotation(collectionValue, primitiveCollection);

                    return(primitiveCollection);
                }
                else
                {
                    ComplexMultiValue complexCollection = new ComplexMultiValue(typeName, false);
                    foreach (object item in items)
                    {
                        complexCollection.Add((ComplexInstance)item);
                    }

                    this.ConvertSerializationTypeNameAnnotation(collectionValue, complexCollection);

                    return(complexCollection);
                }
            }
        public void ConvertToUriLiteralCollectionTest()
        {
            List <ConvertToUriLiteralTestCase> testCases = new List <ConvertToUriLiteralTestCase>();

            #region Collection

            // empty collection
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                    TypeName = EntityModelUtils.GetCollectionTypeName("Edm.String")
                },
                ExpectedValue = "[]",
            });
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                    TypeName = EntityModelUtils.GetCollectionTypeName("NameSpace.MyType")
                },
                ExpectedValue = "[]",
            });
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                },
                ExpectedValue = "[]",
            });

            //// collection with one item
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                    TypeName = EntityModelUtils.GetCollectionTypeName("Edm.String"), Items = new string[] { "value" }
                },
                ExpectedValue = "[\"value\"]",
            });

            //// collection of spatial type
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                    TypeName = EntityModelUtils.GetCollectionTypeName("Edm.GeographyPoint"), Items = new[] { GeographyFactory.Point(5.0, -10.0).Build() }
                },
                ExpectedValue = "[{\"type\":\"Point\",\"coordinates\":[-10.0,5.0],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4326\"}}}]",
            });

            // collection with multiple items
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                    TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Int64"), Items = new object[] { Int64.MinValue, Int64.MaxValue }
                },
                ExpectedValue = "[\"-9223372036854775808\",\"9223372036854775807\"]",
            });
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                    Items = new object[] { Int64.MinValue, Int64.MaxValue }
                },
                ExpectedValue = "[\"-9223372036854775808\",\"9223372036854775807\"]",
            });
            #endregion

            this.RunTestCases(testCases);
        }
        public void CollectionWithoutExpectedTypeAndWithMetadataTest()
        {
            // For now only top-level property can do this.
            // TODO: Once we have open properties, these test cases apply to those as well, then probably move these to the top-level property
            // tests and share them from the open properties test, or possible keep both here.

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = this.CreateCollectionPayloadsWithMetadata(true);

            testDescriptors = testDescriptors.Concat(this.CreateInvalidCollectionsWithTypeNames(false));

            EdmModel       model           = new EdmModel();
            EdmComplexType itemComplexType = model.ComplexType("ItemComplexType").Property("stringProperty", EdmPrimitiveTypeKind.String);

            model = model.Fixup();

            testDescriptors = testDescriptors.Concat(new[]
            {
                // No expected type specified, the one in the payload should be enough
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")),
                    PayloadEdmModel = model,
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.ItemComplexType")),
                    PayloadEdmModel = model,
                },

                // Verify that the item type is inherited from the collection to its items if the item doesn't specify the type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.ItemComplexType"))
                                     .Item(PayloadBuilder
                                           .ComplexValue()
                                           .PrimitiveProperty("stringProperty", "test")
                                           .WithTypeAnnotation(itemComplexType)
                                           .AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    })),                                                                                             // Add item which does not have the type name
                    PayloadEdmModel = model
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.ItemComplexType"))
                                     .Item(PayloadBuilder
                                           .ComplexValue("TestModel.ItemComplexType")
                                           .PrimitiveProperty("stringProperty", "test")
                                           .WithTypeAnnotation(itemComplexType)) // Add an item which does have the type name
                                     .Item(PayloadBuilder
                                           .ComplexValue()
                                           .PrimitiveProperty("stringProperty", "test")
                                           .WithTypeAnnotation(itemComplexType)
                                           .AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    })),                                                                                             // Add item which does not have the type name
                    PayloadEdmModel = model
                }
            });

            // Wrap the value in a top-level property without expected type (can't use the .InProperty here, since that would put the expected type on it)
            testDescriptors = testDescriptors.Select(td =>
                                                     new PayloadReaderTestDescriptor(td)
            {
                PayloadElement = PayloadBuilder.Property("propertyName", td.PayloadElement)
            });

            // Fill in type names for expected result from the type annotations
            testDescriptors = testDescriptors.Select(td =>
            {
                td.ExpectedResultNormalizers.Add(tc => FillTypeNamesFromTypeAnnotationsPayloadElementVisitor.Visit);
                return(td);
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                // The version dependent behavior tests are implemented in the format specific tests.
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.PayloadNormalizers.Add((tc) => tc.Format == ODataFormat.Json ? ReplaceExpectedTypeWithContextUriVisitor.VisitPayload : (Func <ODataPayloadElement, ODataPayloadElement>)null);

                var property = testDescriptor.PayloadElement as PropertyInstance;
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public IEnumerable <PayloadReaderTestDescriptor> CreateInvalidCollectionsWithTypeNames(bool expectedTypeWillBeUsed)
        {
            EdmModel       model           = new EdmModel();
            EdmComplexType itemComplexType = model.ComplexType("ItemComplexType");

            model.ComplexType("ExtraComplexType");
            model = model.Fixup();

            // Add invalid cases
            var testDescriptors = new[]
            {
                // Invalid collection type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue("")
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", string.Empty),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName(""))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", EntityModelUtils.GetCollectionTypeName("")),
                },
                // Invalid collection type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue("collection(Edm.Int32)")
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "collection(Edm.Int32)"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue("foo")
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "foo"),
                },

                // Non existant type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.NonExistant"))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", EntityModelUtils.GetCollectionTypeName("TestModel.NonExistant")),
                },

                // Type of the item differs from the type of the collection
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String"))
                                     .Item(-42)
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true))),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_CannotConvertPrimitiveValue", "-42", "Edm.String")
                    },
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.ItemComplexType"))
                                     .Item(PayloadBuilder.ComplexValue("TestModel.ExtraComplexType"))
                                     .WithTypeAnnotation(EdmCoreModel.GetCollection(itemComplexType.ToTypeReference())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", "TestModel.ExtraComplexType", "TestModel.ItemComplexType"),
                }
            };

            if (expectedTypeWillBeUsed)
            {
                testDescriptors = testDescriptors.Concat(new[]
                {
                    // Type differs from the declared/expected type
                    new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String"))
                                         .WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))),
                        PayloadEdmModel   = model,
                        ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", EntityModelUtils.GetCollectionTypeName("Edm.String"), EntityModelUtils.GetCollectionTypeName("Edm.Int32")),
                    },
                }).ToArray();
            }

            foreach (var testDescriptor in testDescriptors)
            {
                testDescriptor.PayloadNormalizers.Add((tc) => tc.Format == ODataFormat.Json ? AddJsonLightTypeAnnotationToCollectionsVisitor.Normalize : (Func <ODataPayloadElement, ODataPayloadElement>)null);
            }

            return(testDescriptors);
        }
        private IEnumerable <PayloadReaderTestDescriptor> CreateCollectionPayloadsWithMetadata(bool withTypeNames)
        {
            // Start with the standard set of collections
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = PayloadReaderTestDescriptorGenerator.CreateCollectionTestDescriptors(this.Settings, withTypeNames);

            // Add collections with all of the primitive values (except null)
            testDescriptors = testDescriptors.Concat(PayloadReaderTestDescriptorGenerator.CreatePrimitiveValueTestDescriptors(this.Settings, false)
                                                     .Where(primitivePayload => ((PrimitiveValue)primitivePayload.PayloadElement).ClrValue != null)
                                                     .Select(primitivePayload =>
            {
                IEdmTypeReference edmType = primitivePayload.PayloadElement.GetAnnotation <EntityModelTypeAnnotation>().EdmModelType;
                var primitiveCollection   = PayloadBuilder.PrimitiveMultiValue(withTypeNames ? EntityModelUtils.GetCollectionTypeName(edmType.FullName()) : null)
                                            .Item(((PrimitiveValue)primitivePayload.PayloadElement).ClrValue)
                                            .WithTypeAnnotation(EdmCoreModel.GetCollection(edmType));
                if (!withTypeNames)
                {
                    primitiveCollection.AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    });
                }
                return(new PayloadReaderTestDescriptor(primitivePayload)
                {
                    PayloadElement = primitiveCollection,
                });
            }));

            // Add collections with all of the complex values (except null)
            testDescriptors = testDescriptors.Concat(PayloadReaderTestDescriptorGenerator.CreateComplexValueTestDescriptors(this.Settings, withTypeNames, false)
                                                     .Where(complexPayload => !((ComplexInstance)complexPayload.PayloadElement).IsNull)
                                                     .Select(complexPayload =>
            {
                IEdmTypeReference edmComplexType = complexPayload.PayloadElement.GetAnnotation <EntityModelTypeAnnotation>().EdmModelType;
                var complexCollection            = PayloadBuilder.ComplexMultiValue(withTypeNames ? EntityModelUtils.GetCollectionTypeName(edmComplexType.FullName()) : null)
                                                   .Item((ComplexInstance)complexPayload.PayloadElement)
                                                   .WithTypeAnnotation(EdmCoreModel.GetCollection(edmComplexType));
                if (!withTypeNames)
                {
                    complexCollection.AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    });
                }
                return(new PayloadReaderTestDescriptor(complexPayload)
                {
                    PayloadElement = complexCollection,
                });
            }));

            return(testDescriptors);
        }
示例#18
0
        public void CollectionReaderAtomErrorTest()
        {
            EdmModel edmModel = new EdmModel();

            EdmComplexType edmComplexTypeEmpty = new EdmComplexType(ModelNamespace, "EmptyComplexType");

            edmModel.AddElement(edmComplexTypeEmpty);

            EdmComplexType edmComplexTypeCity = new EdmComplexType(ModelNamespace, "CityType");

            edmComplexTypeCity.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(true));
            edmModel.AddElement(edmComplexTypeCity);

            EdmComplexType edmComplexTypeAddress = new EdmComplexType(ModelNamespace, "AddressType");

            edmComplexTypeAddress.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(true));
            edmModel.AddElement(edmComplexTypeAddress);

            edmModel.Fixup();

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Verify that collections do not support top level collection type.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new ComplexInstanceCollection().CollectionName(null)
                                     .XmlRepresentation(@"<m:value>
                                           <m:element m:type='" + EntityModelUtils.GetCollectionTypeName("Edm.Int32") + @"'>
                                                <m:element>42</m:element>
                                           </m:element>
                                           </m:value>"),
                    PayloadEdmModel       = edmModel,
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_InvalidItemTypeKind", "Collection"),
                    SkipTestConfiguration = tc => tc.Version < Microsoft.OData.Core.ODataVersion.V4,
                },

                // Verify that collection inside complex type is not supported.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new  ComplexInstanceCollection().CollectionName(null)
                                     .XmlRepresentation(@"<m:value>
                                               <m:element>
                                                <m:element m:type='" + EntityModelUtils.GetCollectionTypeName("Edm.Int32") + @"'>
                                                 <m:element>42</m:element>
                                                </m:element>
                                               </m:element>
                                             </m:value>"),
                    PayloadEdmModel       = null, // No model, since otherwise we would fail to read the top-level item as it has no type information
                    ExpectedException     = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_InvalidItemTypeKind", "Collection"),
                    SkipTestConfiguration = tc => tc.Version < Microsoft.OData.Core.ODataVersion.V4,
                },

                // Collection with m:type attribute in the root collection element.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new PrimitiveCollection().CollectionName(null)
                                     .XmlRepresentation("<m:value m:type='Edm.Int32'></m:value>"),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomCollectionDeserializer_TypeOrNullAttributeNotAllowed"),
                },

                // Collection with m:null attribute in the Collection element.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new PrimitiveCollection().CollectionName(null)
                                     .XmlRepresentation("<m:value m:null='true'></m:value>"),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomCollectionDeserializer_TypeOrNullAttributeNotAllowed"),
                },

                // Collection with both m:type and m:null attribute in the Collection element.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new PrimitiveCollection().CollectionName(null)
                                     .XmlRepresentation("<m:value m:null='true' m:type='Edm.Int32'></m:value>"),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomCollectionDeserializer_TypeOrNullAttributeNotAllowed"),
                },

                // root collection element not in the d namespace.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new PrimitiveCollection().CollectionName("PrimitiveCollection")
                                     .XmlRepresentation("<d:PrimitiveCollection></d:PrimitiveCollection>"),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomCollectionDeserializer_TopLevelCollectionElementWrongNamespace", "http://docs.oasis-open.org/odata/ns/data", "http://docs.oasis-open.org/odata/ns/metadata"),
                },

                // complex value instead of collection.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new PrimitiveCollection().CollectionName(null)
                                     .XmlRepresentation(@"<m:value>
                                              <m:city>Seattle</m:city>
                                             </m:value>"),
                    PayloadEdmModel   = edmModel,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomCollectionDeserializer_WrongCollectionItemElementName", "city", "http://docs.oasis-open.org/odata/ns/data", "http://docs.oasis-open.org/odata/ns/data"),
                },

                // complex collection with expected type and no metadata.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new ComplexInstanceCollection(
                        PayloadBuilder.ComplexValue("TestModel.CityType").Property("Name", PayloadBuilder.PrimitiveValue("Vienna")),
                        PayloadBuilder.ComplexValue("TestModel.CityType").Property("Name", PayloadBuilder.PrimitiveValue("Am Euro Platz"))
                        ).ExpectedCollectionItemType(edmComplexTypeCity).CollectionName(null),

                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.PayloadExpectedResultSettings)
                    {
                        // There was no simple way to specify the complex type as the expected type, so specifying a primitive type as the
                        // expected type. Since the expected type is only used to trigger the exception any expected type works.
                        ReaderMetadata    = new PayloadReaderTestDescriptor.ReaderMetadata(EdmCoreModel.Instance.GetInt32(false)),
                        ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedTypeSpecifiedWithoutMetadata", "expectedItemTypeReference"),
                    }
                },

                // primitive collection with expected type and no metadata.
                new PayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings)
                {
                    PayloadElement = new PrimitiveCollection(
                        PayloadBuilder.PrimitiveValue(1),
                        PayloadBuilder.PrimitiveValue(2)
                        ).ExpectedCollectionItemType(EdmDataTypes.Int32).CollectionName(null),
                    ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedTypeSpecifiedWithoutMetadata", "expectedItemTypeReference"),
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void CollectionWithoutExpectedTypeAndWithoutMetadataTest()
        {
            const string complexType1Name = "TestModel.TestComplexType1";
            const string complexType2Name = "TestModel.TestComplexType2";

            #region Test cases where the collection does not specify a type name
            IEnumerable <PayloadReaderTestDescriptor> noCollectionTypeNameTestDescriptors = new[]
            {
                // Primitive collection containing items of the same primitive type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue().Item(1).Item(2).Item(3)
                },
                // Primitive collection containing string items where some don't specify the type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue().Item("One").Item(new PrimitiveValue(/*fullTypeName*/ null, "Two")).Item("Three")
                },
                // Primitive collection containing string items where the first doesn't specify the type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue().Item(new PrimitiveValue(/*fullTypeName*/ null, "One")).Item("Two").Item("Three")
                },

                // Primitive collection containing items of different primitive types
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.PrimitiveMultiValue().Item(1).Item(true).Item(2),
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Boolean", "Edm.Int32")
                    }
                },
                // Complex collection containing items of different complex type (correct type attribute value)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .Item(PayloadBuilder.ComplexValue(complexType1Name).PrimitiveProperty("Property1", "Foo"))
                                     .Item(PayloadBuilder.ComplexValue(complexType2Name).PrimitiveProperty("Property1", "Foo")),
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", complexType2Name, complexType1Name),
                },
                // Primitive collection containing items of different primitive types (including one not specifying the type name)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.PrimitiveMultiValue().Item(new PrimitiveValue(/*fullTypeName*/ null, "One")).Item("Two").Item(3),
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String")
                    }
                },
                // Complex collection containing complex items without type names
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue()
                                     .Item(PayloadBuilder.ComplexValue().PrimitiveProperty("Property1", "Foo"))
                                     .Item(PayloadBuilder.ComplexValue().PrimitiveProperty("Property2", "Bar")),
                },
            };
            #endregion Test cases where the collection does not specify a type name

            #region Test cases where the collection does specify a type name
            IEnumerable <PayloadReaderTestDescriptor> collectionTypeNameTestDescriptors = new[]
            {
                // Primitive collection containing items of the same primitive type and the items have type names as well
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32")).Item(1).Item(2).Item(3)
                },
                // Primitive collection containing string items where some don't specify the type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")).Item("One").Item(new PrimitiveValue(/*fullTypeName*/ null, "Two")).Item("Three")
                },
                // Primitive collection containing string items where the first doesn't specify the type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")).Item(new PrimitiveValue(/*fullTypeName*/ null, "One")).Item("Two").Item("Three")
                },

                // Primitive collection containing some items of a different primitive type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")).Item(new PrimitiveValue(/*fullTypeName*/ null, "One")).Item("Two").Item(3),
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String")
                    }
                },
                // Primitive collection containing items of the same primitive type where some specify type names
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32")).Item(1).Item(new PrimitiveValue(/*fullTypeName*/ null, 2)).Item(3),
                },
                // Primitive collection containing items of different primitive types
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")).Item(1).Item(true).Item(2),
                    ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String")
                    }
                },
                // Complex collection containing items of different complex type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName(complexType1Name))
                                     .Item(PayloadBuilder.ComplexValue(complexType2Name).PrimitiveProperty("Property1", "Foo")),
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", complexType2Name, complexType1Name),
                },
                // Complex collection containing items of different complex type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName(complexType1Name))
                                     .Item(PayloadBuilder.ComplexValue(complexType1Name).PrimitiveProperty("Property1", "Foo"))
                                     .Item(PayloadBuilder.ComplexValue(complexType2Name).PrimitiveProperty("Property1", "Foo")),
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", complexType2Name, complexType1Name),
                },
            };
            #endregion

            noCollectionTypeNameTestDescriptors = noCollectionTypeNameTestDescriptors.Select(td => td.InProperty());
            collectionTypeNameTestDescriptors   = collectionTypeNameTestDescriptors.Select(td => td.InProperty());

            this.CombinatorialEngineProvider.RunCombinations(
                noCollectionTypeNameTestDescriptors.Concat(collectionTypeNameTestDescriptors),
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void ConvertToUriLiteralModelTest()
        {
            List <ConvertToUriLiteralTestCase> testCases = new List <ConvertToUriLiteralTestCase>();

            var edmModel = new EdmModel();

            edmModel.GetUInt32("TestModel", false);
            EdmComplexType addressType = new EdmComplexType("TestModel", "Address");

            addressType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(true));
            addressType.AddStructuralProperty("Zip", EdmCoreModel.Instance.GetInt32(false));
            edmModel.AddElement(addressType);

            var container = new EdmEntityContainer("TestModel", "DefaultContainer");

            edmModel.AddElement(container);

            #region negative test
            // types that does not exist in model
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter         = (UInt16)123,
                Model             = edmModel,
                ExpectedException = ODataExpectedExceptions.ODataException("ODataUriUtils_ConvertToUriLiteralUnsupportedType", "System.UInt16"),
            });
            #endregion

            #region positive test
            // types that exists in model
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter     = new ODataNullValue(),
                Model         = edmModel,
                ExpectedValue = "null",
            });
            // Do not verify primitive types against model
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter     = GeographyFactory.Point(32.5, -100.3).Build(),
                Model         = edmModel,
                ExpectedValue = "geography'SRID=4326;POINT (-100.3 32.5)'",
            });
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter = new ODataCollectionValue()
                {
                    TypeName = EntityModelUtils.GetCollectionTypeName("Edm.String"), Items = new string[] { "value" }
                },
                Model         = edmModel,
                ExpectedValue = "[\"value\"]",
            });
            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter     = (UInt32)123,
                Model         = edmModel,
                ExpectedValue = "123",
            });
            #endregion

            this.RunTestCases(testCases);
        }
示例#21
0
        public void ComplexValueWithMetadataTest()
        {
            // Use some standard complex value payloads first
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = PayloadReaderTestDescriptorGenerator.CreateComplexValueTestDescriptors(this.Settings, true);

            // Add metadata validation tests
            EdmModel model            = new EdmModel();
            var      innerComplexType = model.ComplexType("InnerComplexType");

            innerComplexType.AddStructuralProperty("name", EdmCoreModel.Instance.GetString(true));

            var complexType = model.ComplexType("ComplexType");

            complexType.AddStructuralProperty("number", EdmPrimitiveTypeKind.Int32);
            complexType.AddStructuralProperty("string", EdmCoreModel.Instance.GetString(true));
            complexType.AddStructuralProperty("complex", MetadataUtils.ToTypeReference(innerComplexType, true));

            var entityType = model.EntityType("EntityType");

            entityType.KeyProperty("Id", EdmCoreModel.Instance.GetInt32(false));
            model.Fixup();

            // Test that different types of properties not present in the metadata all fail
            IEnumerable <PropertyInstance> undeclaredPropertyTestCases = new PropertyInstance[]
            {
                PayloadBuilder.PrimitiveProperty("undeclared", 42),
                PayloadBuilder.Property("undeclared", PayloadBuilder.ComplexValue(innerComplexType.FullName())),
                PayloadBuilder.Property("undeclared", PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32"))),
                PayloadBuilder.Property("undeclared", PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.InnerComplexType"))),
            };

            testDescriptors = testDescriptors.Concat(
                undeclaredPropertyTestCases.Select(tc =>
            {
                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property(tc),
                    PayloadEdmModel = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "undeclared", "TestModel.ComplexType"),
                });
            }));

            testDescriptors = testDescriptors.Concat(new[]
            {
                // Property which should take typename not from value but from the parent metadata
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property("complex", PayloadBuilder.ComplexValue(innerComplexType.FullName()).PrimitiveProperty("name", null)
                                               .JsonRepresentation("{ \"name\" : null }").XmlRepresentation("<d:name m:null=\"true\" />")
                                               .AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    })),
                    PayloadEdmModel = model,
                },
                // Property which is declared in the metadata but with a different type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property("complex", PayloadBuilder.ComplexValue(complexType.FullName())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", "TestModel.ComplexType", "TestModel.InnerComplexType"),
                },
                // Property which is declared in the metadata but with a wrong kind
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property("complex", PayloadBuilder.ComplexValue(entityType.FullName())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "TestModel.EntityType", "Complex", "Entity"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.ComplexValue("").WithTypeAnnotation(complexType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", string.Empty)
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.ComplexValue("TestModel.NonExistant").WithTypeAnnotation(complexType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "TestModel.NonExistant"),
                },
            });

            // Wrap the complex type in a property
            testDescriptors = testDescriptors
                              .Select((td, index) => new PayloadReaderTestDescriptor(td)
            {
                PayloadDescriptor = td.PayloadDescriptor.InProperty("propertyName" + index)
            })
                              .SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            // Handcrafted cases
            testDescriptors = testDescriptors.Concat(new[]
            {
                // Top-level complex property without expected type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = PayloadBuilder.Property("property", PayloadBuilder.ComplexValue(complexType.FullName()).PrimitiveProperty("number", 42)),
                    PayloadEdmModel = model
                },
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                var property = testDescriptor.PayloadElement as PropertyInstance;
                if (property != null && testConfiguration.Format == ODataFormat.Atom)
                {
                    property.Name = null;
                }
                testDescriptor.RunTest(testConfiguration);
            });
        }