public void WriteComplexParameterWithoutTypeInformationErrorTest()
        {
            EdmModel edmModel = new EdmModel();
            var container = new EdmEntityContainer("DefaultNamespace", "DefaultContainer");
            edmModel.AddElement(container);

            var testDescriptors = new PayloadWriterTestDescriptor<ODataParameters>[]
            {
                new PayloadWriterTestDescriptor<ODataParameters>(
                    this.Settings,
                    new ODataParameters()
                    {
                        new KeyValuePair<string, object>("p1", new ODataComplexValue())
                    },
                    tc => new WriterTestExpectedResults(this.ExpectedResultSettings)
                        {
                            ExpectedException2 = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueSerializer_NoExpectedTypeOrTypeNameSpecifiedForComplexValueRequest")
                        })
                    {
                        DebugDescription = "Complex value without expected type or type name.",
                        Model = edmModel
                    },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => tc.IsRequest),
                (testDescriptor, testConfiguration) =>
                {
                    TestWriterUtils.WriteAndVerifyODataParameterPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
        /// <summary>
        /// Copy constructor.
        /// </summary>
        /// <param name="other">The <see cref="PayloadWriterTestDescriptor"/> to clone.</param>
        protected PayloadWriterTestDescriptor(PayloadWriterTestDescriptor other)
            : base(other)
        {
            ExceptionUtilities.CheckArgumentNotNull(other, "other");

            this.settings                   = other.settings;
            this.PayloadDescriptor          = new PayloadTestDescriptor(other.PayloadDescriptor);
            this.Model                      = other.Model;
            this.PayloadEdmElementContainer = other.PayloadEdmElementContainer;
        }
        /// <summary>
        /// Copy constructor.
        /// </summary>
        /// <param name="other">The <see cref="PayloadWriterTestDescriptor"/> to clone.</param>
        protected PayloadWriterTestDescriptor(PayloadWriterTestDescriptor other)
            : base(other)
        {
            ExceptionUtilities.CheckArgumentNotNull(other, "other");

            this.settings = other.settings;
            this.PayloadDescriptor = new PayloadTestDescriptor(other.PayloadDescriptor);
            this.Model = other.Model;
            this.PayloadEdmElementContainer = other.PayloadEdmElementContainer;
        }
Esempio n. 4
0
        public void RawPrimitiveValueTests()
        {
            var testCases = new PayloadWriterTestDescriptor<object> []
            {
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(double)1, "1", null, TextPlainContentType), // double
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)new byte[] { 0, 1, 0, 1}, (string)null, new byte[] { 0, 1, 0, 1}, ApplicationOctetStreamContentType), // binary
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(Single)1,  "1", (byte[])null, TextPlainContentType), // single
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)true, "true", (byte[])null, TextPlainContentType), // boolean
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(byte)1, "1", (byte[])null, TextPlainContentType), // byte
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)DateTimeOffset.Parse("2010-10-10T10:10:10Z"), "2010-10-10T10:10:10Z", (byte[])null, TextPlainContentType), // DateTimeOffset
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)DateTimeOffset.Parse("2010-10-10T10:10:10+01:00"), "2010-10-10T10:10:10+01:00", (byte[])null, TextPlainContentType), // DateTimeOffset (2)
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)DateTimeOffset.Parse("2010-10-10T10:10:10-08:00"), "2010-10-10T10:10:10-08:00", (byte[])null, TextPlainContentType), // DateTimeOffset (3)
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(decimal)1, "1", (byte[])null, TextPlainContentType), // Decimal
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)new Guid("11111111-2222-3333-4444-555555555555"), "11111111-2222-3333-4444-555555555555", (byte[])null, TextPlainContentType), // Guid
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(sbyte)1, "1", (byte[])null, TextPlainContentType), // SByte
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(Int16)1, "1", (byte[])null, TextPlainContentType), // Int16
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(Int32)1, "1", (byte[])null, TextPlainContentType), // Int32
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)(Int64)1, "1", (byte[])null, TextPlainContentType), // Int64
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)"1", "1", (byte[])null, TextPlainContentType), // string
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)TimeSpan.FromMinutes(12.34), "PT12M20.4S", (byte[])null, TextPlainContentType), // Duration
                new PayloadWriterTestDescriptor<object>(this.Settings, (object)string.Empty, string.Empty, (byte[])null, TextPlainContentType), // empty 
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.DefaultFormatConfigurationsWithIndent,
                (testCase, testConfiguration) =>
                {
                    // fix up the accept header for binary content
                    bool binaryPayload = testCase.PayloadItems.Single() is byte[];
                    if (binaryPayload)
                    {
                        ODataMessageWriterSettings settings = testConfiguration.MessageWriterSettings.Clone();
                        settings.SetContentType("application/octet-stream", null);
                        testConfiguration = new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);
                    }

                    TestWriterUtils.WriteAndVerifyRawContent(testCase, testConfiguration, this.Assert, this.Logger);
                });
        }
        public void WritePropertyWithoutOwningType()
        {
            var model = new EdmModel();
            var container = new EdmEntityContainer("DefaultNamespace", "DefaultContainer");
            model.AddElement(container);

            var testDescriptor = new PayloadWriterTestDescriptor<ODataProperty>(
                this.Settings,
                new ODataProperty() { Name = "PropertyName", Value = null },
                tc => new JsonWriterTestExpectedResults(this.ExpectedResultSettings)
                {
                })
                {
                    Model = model
                };

            this.CombinatorialEngineProvider.RunCombinations(
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurations,
                (testConfiguration) =>
                {
                    testDescriptor.RunTopLevelPropertyPayload(testConfiguration, baselineLogger: this.Logger);
                });
        }
Esempio n. 6
0
        public void InvalidXmlCharactersTests()
        {
            ODataProperty property = ObjectModelUtils.CreateDefaultPrimitiveProperties().First(p => p.Name == "String");
            this.Assert.AreEqual("String", property.Name, "Expected string property to be the primitive property at position 16.");

            string invalidXmlString = "Invalid character: '" + (char)1 + "'";

            string atomResult = @"<{5} xmlns=""{1}"" xmlns:{0}=""{1}"">Invalid character: '&#x1;'</{5}>";
            atomResult = string.Format(atomResult,
                TestAtomConstants.ODataMetadataNamespacePrefix,
                TestAtomConstants.ODataMetadataNamespace,
                TestAtomConstants.ODataNamespacePrefix,
                TestAtomConstants.ODataNamespace,
                TestAtomConstants.AtomTypeAttributeName,
                TestAtomConstants.ODataValueElementName);

            property.Value = invalidXmlString;
            PayloadWriterTestDescriptor.WriterTestExpectedResultCallback expectedResultCallback =
                (testConfig) =>
                {
                    if (testConfig.MessageWriterSettings.CheckCharacters)
                    {
                        return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            // TODO: Support raw error message verification for non-product exceptions
                            ExpectedException2 = new ExpectedException(typeof(ArgumentException)),
                        };
                    }
                    else
                    {
                        return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            FragmentExtractor = null,
                            Xml = atomResult
                        };
                    }
                };

            PayloadWriterTestDescriptor<ODataProperty>[] testDescriptors = new PayloadWriterTestDescriptor<ODataProperty>[]
                {
                    new PayloadWriterTestDescriptor<ODataProperty>(this.Settings, property, expectedResultCallback),
                };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                    testDescriptor.RunTopLevelPropertyPayload(testConfiguration, baselineLogger: this.Logger);

                    WriterTestConfiguration otherTestConfiguration = testConfiguration.Clone();
                    otherTestConfiguration.MessageWriterSettings.CheckCharacters = !testConfiguration.MessageWriterSettings.CheckCharacters;
                    testDescriptor.RunTopLevelPropertyPayload(otherTestConfiguration, baselineLogger: this.Logger);
                });
        }
        public void ActionAndFunctionTest()
        {
            // <m:action Metadata=URI title?="title" target=URI />

            Uri actionMetadata = new Uri("http://odata.org/test/$metadata#defaultAction");
            Uri actionMetadata2 = new Uri("#action escaped relative metadata", UriKind.Relative);
            Uri actionMetadata3 = new Uri("../#action escaped relative metadata", UriKind.Relative);
            string actionTitle = "Default Action";
            Uri actionTarget = new Uri("http://odata.org/defaultActionTarget");
            Uri actionTarget2 = new Uri("http://odata.org/defaultActionTarget2");

            ODataAction action_r1_t1 = new ODataAction() { Metadata = actionMetadata, Title = actionTitle, Target = actionTarget };
            ODataAction action_r1_t2 = new ODataAction() { Metadata = actionMetadata, Title = actionTitle, Target = actionTarget2 };
            ODataAction action_r2_t1 = new ODataAction() { Metadata = actionMetadata2, Title = actionTitle, Target = actionTarget };
            ODataAction action_r3_t1 = new ODataAction() { Metadata = actionMetadata3, Title = actionTitle, Target = actionTarget };

            Uri functionMetadata = new Uri("http://odata.org/test/$metadata#defaultFunction");
            Uri functionMetadata2 = new Uri("#function escaped relative metadata", UriKind.Relative);
            Uri functionMetadata3 = new Uri("\\#function escaped relative metadata", UriKind.Relative);
            string functionTitle = "Default Function";
            Uri functionTarget = new Uri("http://odata.org/defaultFunctionTarget");
            Uri functionTarget2 = new Uri("http://odata.org/defaultFunctionTarget2");

            ODataFunction function_r1_t1 = new ODataFunction() { Metadata = functionMetadata, Title = functionTitle, Target = functionTarget };
            ODataFunction function_r1_t2 = new ODataFunction() { Metadata = functionMetadata, Title = functionTitle, Target = functionTarget2 };
            ODataFunction function_r2_t1 = new ODataFunction() { Metadata = functionMetadata2, Title = functionTitle, Target = functionTarget };
            ODataFunction function_r3_t1 = new ODataFunction() { Metadata = functionMetadata3, Title = functionTitle, Target = functionTarget };

            var actionCases = new[]
            {
                new {
                    ODataActions = new ODataAction[] { action_r1_t1 },
                    Atom = GetAtom(action_r1_t1),
                    JsonLight = GetJsonLightForRelGroup(action_r1_t1),
                },
                new {
                    ODataActions = new ODataAction[] { action_r1_t1, action_r1_t2 },
                    Atom = GetAtom(action_r1_t1) + GetAtom(action_r1_t2),
                    JsonLight = GetJsonLightForRelGroup(action_r1_t1, action_r1_t2),
                },
                new {
                    ODataActions = new ODataAction[] { action_r1_t1, action_r2_t1 },
                    Atom = GetAtom(action_r1_t1) + GetAtom(action_r2_t1),
                    JsonLight = GetJsonLightForRelGroup(action_r1_t1) + "," + GetJsonLightForRelGroup(action_r2_t1),
                },
                new {
                    ODataActions = new ODataAction[] { action_r1_t1, action_r2_t1, action_r1_t2 },
                    Atom = GetAtom(action_r1_t1) + GetAtom(action_r2_t1) + GetAtom(action_r1_t2),
                    JsonLight = GetJsonLightForRelGroup(action_r1_t1, action_r1_t2) + "," + GetJsonLightForRelGroup(action_r2_t1),
                },
                new {
                    ODataActions = new ODataAction[] { action_r3_t1 },
                    Atom = GetAtom(action_r3_t1),
                    JsonLight = GetJsonLightForRelGroup(action_r3_t1),
                },
            };

            var functionCases = new[]
            {
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1 },
                    Atom = GetAtom(function_r1_t1),
                    JsonLight = GetJsonLightForRelGroup(function_r1_t1),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1, function_r1_t2 },
                    Atom = GetAtom(function_r1_t1) + GetAtom(function_r1_t2),
                    JsonLight = GetJsonLightForRelGroup(function_r1_t1, function_r1_t2),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1, function_r2_t1 },
                    Atom = GetAtom(function_r1_t1) + GetAtom(function_r2_t1),
                    JsonLight = GetJsonLightForRelGroup(function_r1_t1) + "," + GetJsonLightForRelGroup(function_r2_t1),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1, function_r2_t1, function_r1_t2 },
                    Atom = GetAtom(function_r1_t1) + GetAtom(function_r2_t1) + GetAtom(function_r1_t2),
                    JsonLight = GetJsonLightForRelGroup(function_r1_t1, function_r1_t2) + "," + GetJsonLightForRelGroup(function_r2_t1),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r3_t1 },
                    Atom = GetAtom(function_r3_t1),
                    JsonLight = GetJsonLightForRelGroup(function_r3_t1),
                },
            };

            var queryResults =
                from actionCase in actionCases
                from functionCase in functionCases
                select new
                {
                    actionCase.ODataActions,
                    functionCase.ODataFunctions,
                    Atom = string.Concat(actionCase.Atom, functionCase.Atom),
                    JsonLight = string.Join(",", new[] { actionCase.JsonLight, functionCase.JsonLight }.Where(x => x != null))
                };

            EdmModel model = new EdmModel();
            EdmEntityType edmEntityTypeCustomer = model.EntityType("Customer", "TestModel");
            EdmEntityContainer edmEntityContainer = model.EntityContainer("DefaultContainer","TestModel" );
            EdmEntitySet edmEntitySetCustermors = model.EntitySet("Customers", edmEntityTypeCustomer);

            var testDescriptors = queryResults.Select(testCase =>
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntry("TestModel.Customer");

                if (testCase.ODataActions != null)
                {
                    foreach (var action in testCase.ODataActions)
                    {
                        entry.AddAction(action);
                    }
                }

                if (testCase.ODataFunctions != null)
                {
                    foreach (var function in testCase.ODataFunctions)
                    {
                        entry.AddFunction(function);
                    }
                }

                return new PayloadWriterTestDescriptor<ODataItem>(
                    this.Settings,
                    entry,
                    (testConfiguration) =>
                    {
                        if (testConfiguration.Format == ODataFormat.Atom)
                        {
                            return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                Xml = "<ODataOperations>" + testCase.Atom + "</ODataOperations>",
                                ExpectedException2 =
                                    entry.Actions != null && entry.Actions.Contains(null)
                                        ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Actions")
                                        : testConfiguration.IsRequest && entry.Actions != null && entry.Actions.Any()
                                            ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry))
                                            : entry.Functions != null && entry.Functions.Contains(null)
                                                ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Functions")
                                                : testConfiguration.IsRequest && entry.Functions != null && entry.Functions.Any()
                                                    ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry))
                                                    : null,
                                FragmentExtractor = (result) =>
                                {
                                    var actions = result.Elements(TestAtomConstants.ODataMetadataXNamespace + "action");
                                    var functions = result.Elements(TestAtomConstants.ODataMetadataXNamespace + "function");
                                    result = new XElement("ODataOperations", actions, functions);
                                    if (result.FirstNode == null)
                                    {
                                        result.Add(string.Empty);
                                    }

                                    return result;
                                }
                            };
                        }
                        else if (testConfiguration.Format == ODataFormat.Json)
                        {
                            return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                Json = string.Join(
                                    "$(NL)",
                                    "{",
                                    testCase.JsonLight,
                                    "}"),
                                ExpectedException2 =
                                    entry.Actions != null && entry.Actions.Contains(null)
                                        ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Actions")
                                        : testConfiguration.IsRequest && entry.Actions != null && entry.Actions.Any()
                                            ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry))
                                            : entry.Actions != null && entry.Actions.Any(a => !a.Metadata.IsAbsoluteUri && !a.Metadata.OriginalString.StartsWith("#"))
                                                ? ODataExpectedExceptions.ODataException("ValidationUtils_InvalidMetadataReferenceProperty", entry.Actions.First(a => a.Metadata.OriginalString.Contains(" ")).Metadata.OriginalString)
                                            : entry.Functions != null && entry.Functions.Contains(null)
                                                ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Functions")
                                                : testConfiguration.IsRequest && entry.Functions != null && entry.Functions.Any()
                                                    ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry))
                                                        : entry.Functions != null && entry.Functions.Any(f => !f.Metadata.IsAbsoluteUri && !f.Metadata.OriginalString.StartsWith("#"))
                                                            ? ODataExpectedExceptions.ODataException("ValidationUtils_InvalidMetadataReferenceProperty", entry.Functions.First(f => f.Metadata.OriginalString.Contains(" ")).Metadata.OriginalString)
                                                    : null,
                                FragmentExtractor = (result) =>
                                {
                                    var actionsAndFunctions = result.Object().Properties.Where(p => p.Name.Contains("#")).ToList();

                                    var jsonResult = new JsonObject();
                                    actionsAndFunctions.ForEach(p =>
                                    {
                                        // NOTE we remove all annotations here and in particular the text annotations to be able to easily compare
                                        //      against the expected results. This however means that we do not distinguish between the indented and non-indented case here.
                                        p.RemoveAllAnnotations(true);
                                        jsonResult.Add(p);
                                    });
                                    return jsonResult;
                                }
                            };
                        }
                        else
                        {
                            string formatName = testConfiguration.Format == null ? "null" : testConfiguration.Format.GetType().Name;
                            throw new NotSupportedException("Invalid format detected: " + formatName);
                        }
                    });
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    if (testConfiguration.Format == ODataFormat.Json)
                    {
                        if (testDescriptor.IsGeneratedPayload)
                        {
                            return;
                        }

                        // We need a model, entity set and entity type for JSON Light
                        testDescriptor = new PayloadWriterTestDescriptor<ODataItem>(testDescriptor)
                        {
                            Model = model,
                            PayloadEdmElementContainer = edmEntitySetCustermors,
                            PayloadEdmElementType = edmEntityTypeCustomer,
                        };
                    }

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
Esempio n. 8
0
        public void EntryNullPropertyErrorTests()
        {
            EdmModel model = new EdmModel();

            var complex = new EdmComplexType("My", "Complex");
            complex.AddStructuralProperty("Number", EdmPrimitiveTypeKind.Int32, isNullable: true);
            complex.AddStructuralProperty("String", EdmPrimitiveTypeKind.String, isNullable: true);
            complex.AddStructuralProperty("InnerComplex", new EdmComplexTypeReference(complex, isNullable: false));
            model.AddElement(complex);

            var entryWithNullProperties = new EdmEntityType("My", "EntryWithNullProperties");
            entryWithNullProperties.AddKeys(entryWithNullProperties.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32, isNullable: false));
            entryWithNullProperties.AddStructuralProperty("Double", EdmPrimitiveTypeKind.Double, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Binary", EdmPrimitiveTypeKind.Binary, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Single", EdmPrimitiveTypeKind.Single, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Boolean", EdmPrimitiveTypeKind.Boolean, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Byte", EdmPrimitiveTypeKind.Byte, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Decimal", EdmPrimitiveTypeKind.Decimal, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Guid", EdmPrimitiveTypeKind.Guid, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("SByte", EdmPrimitiveTypeKind.SByte, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Int16", EdmPrimitiveTypeKind.Int16, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Int32", EdmPrimitiveTypeKind.Int32, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Int64", EdmPrimitiveTypeKind.Int64, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Collection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(isNullable: false)));
            entryWithNullProperties.AddStructuralProperty("NamedStream", EdmPrimitiveTypeKind.Stream, isNullable: false);
            entryWithNullProperties.AddStructuralProperty("Complex", new EdmComplexTypeReference(complex, isNullable: false));
            model.AddElement(entryWithNullProperties);
            
            model.AddElement(new EdmEntityType("OtherTestNamespace", "EntryWithNullProperties"));

            var container = new EdmEntityContainer("My", "TestContainer");
            model.AddElement(container);

            string[] propertyNames = new string[]
            {
                "Double",
                "Single",
                "Boolean",
                "Byte",
                "Decimal",
                "Guid",
                "SByte",
                "Int16",
                "Int32",
                "Int64",
                "Collection",
                "NamedStream",
                "Complex",
            };

            var versions = new Version[] {
                    null,
                    new Version(4, 0),
                };

            this.CombinatorialEngineProvider.RunCombinations(
                propertyNames,
                versions,
                versions,
                TestWriterUtils.ODataBehaviorKinds,
                this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent,
                (propertyName, dataServiceVersion, edmVersion, behaviorKind, testConfig) =>
                {
                    ODataEntry primitivePropertiesEntry = ObjectModelUtils.CreateDefaultEntry();
                    primitivePropertiesEntry.TypeName = "My.EntryWithNullProperties";
                    primitivePropertiesEntry.Properties = new ODataProperty[] { new ODataProperty { Name = propertyName, Value = null } };

                    string errorResourceKey;
                    var messageParameters = new List<string> { propertyName };

                    if (propertyName == "Collection")
                    {
                        errorResourceKey = "WriterValidationUtils_CollectionPropertiesMustNotHaveNullValue";
                    }
                    else if (propertyName == "NamedStream")
                    {
                        errorResourceKey = "WriterValidationUtils_StreamPropertiesMustNotHaveNullValue";
                    }
                    else if (propertyName == "Complex")
                    {
                        errorResourceKey = "WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue";
                        messageParameters.Add("My." + propertyName);
                    }
                    else
                    {
                        errorResourceKey = "WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue";
                        messageParameters.Add("Edm." + propertyName);
                    }

                    PayloadWriterTestDescriptor<ODataItem> descriptor = new PayloadWriterTestDescriptor<ODataItem>(this.Settings, primitivePropertiesEntry)
                    {
                        ExpectedResultCallback = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)(
                           (testConfiguration) =>
                           {
                               // When AllowNullValuesForNonNullablePrimitiveTypes flag is set (happens only for the WCF DS server), primitive null value validation is disabled. 
                               if (behaviorKind == TestODataBehaviorKind.WcfDataServicesServer
                                   && new[] { "Collection", "Complex", "NamedStream" }.Where(v => v != propertyName).Count() > 0)
                               {
                                   return null;
                               }

                               return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                               {
                                   ExpectedException2 = ODataExpectedExceptions.ODataException(errorResourceKey, messageParameters.ToArray()),
                               };
                           }),
                        Model = model,
                    };

                    TestWriterUtils.WriteAndVerifyODataPayload(descriptor, testConfig.CloneAndApplyBehavior(behaviorKind), this.Assert, this.Logger);
                });
        }
        public void InvalidPropertyValueTypeTest()
        {
            Func<EdmModel, EdmEntityType> entityTypeWithComplexProperty =
                (model) =>
                {
                    EdmComplexType addressComplexType = new EdmComplexType("TestNS", "AddressComplexType");
                    addressComplexType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(true));
                    model.AddElement(addressComplexType);

                    EdmEntityType entityType = new EdmEntityType("TestNS", "EntityType");
                    entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                    entityType.AddStructuralProperty("Address", new EdmComplexTypeReference(addressComplexType, false));

                    model.AddElement(entityType);

                    return entityType;
                };

            Func<EdmModel, EdmEntityType> entityTypeWithCollectionProperty =
                (model) =>
                {
                    EdmEntityType entityType = new EdmEntityType("TestNS", "EntityType");
                    entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                    entityType.AddStructuralProperty("Address", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true)));

                    model.AddElement(entityType);

                    return entityType;
                };

            Func<EdmModel, EdmEntityType> openEntityType =
                (model) =>
                {
                    EdmEntityType entityType = new EdmEntityType("TestNS", "EntityType", null, false, true);
                    entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));

                    model.AddElement(entityType);

                    return entityType;
                };

            var testCases = new[] {
                new { // empty type name
                    PropertyCreate = (Func<ODataProperty>)(() => new ODataProperty() { Name = "Address", Value = new ODataComplexValue() { TypeName = string.Empty } }),
                    MetadataCreate = entityTypeWithComplexProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_TypeNameMustNotBeEmpty"),
                    ResponseOnly = false,
                },
                new { // Invalid collection type name
                    PropertyCreate = (Func<ODataProperty>)(() => new ODataProperty() { Name = "Address", Value = new ODataCollectionValue() { TypeName = "TestNS.AddressComplexType" } }),
                    MetadataCreate = entityTypeWithComplexProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "TestNS.AddressComplexType", "Collection", "Complex"),
                    ResponseOnly = false,
                },
                new { // Invalid complex type name
                    PropertyCreate = (Func<ODataProperty>)(() => new ODataProperty() { Name = "Address", Value = new ODataComplexValue() { TypeName = EntityModelUtils.GetCollectionTypeName("String") } }),
                    MetadataCreate = entityTypeWithCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", EntityModelUtils.GetCollectionTypeName("Edm.String"), "Complex", "Collection"),
                    ResponseOnly = false,
                },
                new { // open property with complex value but without type; error.
                    PropertyCreate = (Func<ODataProperty>)(() => new ODataProperty() { Name = "Address", Value = new ODataComplexValue() { Properties = null } }),
                    MetadataCreate = openEntityType,
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_MissingTypeNameWithMetadata"),
                    ResponseOnly = false,
                },
                new { // open property with collection but without a type; error.
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Address", 
                            Value = new ODataCollectionValue() 
                            {
                                Items = null
                            } 
                        }),
                    MetadataCreate = openEntityType,
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_MissingTypeNameWithMetadata"),
                    ResponseOnly = false,
                },
                new { // open property with stream value
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Address", 
                            Value = new ODataStreamReferenceValue()
                            {
                                ReadLink = new Uri("http://odata.org/readlink"),
                                EditLink = new Uri("http://odata.org/editlink"),
                                ContentType = "plain/text"
                            }
                        }),
                    MetadataCreate = openEntityType,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_OpenStreamProperty", "Address"),
                    ResponseOnly = true,
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testCase, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    if (testConfiguration.IsRequest && testCase.ResponseOnly)
                    {
                        return;
                    }

                    ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                    entry.TypeName = "TestNS.EntityType";
                    ODataProperty idProperty = new ODataProperty() { Name = "Id", Value = "1" };
                    entry.Properties = new ODataProperty[] { idProperty, testCase.PropertyCreate() };
                    var descriptor = new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        entry,
                        (tc) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) 
                        { 
                            ExpectedException2 = testCase.ExpectedException });
                    var model = new EdmModel();
                    testCase.MetadataCreate(model);
                    var container = new EdmEntityContainer("TestNS", "TestContainer");
                    model.AddElement(container);

                    descriptor.Model = model;
                    TestWriterUtils.WriteAndVerifyODataPayload(descriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
 public CollectionWriterTestDescriptor(Settings settings, string collectionName, object[] payloadItems, PayloadWriterTestDescriptor.WriterTestExpectedResultCallback expectedResultCallback, IEdmModel model)
 {
     this.TestDescriptorSettings = settings;
     this.collectionName = collectionName;
     this.payloadItems = payloadItems;
     bool errorOnly;
     this.invocations = CreateInvocations(payloadItems, out errorOnly);
     this.expectedResultCallback = expectedResultCallback;
     this.Model = model;
 }
Esempio n. 11
0
        public void EntryUserExceptionTests()
        {
            ODataFeed defaultFeed = ObjectModelUtils.CreateDefaultFeed();
            ODataEntry defaultEntry = ObjectModelUtils.CreateDefaultEntry();
            ODataNavigationLink defaultCollectionLink = ObjectModelUtils.CreateDefaultCollectionLink();
            ODataNavigationLink defaultSingletonLink = ObjectModelUtils.CreateDefaultSingletonLink();

            ODataItem[][] writerPayloads = new ODataItem[][]
            {
                new ODataItem[]
                {
                    defaultEntry,
                        defaultCollectionLink,
                            defaultFeed,
                                defaultEntry,
                                null,
                                defaultEntry,
                                null,
                                defaultEntry,
                                    defaultSingletonLink,
                                        defaultEntry,
                                            defaultCollectionLink,
                                                defaultFeed,
                                                    defaultEntry,
                                                    null,
                                                null,
                                            null,
                                        null,
                                    null,
                                null,
                            null,
                        null,
                },
                new ODataItem[]
                {
                    defaultEntry,
                        defaultSingletonLink,
                            defaultEntry,
                            null,
                        null,
                },
            };

            IEnumerable<PayloadWriterTestDescriptor<ODataItem>> testDescriptors = writerPayloads.Select(payload =>
                new PayloadWriterTestDescriptor<ODataItem>(
                    this.Settings,
                    payload,
                    tc => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = ODataExpectedExceptions.TestException(),
                    }
                ));

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => !tc.IsRequest && tc.Format == ODataFormat.Atom),
                (testDescriptor, testConfiguration) =>
                {
                    foreach (int throwUserExceptionAt in Enumerable.Range(0, testDescriptor.PayloadItems.Count + 1))
                    {
                        var configuredTestDescriptor = new PayloadWriterTestDescriptor<ODataItem>(this.Settings, testDescriptor.PayloadItems, testDescriptor.ExpectedResultCallback)
                        {
                            ThrowUserExceptionAt = throwUserExceptionAt,
                        };

                        TestWriterUtils.WriteAndVerifyODataPayload(configuredTestDescriptor, testConfiguration, this.Assert, this.Logger);
                    }
                });
        }
Esempio n. 12
0
        public void PrimitiveTypesMustMatchExactlyOnWriteTest()
        {
            EdmModel model = new EdmModel();

            var entityType = new EdmEntityType("TestNS", "WithIntType");
            entityType.AddStructuralProperty("Int64Property", EdmPrimitiveTypeKind.Int64, isNullable: false);
            model.AddElement(entityType);

            var entityType2 = new EdmEntityType("TestNS", "WithStringType");
            entityType2.AddStructuralProperty("StringProperty", EdmPrimitiveTypeKind.String, isNullable: false);
            model.AddElement(entityType2);

            EdmModel model2 = new EdmModel();

            var entityType3 = new EdmEntityType("TestNS", "WithSpatialType");
            entityType3.AddStructuralProperty("GeographyProperty", EdmPrimitiveTypeKind.GeographyPoint, isNullable: true);
            model2.AddElement(entityType3);

            var int64EntityWithInt32 = new EntityInstance("TestNS.WithIntType", false);
            int64EntityWithInt32.Property(new PrimitiveProperty("Int64Property", "Edm.Int32", 5));

            var stringEntityWithInt = new EntityInstance("TestNS.WithStringType", false);
            stringEntityWithInt.Property(new PrimitiveProperty("StringProperty", "Edm.Int32", 5));

            var geographyEntityWithString = new EntityInstance("TestNS.WithSpatialType", false);
            geographyEntityWithString.Property(new PrimitiveProperty("GeographyProperty", "Edm.String", "Hello"));

            var intEntityWithGeography = new EntityInstance("TestNS.WithIntType", false);
            intEntityWithGeography.Property(new PrimitiveProperty("Int64Property", "Edm.GeographyPoint", GeographyFactory.Point(32.0, -100.0).Build()).WithTypeAnnotation(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, false)));

            PayloadWriterTestDescriptor[] descriptors = new PayloadWriterTestDescriptor<ODataPayloadElement>[]
            {
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    Model = model,
                    PayloadElement = int64EntityWithInt32,
                    ExpectedResultCallback = (tc) => new PayloadWriterTestExpectedResults(this.ExpectedResultSettings) 
                    { 
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatiblePrimitiveItemType", "Edm.Int32","False", "Edm.Int64", "False") 
                    }
                },
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    Model = model,
                    PayloadElement = stringEntityWithInt,
                    ExpectedResultCallback = (tc) => new PayloadWriterTestExpectedResults(this.ExpectedResultSettings) 
                    { 
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatiblePrimitiveItemType", "Edm.Int32","False", "Edm.String", "False") 
                    }
                },
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    Model = model2,
                    PayloadElement = geographyEntityWithString,
                    ExpectedResultCallback = (tc) => new PayloadWriterTestExpectedResults(this.ExpectedResultSettings) 
                    { 
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatiblePrimitiveItemType", "Edm.String","True", "Edm.GeographyPoint", "True") 
                    },
                    
                },
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    Model = model,
                    PayloadElement = intEntityWithGeography,
                    ExpectedResultCallback = (tc) => new PayloadWriterTestExpectedResults(this.ExpectedResultSettings) 
                    { 
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatiblePrimitiveItemType", "Edm.GeographyPoint","True", "Edm.Int64", "False") 
                    }
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(descriptors,
                WriterTestConfigurationProvider.AtomFormatConfigurations,
                (descriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    descriptor.RunTest(testConfiguration, this.Logger);
                });
        }
Esempio n. 13
0
        public void DuplicateNavigationLinkTest()
        {
            IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            Uri navLinkUri = new Uri("http://odata.org/navlink");
            ODataEntry officeEntryInstance = ObjectModelUtils.CreateDefaultEntry();
            officeEntryInstance.TypeName = "TestModel.OfficeType";

            // Note that these tests specify behavior for requests. For responses we compute the behavior from these.
            IEnumerable<DuplicateNavigationLinkTestCase> testCases = new[]
            {
                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Two expanded links, both collection",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                ObjectModelUtils.CreateDefaultFeed(),
                                    officeEntryInstance,
                                    null,
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                ObjectModelUtils.CreateDefaultFeed(),
                                null,
                            null
                        }
                    },
                },
                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Two expanded links, both singletons",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = false },
                                officeEntryInstance,
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = false },
                                ObjectModelUtils.ODataNullEntry,
                                null,
                            null
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_MultipleLinksForSingleton", "PoliceStation"),
                },

                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Expanded singleton, deferred without type",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = false },
                                officeEntryInstance,
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = null },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_MultipleLinksForSingleton", "PoliceStation"),
                    // ATOM requires IsCollection to be non-null, JSON in request request IsCollection to be non-null
                    SkipTestConfiguration = tc => (tc.Format == ODataFormat.Atom)
                },
                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Expanded singleton, deferred singleton",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = false },
                                officeEntryInstance,
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = false },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_MultipleLinksForSingleton", "PoliceStation"),
                },
                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Expanded singleton, deferred collection (no metadata), we will fail on this since we don't allow multiple links for singletons",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = false },
                                officeEntryInstance,
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "PoliceStation", Url = navLinkUri, IsCollection = false },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_MultipleLinksForSingleton", "PoliceStation"),
                },

                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Expanded collection, deferred without type - no failures",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                ObjectModelUtils.CreateDefaultFeed(),
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = null },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    // ATOM requires IsCollection to be non-null, JSON in request requires IsCollection to be non-null
                    SkipTestConfiguration = tc => (tc.Format == ODataFormat.Atom)
                },
                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Expanded collection, deferred singleton - no failures (binding scenario) (the metadata mismatch is specifically allowed)",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                ObjectModelUtils.CreateDefaultFeed(),
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = false },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    // Skip this test in responses since we omit the entity reference link to turn the payload into
                    // a response and then the IsCollection value is invalid (since the mismatch is only allowed in requests)
                    SkipTestConfiguration = tc => !tc.IsRequest
                },
                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Expanded collection, deferred collection - no failures (binding scenario)",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                ObjectModelUtils.CreateDefaultFeed(),
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                },

                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Two deferred singletons on a collection property - no failures (binding scenario) (the metadata mismatch is specifically allowed)",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = false },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = false },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    // Skip this test in responses since we omit the entity reference link to turn the payload into
                    // a response and then the IsCollection value is invalid (since the mismatch is only allowed in requests)
                    SkipTestConfiguration = tc => !tc.IsRequest
                },
                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Two deferred collections on a collection property - no failures (binding scenario)",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                },
               new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Deferred collection and deferred singleton - no failures (binding scenario) (the metadata mismatch is specifically allowed)",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = false },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    // Skip this test in responses since we omit the entity reference link to turn the payload into
                    // a response and then the IsCollection value is invalid (since the mismatch is only allowed in requests)
                    SkipTestConfiguration = tc => !tc.IsRequest
                },

                new DuplicateNavigationLinkTestCase
                {
                    DebugDescription = "Expanded collection, deferred collection and deferred singleton - no failures (binding scenario) (the metadata mismatch is specifically allowed)",
                    NavigationLinks = new []
                    {
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                ObjectModelUtils.CreateDefaultFeed(),
                                null,
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = true },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        },
                        new ODataItem[]
                        {
                            new ODataNavigationLink { Name = "CityHall", Url = navLinkUri, IsCollection = false },
                                new ODataEntityReferenceLink { Url = navLinkUri },
                            null
                        }
                    },
                    // Skip this test in responses since we omit the entity reference link to turn the payload into
                    // a response and then the IsCollection value is invalid (since the mismatch is only allowed in requests)
                    SkipTestConfiguration = tc => !tc.IsRequest
                },
            };

            testCases = testCases.SelectMany(testCase => testCase.NavigationLinks.Permutations().Select(navigationLinks =>
                new DuplicateNavigationLinkTestCase(testCase) { NavigationLinks = navigationLinks }));

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                new bool[] { true, false },
                this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent,
                (testCase, withMetadata, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    if (testCase.SkipTestConfiguration != null && testCase.SkipTestConfiguration(testConfiguration))
                    {
                        return;
                    }

                    if (testConfiguration.IsRequest)
                    {
                        return;
                    }

                    ODataEntry entryInstance = ObjectModelUtils.CreateDefaultEntry();
                    entryInstance.TypeName = "TestModel.CityType";

                    string duplicationPropertyName = null;
                    ODataItem firstItem = testCase.NavigationLinks[0][0];
                    ODataNavigationLink firstNavigationLink = firstItem as ODataNavigationLink;
                    if (firstNavigationLink != null)
                    {
                        duplicationPropertyName = firstNavigationLink.Name;
                    }

                    Func<IEnumerable<ODataItem>, IEnumerable<ODataItem>> filterNavigationLinks = input => input;

                    ExpectedException expectedException = testCase.ExpectedException;
                    if (!testConfiguration.IsRequest)
                    {
                        // In responses, remove all entity reference links that will turn the payloads into true deferred links
                        filterNavigationLinks = input => input.Where(i => !(i is ODataEntityReferenceLink));

                        // In responses all duplicates will fail with the same error message since we don't allow any duplicates there.
                        expectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", duplicationPropertyName);
                    }

                    PayloadWriterTestDescriptor<ODataItem> testDescriptor = new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        new[] { entryInstance }.Concat(testCase.NavigationLinks.SelectMany(navigationLinkItems => filterNavigationLinks(navigationLinkItems))).ConcatSingle(null).ToArray(),
                        tc => tc.Format == ODataFormat.Atom ?
                            (WriterTestExpectedResults)new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                // Skip verification of payload in success cases
                                Xml = null,
                                ExpectedException2 = expectedException
                            } :
                            (WriterTestExpectedResults)new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                // Skip verification of payload in success cases
                                Json = null,
                                ExpectedException2 = expectedException
                            })
                        {
                            Model = withMetadata ? model : null,
                        };

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
Esempio n. 14
0
        public void NullPropertyNameTest()
        {
            EdmModel model = new EdmModel();

            var complexType1 = new EdmComplexType("TestNS", "ComplexType1");
            complexType1.AddStructuralProperty("StringProperty", EdmPrimitiveTypeKind.String, isNullable: false);
            model.AddElement(complexType1);

            var entityType1 = new EdmEntityType("TestNS", "EntityType1");
            entityType1.AddStructuralProperty("ComplexProperty", new EdmComplexTypeReference(complexType1, isNullable: false));
            model.AddElement(entityType1);

            var entityType2 = new EdmEntityType("TestNS", "EntityType2");
            entityType2.AddStructuralProperty("ComplexCollection", EdmCoreModel.GetCollection(new EdmComplexTypeReference(complexType1, isNullable: false)));
            model.AddElement(entityType2);

            // For these payloads we expect that the product will infer and write the type on the complex and collection properties on the entries.
            // As such we expect a different payload to what we write.
            // Complex Property + expected
            ComplexInstance instance = PayloadBuilder.ComplexValue();
            instance.PrimitiveProperty("StringProperty", "Hello");
            ComplexProperty complexProperty = new ComplexProperty("ComplexProperty", instance);

            ComplexInstance instanceWithType = PayloadBuilder.ComplexValue("TestNS.ComplexType1");
            instanceWithType.PrimitiveProperty("StringProperty", "Hello");
            ComplexProperty complexPropertyWithType = new ComplexProperty("ComplexProperty", instanceWithType);

            // Entity Instance with complex property + expected
            EntityInstance entity1 = new EntityInstance("TestNS.EntityType1", false /*isNull*/);
            entity1.Property(complexProperty);
            entity1.Id = "urn:Id";
            entity1.WithTypeAnnotation(entityType1);
            EntityInstance expectedEntity1 = new EntityInstance("TestNS.EntityType1", false /*isNull*/);
            expectedEntity1.Property(complexPropertyWithType);
            expectedEntity1.Id = "urn:Id";
            expectedEntity1.WithTypeAnnotation(entityType1);

            // Complex Collection Property
            ComplexMultiValueProperty collection = new ComplexMultiValueProperty("ComplexCollection", new ComplexMultiValue(null, false, instance));
            ComplexMultiValueProperty collectionWithType = new ComplexMultiValueProperty("ComplexCollection", new ComplexMultiValue("Collection(TestNS.ComplexType1)", false, instanceWithType));

            // Entity Instance with collection property
            EntityInstance entity2 = new EntityInstance("TestNS.EntityType2", false);
            entity2.Property(collection);
            entity2.Id = "urn:Id";
            entity2.WithTypeAnnotation(entityType2);
            EntityInstance expectedEntity2 = new EntityInstance("TestNS.EntityType2", false);
            expectedEntity2.Property(collectionWithType);
            expectedEntity2.Id = "urn:Id";
            expectedEntity2.WithTypeAnnotation(entityType2);

            PayloadWriterTestDescriptor<ODataPayloadElement>[] testDescriptors = new PayloadWriterTestDescriptor<ODataPayloadElement>[] 
            {
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    PayloadElement = entity1,
                    Model = model,
                    ExpectedResultCallback = (tc) =>
                    {
                        return new PayloadWriterTestExpectedResults(this.ExpectedResultSettings)
                        {
                            ExpectedPayload = expectedEntity1
                        };
                    },
                },
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    PayloadElement = entity2,
                    Model = model,
                    ExpectedResultCallback = (tc) =>
                    {
                        return new PayloadWriterTestExpectedResults(this.ExpectedResultSettings)
                        {
                            ExpectedPayload = expectedEntity2
                        };
                    },
                    
                }
            };

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
               testDescriptors,
               this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => tc.Format == ODataFormat.Atom),
               (testDescriptor, testConfiguration) =>
               {
                   testConfiguration = testConfiguration.Clone();
                   testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                   testDescriptor.RunTest(testConfiguration, this.Logger);
               });
        }
Esempio n. 15
0
        public void NullPropertiesOnOpenTypes()
        {
            EdmModel model = new EdmModel();

            var entityTypeWithSpatial = new EdmEntityType("TestModel", "OpenTypeWithNullSpatial", null, isAbstract: false, isOpen: true);
            entityTypeWithSpatial.AddStructuralProperty("SpatialProperty", EdmPrimitiveTypeKind.GeometryPoint, isNullable: true);
            model.AddElement(entityTypeWithSpatial);

            var entityType = new EdmEntityType("TestModel", "OpenTypeWithNullUndeclaredProperty", null, isAbstract: false, isOpen: true);
            model.AddElement(entityType);

            var container = new EdmEntityContainer("TestModel", "DefaultContainer");
            container.AddEntitySet("OpenTypeWithNullSpatial", entityTypeWithSpatial);
            container.AddEntitySet("OpenTypeWithNullUndeclaredProperty", entityType);
            model.AddElement(container);

            // We use NullPropertyInstance to represent the expected value in the two tests below due
            // to limitations in the test deserialiser.

            // Spatial property set to null.
            EntityInstance entityWithNullSpatialProperty = new EntityInstance("TestModel.OpenTypeWithNullSpatial", false);
            entityWithNullSpatialProperty.PrimitiveProperty("SpatialProperty", null);
            entityWithNullSpatialProperty.WithTypeAnnotation(entityTypeWithSpatial);
            entityWithNullSpatialProperty.Id = "http://test/Id";

            EntityInstance spatialExpected = new EntityInstance("TestModel.OpenTypeWithNullSpatial", false);
            spatialExpected.Property(new NullPropertyInstance("SpatialProperty", null));
            spatialExpected.Id = "http://test/Id";
            spatialExpected.WithTypeAnnotation(entityTypeWithSpatial);

            // Undeclared property set to null.
            EntityInstance entityWithNullUndeclaredProperty = new EntityInstance("TestModel.OpenTypeWithNullUndeclaredProperty", false);
            entityWithNullUndeclaredProperty.PrimitiveProperty("UndeclaredProperty", null);
            entityWithNullUndeclaredProperty.Id = "http://test/Id";
            entityWithNullUndeclaredProperty.WithTypeAnnotation(entityType);

            EntityInstance undeclaredExpected = new EntityInstance("TestModel.OpenTypeWithNullUndeclaredProperty", false);
            undeclaredExpected.Property(new NullPropertyInstance("UndeclaredProperty", null));
            undeclaredExpected.Id = "http://test/Id";
            undeclaredExpected.WithTypeAnnotation(entityType);

            PayloadWriterTestDescriptor[] testDescriptors = new PayloadWriterTestDescriptor[]
            {
                // Spatial property with model on v3
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    PayloadElement = entityWithNullSpatialProperty,
                    Model = model,
                    
                    ExpectedResultCallback = (tc) =>
                    {
                        return new PayloadWriterTestExpectedResults(this.ExpectedResultSettings)
                        {
                            ExpectedPayload = spatialExpected
                        };
                    },
                },
                // Spatial property with model on version < v3
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, (ODataPayloadElement)null)
                {
                    PayloadElement = entityWithNullSpatialProperty,
                    Model = model,
                    SkipTestConfiguration = tc => tc.Version >= ODataVersion.V4,
                    ExpectedResultCallback = (tc) =>
                    {
                        return new PayloadWriterTestExpectedResults(this.ExpectedResultSettings)
                        {
                            ExpectedException2 = ODataExpectedExceptions.ODataException("ODataVersionChecker_GeographyAndGeometryNotSupported", tc.Version.ToText())
                        };
                    },
                },
                // Undeclared null property
                new PayloadWriterTestDescriptor<ODataPayloadElement>(this.Settings, entityWithNullUndeclaredProperty)
                {
                    PayloadElement = entityWithNullUndeclaredProperty,
                    Model = model,
                    ExpectedResultCallback = (tc) =>
                    {
                        return new PayloadWriterTestExpectedResults(this.ExpectedResultSettings)
                        {
                            ExpectedPayload = undeclaredExpected
                        };
                    },
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
               testDescriptors,
               this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => tc.Format == ODataFormat.Atom),
               (testDescriptor, testConfiguration) =>
               {
                   testConfiguration = testConfiguration.Clone();
                   testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                   testDescriptor.RunTest(testConfiguration, this.Logger);
               });
        }
Esempio n. 16
0
        public void InferredTypeNamesTests()
        {
            EdmModel model = new EdmModel();
            var addressTypeNS = new EdmComplexType("TestNS", "AddressComplexType");
            addressTypeNS.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            model.AddElement(addressTypeNS);

            var addressTypeOther = new EdmComplexType("OtherTestNamespace", "AddressComplexType");
            model.AddElement(addressTypeOther);

            var orderTypeNS = new EdmComplexType("TestNS", "OrderComplexType");
            model.AddElement(orderTypeNS);

            var orderTypeOther = new EdmComplexType("OtherTestNamespace", "OrderComplexType");
            model.AddElement(orderTypeOther);

            var entityTypeNS = new EdmEntityType("TestNS", "EntityType");
            entityTypeNS.AddKeys(entityTypeNS.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(isNullable: false)));
            entityTypeNS.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            entityTypeNS.AddStructuralProperty("Scores", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(isNullable: true)));
            entityTypeNS.AddStructuralProperty("Address", new EdmComplexTypeReference(addressTypeNS, isNullable: false));
            model.AddElement(entityTypeNS);

            var entityTypeOther = new EdmEntityType("OtherTestNamespace", "EntityType");
            entityTypeOther.AddKeys(entityTypeOther.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(isNullable: false)));
            entityTypeOther.AddStructuralProperty("Age", EdmCoreModel.Instance.GetInt32(isNullable: false));
            model.AddElement(entityTypeOther);

            var container = new EdmEntityContainer("TestNS", "TestContainer");
            model.AddElement(container);

            ODataEntry entry = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
            entry.TypeName = "TestNS.EntityType";
            entry.Properties = new ODataProperty[]
            {
                new ODataProperty() { Name = "Id", Value = 1 },
                new ODataProperty() { Name = "Name", Value = "Bill" },
                new ODataProperty() 
                { 
                    Name = "Address", 
                    Value = new ODataComplexValue()
                    {
                        Properties = new []
                        {
                            new ODataProperty() { Name = "Name", Value = "" }
                        }
                    }
                },
                new ODataProperty()
                {
                    Name = "Scores",
                    Value = new ODataCollectionValue()
                    {
                        Items = null
                    }
                },
            };

            var testCases = new[]
                {
                    new
                    {
                        ExpectedResults = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)(
                            (testConfiguration) => 
                            { 
                                if (testConfiguration.Format == ODataFormat.Atom)
                                {
                                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Xml = string.Format(
                                            @"<{0}:Id {1}:{2}=""Edm.Int32"" xmlns:{1}=""{3}"" xmlns:{0}=""{4}"">1</{0}:Id>",
                                            TestAtomConstants.ODataNamespacePrefix,
                                            TestAtomConstants.ODataMetadataNamespacePrefix,
                                            TestAtomConstants.AtomTypeAttributeName,
                                            TestAtomConstants.ODataMetadataNamespace,
                                            TestAtomConstants.ODataNamespace),
                                        FragmentExtractor = (element) => TestAtomUtils.ExtractPropertiesFromEntry(element)
                                            .Elements(TestAtomConstants.ODataXNamespace + "Id").Single()
                                    };
                                }
                                else
                                {
                                    return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Json = "$(JsonDataWrapperIndent)$(Indent)\"Id\":1",
                                        FragmentExtractor = (result) => JsonUtils.UnwrapTopLevelValue(testConfiguration, result).Object().Property("Id")
                                    };
                                }
                            })
                    },
                    new
                    {
                        ExpectedResults = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)(
                            (testConfiguration) => 
                            { 
                                if (testConfiguration.Format == ODataFormat.Atom)
                                {
                                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Xml = string.Format(
                                            @"<{0}:Name xmlns:{0}=""{1}"">Bill</{0}:Name>",
                                            TestAtomConstants.ODataNamespacePrefix,
                                            TestAtomConstants.ODataNamespace),
                                        FragmentExtractor = (element) => TestAtomUtils.ExtractPropertiesFromEntry(element)
                                            .Elements(TestAtomConstants.ODataXNamespace + "Name").Single()
                                    };
                                }
                                else
                                {
                                    return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Json = "$(JsonDataWrapperIndent)$(Indent)\"Name\":\"Bill\"",
                                        FragmentExtractor = (result) => JsonUtils.UnwrapTopLevelValue(testConfiguration, result).Object().Property("Name")
                                    };
                                }
                            })
                    },
                    new
                    {
                        ExpectedResults = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)(
                            (testConfiguration) => 
                            { 
                                if (testConfiguration.Format == ODataFormat.Atom)
                                {
                                    string xmlTemplate = 
                                        @"<{0}:Address {1}:{2}=""TestNS.AddressComplexType"" xmlns:{1}=""{3}"" xmlns:{0}=""{4}"">" +
                                            @"<{0}:Name></{0}:Name>" +
                                        @"</{0}:Address>";
                                    xmlTemplate = string.Format(xmlTemplate,
                                            TestAtomConstants.ODataNamespacePrefix,
                                            TestAtomConstants.ODataMetadataNamespacePrefix,
                                            TestAtomConstants.AtomTypeAttributeName,
                                            TestAtomConstants.ODataMetadataNamespace,
                                            TestAtomConstants.ODataNamespace);

                                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Xml = xmlTemplate,
                                        FragmentExtractor = (element) => TestAtomUtils.ExtractPropertiesFromEntry(element)
                                            .Elements(TestAtomConstants.ODataXNamespace + "Address").Single()
                                    };
                                }
                                else
                                {
                                    string json = string.Join(
                                        "$(NL)",
                                        "$(JsonDataWrapperIndent)$(Indent)\"Address\":{",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)\"__metadata\":{",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)$(Indent)\"type\":\"TestNS.AddressComplexType\"",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)},\"Name\":\"\"",
                                        "$(JsonDataWrapperIndent)$(Indent)}");
                                    return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Json = json,
                                        FragmentExtractor = (result) => JsonUtils.UnwrapTopLevelValue(testConfiguration, result).Object().Property("Address")
                                    };
                                }
                            })
                    },
                    new
                    {
                        ExpectedResults = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)(
                            (testConfiguration) => 
                            { 
                                if (testConfiguration.Format == ODataFormat.Atom)
                                {
                                    string xmlTemplate = @"<{0}:Scores {1}:{2}=""{5}"" xmlns:{1}=""{3}"" xmlns:{0}=""{4}"" />";
                                    xmlTemplate = string.Format(xmlTemplate,
                                            TestAtomConstants.ODataNamespacePrefix,
                                            TestAtomConstants.ODataMetadataNamespacePrefix,
                                            TestAtomConstants.AtomTypeAttributeName,
                                            TestAtomConstants.ODataMetadataNamespace,
                                            TestAtomConstants.ODataNamespace,
                                            EntityModelUtils.GetCollectionTypeName("Edm.String"));

                                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Xml = xmlTemplate,
                                        FragmentExtractor = (element) => TestAtomUtils.ExtractPropertiesFromEntry(element)
                                            .Elements(TestAtomConstants.ODataXNamespace + "Scores").Single()
                                    };
                                }
                                else
                                {
                                    string json = string.Join(
                                        "$(NL)",
                                        "$(JsonDataWrapperIndent)$(Indent)\"Scores\":{",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)\"__metadata\":{",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)$(Indent)\"type\":\"" + EntityModelUtils.GetCollectionTypeName("Edm.String") + "\"",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)},\"results\":[",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)$(Indent)",
                                        "$(JsonDataWrapperIndent)$(Indent)$(Indent)]",
                                        "$(JsonDataWrapperIndent)$(Indent)}",
                                        string.Empty);  // TODO: unclear why I need the extra $(NL) in this case.
                                    return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                    {
                                        Json = json,
                                        FragmentExtractor = (result) => JsonUtils.UnwrapTopLevelValue(testConfiguration, result).Object().Property("Scores")
                                    };
                                }
                            })
                    },
                };


            var testDescriptors = testCases.Select(tc =>
            {
                var descriptor = new PayloadWriterTestDescriptor<ODataItem>(this.Settings, entry, tc.ExpectedResults);
                descriptor.Model = model;
                return descriptor;
            });

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => tc.Format == ODataFormat.Atom),
                (testDescriptor, testConfig) =>
                {
                    testConfig.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfig, this.Assert, this.Logger);
                });
        }
Esempio n. 17
0
        public void PreserveSpaceTests()
        {
            ODataProperty property = ObjectModelUtils.CreateDefaultPrimitiveProperties().First(p => p.Name == "String");
            this.Assert.AreEqual("String", property.Name, "Expected string property to be the primitive property at position 16.");

            string[] whiteSpaces = new string[] 
            {
                " ",
                "\t",
                "\n",
                "\r",
                "\r\n",
            };
            string[] stringValues = whiteSpaces.SelectMany(s => new[] { string.Format("{0}foo", s), string.Format("foo{0}", s), string.Format("{0}foo{1}", s, s) }).ToArray();

            this.CombinatorialEngineProvider.SetBaselineCallback(() =>
            {
                // In this case the newline is the check point, but the diff reporter don't support this
                string payload = this.Logger.GetBaseline();
                payload = payload.Replace(Environment.NewLine, "@@Environment.NewLine@@");
                payload = payload.Replace("\r\n", "\\r\\n");
                payload = payload.Replace("\n", "\\n");
                payload = payload.Replace("\r", "\\r");
                payload = payload.Replace("@@Environment.NewLine@@", Environment.NewLine);

                return payload;
            });

            this.CombinatorialEngineProvider.RunCombinations(
                stringValues,
                this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent,
                (stringValue, testConfiguration) =>
                {
                    string atomResult = @"<{5} xmlns:{0}=""{1}"" xml:space=""preserve"" xmlns=""{1}"">{4}</{5}>";
                    atomResult = string.Format(atomResult,
                        TestAtomConstants.ODataMetadataNamespacePrefix,
                        TestAtomConstants.ODataMetadataNamespace,
                        TestAtomConstants.ODataNamespacePrefix,
                        TestAtomConstants.ODataNamespace,
                        stringValue.Replace("\r", "&#xD;"),
                        TestAtomConstants.ODataValueElementName);

                    property.Value = stringValue;
                    PayloadWriterTestDescriptor.WriterTestExpectedResultCallback expectedResultCallback =
                        (testConfig) =>
                        {
                            return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                FragmentExtractor = null,
                                Xml = atomResult
                            };
                        };

                    var testDescriptor = new PayloadWriterTestDescriptor<ODataProperty>(this.Settings, property, expectedResultCallback);
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                    testDescriptor.RunTopLevelPropertyPayload(testConfiguration, baselineLogger: this.Logger);
                });                        
        }
            public PayloadWriterTestDescriptor<ODataItem> ToEdmTestDescriptor(PayloadWriterTestDescriptor.Settings settings, EdmModel model = null, EdmEntitySet entitySet = null, EdmEntityType entityType = null)
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName = entityType == null ? null : entityType.FullName();

                return new PayloadWriterTestDescriptor<ODataItem>(
                    settings,
                    new ODataItem[] { entry }.Concat(this.Items).ToArray(),
                    testConfiguration =>
                    {
                        ExpectedException expectedException = this.ExpectedException;
                        if (this.EdmExpectedExceptionCallback != null)
                        {
                            expectedException = this.EdmExpectedExceptionCallback(testConfiguration, model);
                        }

                        if (testConfiguration.Format == ODataFormat.Atom)
                        {
                            return new AtomWriterTestExpectedResults(settings.ExpectedResultSettings)
                            {
                                FragmentExtractor = result => new XElement("results",
                                    result.Elements(TestAtomConstants.AtomXNamespace + "link")
                                        .Where(e => e.Attribute("rel").Value == (TestAtomConstants.ODataNavigationPropertiesRelatedLinkRelationPrefix + this.PropertyName))),
                                Xml = "<results>" + this.Xml + "</results>",
                                ExpectedException2 = expectedException
                            };
                        }
                        else if (testConfiguration.Format == ODataFormat.Json)
                        {
                            return new JsonWriterTestExpectedResults(settings.ExpectedResultSettings)
                            {
                                FragmentExtractor = result => new JsonObject().AddProperties(result.RemoveAllAnnotations(true).Object().GetPropertyAnnotationsAndProperty(this.PropertyName)),
                                Json = this.JsonLight,
                                ExpectedException2 = expectedException
                            };
                        }
                        else
                        {
                            settings.Assert.Fail("Unsupported format {0}", testConfiguration.Format);
                            return null;
                        }
                    })
                {
                    SkipTestConfiguration = this.SkipTestConfiguration,
                    Model = model,
                    PayloadEdmElementContainer = entitySet,
                    PayloadEdmElementType = entityType,
                };
            }
        public void InvalidEntryTypeTest()
        {
            Action<EdmModel> entityType = (model) =>
            {
                EdmEntityType newEntityType = new EdmEntityType("TestNS", "EntityType");
                model.AddElement(newEntityType);
            };

            Action<EdmModel> complexType = (model) =>
            {
                EdmComplexType newComplexType = new EdmComplexType("TestNS", "ComplexType");
                model.AddElement(newComplexType);
            };

            var testCases = new[] {
                new {
                    TypeName = (string)null,
                    TypeCreate = entityType,
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_MissingTypeNameWithMetadata"),
                },
                new {
                    TypeName = "",
                    TypeCreate = entityType,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_TypeNameMustNotBeEmpty"),
                },
                new {
                    TypeName = "EntityType",
                    TypeCreate = entityType,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "EntityType"),
                },
                new {
                    TypeName = "TestNS.ComplexType",
                    TypeCreate = complexType,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "TestNS.ComplexType", "Entity", "Complex"),
                },
            };

            var testDescriptors = testCases.Select(tc =>
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName = tc.TypeName;
                var descriptor = new PayloadWriterTestDescriptor<ODataItem>(
                    this.Settings,
                    entry,
                    (testConfiguration) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = tc.ExpectedException });

                EdmModel model = new EdmModel();
                tc.TypeCreate(model);
                var container = new EdmEntityContainer("TestNS", "TestContainer");
                model.AddElement(container);
                
                descriptor.Model = model;
                return descriptor;
            });

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

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
 public CollectionWriterTestDescriptor(Settings settings, string collectionName, string collectionTypeName, object[] payloadItems, PayloadWriterTestDescriptor.WriterTestExpectedResultCallback expectedResultCallback, IEdmModel model)
     : this(settings, collectionName, payloadItems, expectedResultCallback, model)
 {
     this.collectionTypeName = collectionTypeName;
 }
        public void MissingPropertyTest()
        {
            Func<EdmModel, EdmEntityType> entityType =
                (model) =>
                {
                    EdmComplexType addressType = new EdmComplexType("TestNS", "AddressComplexType");
                    model.AddElement(addressType);

                    EdmEntityType type = new EdmEntityType("TestNS", "EntityType");
                    type.AddKeys(type.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                    type.AddStructuralProperty("Addresses", new EdmComplexTypeReference(addressType, false));
                    model.AddElement(type);

                    return type;
                };

            Func<EdmModel, EdmEntityType> openEntityType =
                (model) =>
                {
                    EdmEntityType type = new EdmEntityType("TestNS", "EntityType", null, false, true);
                    type.AddKeys(type.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                    model.AddElement(type);

                    return type;
                };

            var testCases = new[] {
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "NonExistentProperty", 
                            Value = null
                        }),
                    MetadataCreate = entityType,
                    ExpectedResults = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)(
                        (testConfiguration) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) 
                        {
                            ExpectedException2 = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "NonExistentProperty", "TestNS.EntityType"),
                        })
                },
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataComplexValue() 
                            {
                                TypeName = "TestNS.AddressComplexType",
                                Properties = new ODataProperty[]
                                {
                                    new ODataProperty() { Name = "Street", Value = "One Microsoft Way" }
                                }

                            }
                        }),
                    MetadataCreate = entityType,
                    ExpectedResults = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)(
                        (testConfiguration) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        { 
                            ExpectedException2 = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "Street", "TestNS.AddressComplexType"),
                        })
                },
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "FirstName", 
                            Value = "Bill"
                        }),
                    MetadataCreate = openEntityType,
                    ExpectedResults = (PayloadWriterTestDescriptor<ODataItem>.WriterTestExpectedResultCallback)((testConfiguration) =>
                        {
                            if (testConfiguration.Format == ODataFormat.Atom)
                            {
                                // TODO, ckerer: follow up to see whether title has to be non-empty, is required at all on self/edit link, etc.
                                return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                {
                                    Xml = @"<d:FirstName xmlns:d=""" + TestAtomConstants.ODataNamespace + @""">Bill</d:FirstName>",
                                    FragmentExtractor = (element) => element.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomContentElementName).Single()
                                        .Elements(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.AtomPropertiesElementName).Single()
                                        .Elements(TestAtomConstants.ODataXNamespace + "FirstName").Single()
                                };
                            }
                            else
                            {
                                string jsonResult = "\"FirstName\":\"Bill\"";

                                return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings) 
                                { 
                                    Json = jsonResult,
                                    FragmentExtractor = (element) => JsonUtils.UnwrapTopLevelValue(testConfiguration, element).Object().Properties.Where(p => p.Name == "FirstName").Single()
                                };
                            }
                        })
                },
            };

            var testDescriptors = testCases.Select(tc =>
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName = "TestNS.EntityType";

                ODataProperty idProperty = new ODataProperty() { Name = "Id", Value = "1" };
                entry.Properties = new ODataProperty[] { idProperty, tc.PropertyCreate() };

                var descriptor = new PayloadWriterTestDescriptor<ODataItem>(this.Settings, entry, tc.ExpectedResults);
                var model = new EdmModel();
                tc.MetadataCreate(model);
                var container = new EdmEntityContainer("TestNS", "TestContainer");
                model.AddElement(container);
                descriptor.Model = model;
                return descriptor;
            });

            //TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => tc.Format == ODataFormat.Atom),
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
        public void InvalidCollectionItemTypeTest()
        {
            Func<EdmModel, EdmEntityType> entityTypeWithComplexCollectionProperty =
               (model) =>
               {
                   EdmComplexType addressType = new EdmComplexType("OtherTestNamespace", "AddressComplexType");
                   addressType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(true));
                   model.AddElement(addressType);

                   EdmComplexType otherComplexType = new EdmComplexType("OtherTestNamespace", "OtherComplexType");
                   model.AddElement(otherComplexType);

                   EdmEntityType type = new EdmEntityType("TestNS", "EntityType");
                   type.AddKeys(type.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                   type.AddStructuralProperty("Addresses", EdmCoreModel.GetCollection(new EdmComplexTypeReference(addressType, false)));
                   model.AddElement(type);

                   return type;
               };

            Func<EdmModel, EdmEntityType> entityTypeWithPrimitiveCollectionProperty =
                (model) =>
                {
                    EdmComplexType addressType = new EdmComplexType("OtherTestNamespace", "AddressComplexType");
                    model.AddElement(addressType);

                    EdmComplexType otherComplexType = new EdmComplexType("OtherTestNamespace", "OtherComplexType");
                    model.AddElement(otherComplexType);

                    EdmEntityType type = new EdmEntityType("TestNS", "EntityType");
                    type.AddKeys(type.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                    type.AddStructuralProperty("Addresses", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true)));
                    model.AddElement(type);

                    return type;
                };

            var testCases = new[] {
                // Primitive item in a complex collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue() 
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.AddressComplexType"), 
                                Items = new string[] { "One Redmond Way" } 
                            }
                        }),
                    MetadataCreate = entityTypeWithComplexCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                },
                // Complex item in a primitive collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue()
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("String"), 
                                Items = new ODataComplexValue[] 
                                { 
                                    new ODataComplexValue() { TypeName = "OtherTestNamespace.AddressComplexType" } 
                                }
                            }
                        }),
                    MetadataCreate = entityTypeWithPrimitiveCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                },
                // Type name of the collection doesn't match the metadata - complex collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue() 
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.OtherComplexType"), 
                                Items = new ODataComplexValue[0]
                            }
                        }),
                    MetadataCreate = entityTypeWithComplexCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.OtherComplexType"), EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.AddressComplexType")),
                },
                // Type name of the collection doesn't match the metadata - primitive collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue() 
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("Int32"), 
                                Items = new int[0]
                            }
                        }),
                    MetadataCreate = entityTypeWithPrimitiveCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", EntityModelUtils.GetCollectionTypeName("Edm.Int32"), EntityModelUtils.GetCollectionTypeName("Edm.String")),
                },
                // Item of a different primitive type in a complex collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue()
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("String"), 
                                Items = new int[] { 1 }
                            }
                        }),
                    MetadataCreate = entityTypeWithPrimitiveCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String"),
                },
                // Item of a different complex type in a complex collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue() 
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.AddressComplexType"), 
                                Items = new ODataComplexValue[] 
                                { 
                                    new ODataComplexValue() { TypeName = "OtherTestNamespace.OtherComplexType" } 
                                } 
                            }
                        }),
                    MetadataCreate = entityTypeWithComplexCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "OtherTestNamespace.OtherComplexType", "OtherTestNamespace.AddressComplexType"),
                },
                // Bogus item for a primitive collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue()
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("String"), 
                                Items = new object[] { new ODataMessageWriterSettings() }
                            }
                        }),
                    MetadataCreate = entityTypeWithPrimitiveCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnsupportedPrimitiveType", "Microsoft.OData.Core.ODataMessageWriterSettings"),
                },
                // Bogus item for a complex collection
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = new ODataCollectionValue() 
                            { 
                                TypeName = EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.AddressComplexType"), 
                                Items = new object[] { new ODataMessageWriterSettings() }
                            }
                        }),
                    MetadataCreate = entityTypeWithComplexCollectionProperty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnsupportedPrimitiveType", "Microsoft.OData.Core.ODataMessageWriterSettings"),
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testCase, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                    entry.TypeName = "TestNS.EntityType";
                    ODataProperty idProperty = new ODataProperty() { Name = "Id", Value = "1" };
                    entry.Properties = new ODataProperty[] { idProperty, testCase.PropertyCreate() };
                    var testDescriptor = new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        entry,
                        (tc) => 
                            new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) 
                            { 
                                ExpectedException2 = testCase.ExpectedException 
                            });
                    var model = new EdmModel();
                    testCase.MetadataCreate(model);
                    var container = new EdmEntityContainer("TestNS", "TestContainer");
                    model.AddElement(container);
                    testDescriptor.Model = model;

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
        public void ExpandedLinkWithNullNavigationTests()
        {
            ODataNavigationLink expandedEntryLink = ObjectModelUtils.CreateDefaultCollectionLink();
            expandedEntryLink.IsCollection = false;

            ODataNavigationLink expandedEntryLink2 = ObjectModelUtils.CreateDefaultCollectionLink();
            expandedEntryLink2.IsCollection = false;
            expandedEntryLink2.Name = expandedEntryLink2.Name + "2";

            ODataEntry defaultEntry = ObjectModelUtils.CreateDefaultEntry();
            ODataFeed defaultFeed = ObjectModelUtils.CreateDefaultFeed();
            ODataEntry nullEntry = ObjectModelUtils.ODataNullEntry;

            PayloadWriterTestDescriptor.WriterTestExpectedResultCallback successCallback = (testConfiguration) =>
            {
                if (testConfiguration.Format == ODataFormat.Atom)
                {
                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Xml = new XElement(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName).ToString(),
                        FragmentExtractor = (result) =>
                            {
                                return result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                                             .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null)
                                             .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName);
                            }
                    };
                }
                else
                {
                    return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Json = "null", //new JsonPrimitiveValue(null).ToText(testConfiguration.MessageWriterSettings.Indent),
                        FragmentExtractor = (result) =>
                        {
                            return JsonUtils.UnwrapTopLevelValue(testConfiguration, result).Object().Properties.First(p => p.Name == ObjectModelUtils.DefaultLinkName).Value;
                        }
                    };
                }

            };

            Func<ExpectedException,PayloadWriterTestDescriptor.WriterTestExpectedResultCallback> errorCallback = (expectedException) =>
                {
                    return (testConfiguration) =>
                        {
                            return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                ExpectedException2 = expectedException,
                            };
                        };
                };

            var testCases = new PayloadWriterTestDescriptor<ODataItem>[]
                {
                    // navigation to a null entry
                    new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        new ODataItem[] { defaultEntry, expandedEntryLink, nullEntry },
                        successCallback),

                    // navigation to a null entry twice
                    new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        new ODataItem[] {  defaultEntry, expandedEntryLink, nullEntry, null, null, expandedEntryLink2, nullEntry, null },
                        successCallback),

                    // top level null entry.
                    new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        new ODataItem[] { nullEntry },
                        errorCallback(new ExpectedException(typeof(ArgumentNullException)))),

                    // navigation to a null entry twice in expanded link
                    // this actually throws ArgumentNullException when WriteStart() for the second nullEntry is called since
                    // the state has been changed from NavigationLink to ExpandedLink after the first one.
                    // TODO: check if ArgumentNullException needs to change the WriterState.
                    new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        new ODataItem[] { defaultEntry, expandedEntryLink, nullEntry, null, nullEntry },
                        errorCallback(new ExpectedException(typeof(ArgumentNullException)))),

                    // Null entry inside a feed, same as above this throws ArgumentNullException but state is not put to error state.
                    new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        new ODataItem[] { defaultFeed, nullEntry },
                        errorCallback(new ExpectedException(typeof(ArgumentNullException)))),
                };

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => tc.Format == ODataFormat.Atom),
                (testCase, testConfig) =>
                {
                    testConfig = testConfig.Clone();
                    testConfig.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    TestWriterUtils.WriteAndVerifyODataPayload(testCase, testConfig, this.Assert, this.Logger);
                });
        }
        public void NullCollectionTest()
        {
            Func<EdmModel, EdmEntityType> entityTypeWithComplexCollectionProperty =
                (model) =>
                {
                    EdmComplexType addressType = new EdmComplexType("TestNS", "AddressComplexType");
                    addressType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(true));
                    model.AddElement(addressType);

                    EdmComplexType otherComplexType = new EdmComplexType("TestNS", "OtherComplexType");
                    model.AddElement(otherComplexType);

                    EdmEntityType type = new EdmEntityType("TestNS", "EntityType");
                    type.AddKeys(type.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                    type.AddStructuralProperty("Addresses", EdmCoreModel.GetCollection(new EdmComplexTypeReference(addressType, false)));
                    model.AddElement(type);

                    return type;
                };

            Func<EdmModel, EdmEntityType> entityTypeWithPrimitiveCollectionProperty =
                (model) =>
                {
                    EdmComplexType addressType = new EdmComplexType("TestNS", "AddressComplexType");
                    EdmComplexType otherComplexType = new EdmComplexType("TestNS", "OtherComplexType");
                    EdmEntityType type = new EdmEntityType("TestNS", "EntityType");
                    type.AddKeys(type.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                    type.AddStructuralProperty("Addresses", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true)));
                    model.AddElement(type);

                    return type;
                };

            ExpectedException expectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_CollectionPropertiesMustNotHaveNullValue", "Addresses");

            var testCases = new[] {
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = null
                        }),
                    MetadataCreate = entityTypeWithComplexCollectionProperty,
                    ExpectedException = expectedException
                },
                new {
                    PropertyCreate = (Func<ODataProperty>)(
                        () => new ODataProperty() 
                        { 
                            Name = "Addresses", 
                            Value = null
                        }),
                    MetadataCreate = entityTypeWithPrimitiveCollectionProperty,
                    ExpectedException = expectedException
                },
            };

            var testDescriptors = testCases.Select(tc =>
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName = "TestNS.EntityType";
                ODataProperty idProperty = new ODataProperty() { Name = "Id", Value = "1" };
                entry.Properties = new ODataProperty[] { idProperty, tc.PropertyCreate() };
                var descriptor = new PayloadWriterTestDescriptor<ODataItem>(
                    this.Settings,
                    entry,
                    (testConfiguration) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = tc.ExpectedException });
                var model = new EdmModel();
                tc.MetadataCreate(model);
                var container = new EdmEntityContainer("TestNS", "TestContainer");
                model.AddElement(container);
                descriptor.Model = model;
                return descriptor;
            });

            //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => tc.Format == ODataFormat.Atom),
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
Esempio n. 25
0
        private PayloadWriterTestDescriptor<ODataProperty> CreateNullPropertyOnComplexValueTestDescriptor(
            IEdmTypeReference dataType,
            ODataVersion version,
            bool allowNulls)
        {
            EdmPrimitiveTypeReference primitiveDataType = dataType as EdmPrimitiveTypeReference;
            EdmComplexTypeReference complexDataType = dataType as EdmComplexTypeReference;
            string typeName = primitiveDataType == null ? complexDataType.Definition.TestFullName() : primitiveDataType.Definition.TestFullName();

            var td = new PayloadWriterTestDescriptor<ODataProperty>(
                this.Settings,
                new ODataProperty
                {
                    Name = "complex",
                    Value = new ODataComplexValue
                    {
                        TypeName = "TestModel.ComplexType",
                        Properties = new[] { new ODataProperty { 
                                    Name = "nullProperty", 
                                    Value = null } }
                    }
                },
                (tc) =>
                {
                    if (allowNulls)
                    {
                        if (tc.Format == ODataFormat.Atom)
                        {
                            return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                Xml = "<d:nullProperty " +
                                    "m:null='true' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' xmlns:d='http://docs.oasis-open.org/odata/ns/data' />",
                                FragmentExtractor = (result) => result.Element(TestAtomConstants.ODataXNamespace + "nullProperty")
                            };
                        }
                        else if (tc.Format == ODataFormat.Json)
                        {
                            return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                Json = "\"nullProperty\":null",
                                FragmentExtractor = (result) => JsonLightWriterUtils.TrimWhitespace(result).Object().Property("nullProperty")
                            };
                        }
                        else
                        {
                            string formatName = tc.Format == null ? "null" : tc.Format.GetType().Name;
                            throw new NotSupportedException("Format " + formatName + " + is not supported.");
                        }
                    }
                    else
                    {
                        return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            ExpectedException2 = ODataExpectedExceptions.ODataException("WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue", "nullProperty", typeName),
                        };
                    }
                });

            EdmModel edmModel = new EdmModel();

            var complexType = new EdmComplexType("TestModel", "ComplexType");
            complexType.AddStructuralProperty("nullProperty", dataType);
            edmModel.AddElement(complexType);

            var entityType = new EdmEntityType("TestModel", "EntityType");
            entityType.AddStructuralProperty("complex", new EdmComplexTypeReference(complexType, isNullable: true));
            edmModel.AddElement(entityType);

            var container = new EdmEntityContainer("TestNS", "TestContainer");
            edmModel.AddElement(container);

            td.Model = edmModel as IEdmModel;

            td.PayloadEdmElementContainer = entityType;

            // NOTE: important to set Edm version to control null value validation!
            td.Model.SetEdmVersion(version.ToSystemVersion());

            return td;
        }
        public void InconsistentTypeNamesTest()
        {
            Func<EdmModel, EdmEntityType> entityType =
               (model) =>
               {
                   EdmComplexType addressComplexType = new EdmComplexType("TestNS", "AddressComplexType");
                   addressComplexType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(true));
                   model.AddElement(addressComplexType);

                   EdmComplexType orderComplexType = new EdmComplexType("OtherTestNamespace", "OrderComplexType");
                   model.AddElement(orderComplexType);

                   EdmEntityType type = new EdmEntityType("TestNS", "EntityType");
                   type.AddKeys(type.AddStructuralProperty("Id", EdmCoreModel.Instance.GetString(true)));
                   type.AddStructuralProperty("Address", new EdmComplexTypeReference(addressComplexType, false));
                   type.AddStructuralProperty("Scores", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true)));
                   type.AddStructuralProperty("Addresses", EdmCoreModel.GetCollection(new EdmComplexTypeReference(addressComplexType, false)));
                   model.AddElement(type);

                   return type;
               };

            ODataProperty[] defaultProperties = new ODataProperty[]
            {
                new ODataProperty() { Name = "Id", Value = "1" },
                new ODataProperty() 
                { 
                    Name = "Address", 
                    Value = new ODataComplexValue()
                    {
                        TypeName = "TestNS.AddressComplexType",
                        Properties = new ODataProperty[]
                        {
                            new ODataProperty { Name = "Street", Value = "First" }
                        }
                    }
                },
                new ODataProperty()
                {
                    Name = "Scores",
                    Value = new ODataCollectionValue()
                    {
                        TypeName = EntityModelUtils.GetCollectionTypeName("String"),
                        Items = null
                    }
                },
                new ODataProperty()
                {
                    Name = "Addresses",
                    Value = new ODataCollectionValue()
                    {
                        TypeName = EntityModelUtils.GetCollectionTypeName("TestNS.AddressComplexType"),
                        Items = new object[]
                        {
                            new ODataComplexValue()
                            {
                                TypeName = "TestNS.AddressComplexType",
                                Properties = null
                            }
                        }
                    }
                },
                new ODataProperty()
                {
                    Name = "Addresses",
                    Value = new ODataCollectionValue()
                    {
                        TypeName = EntityModelUtils.GetCollectionTypeName("TestNS.AddressComplexType"),
                        Items = new object[]
                        {
                            new ODataComplexValue()
                            {
                                TypeName = null,
                                Properties = null
                            }
                        }
                    }
                }
            };

            var testCases = new[] {
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            // inconsistent primitive type
                            new ODataProperty() { Name = "Id", Value = 1 },
                            defaultProperties[1],
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatiblePrimitiveItemType", "Edm.Int32", "False" /* nullable */, "Edm.String", "True" /* nullable */),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            // inconsistent primitive type
                            new ODataProperty() { Name = "Id", Value = new ODataComplexValue { } },
                            defaultProperties[1],
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKindNoTypeName", "Complex", "Primitive"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            // inconsistent primitive type
                            new ODataProperty() { Name = "Id", Value = new ODataCollectionValue { } },
                            defaultProperties[1],
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKindNoTypeName", "Collection", "Primitive"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            // inconsistent primitive type
                            new ODataProperty() { Name = "Id", Value = new ODataStreamReferenceValue { } },
                            defaultProperties[1],
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_MismatchPropertyKindForStreamProperty", "Id"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            // inconsistent complex type (same kind)
                            new ODataProperty()
                            {
                                Name = "Address", 
                                Value = new ODataComplexValue()
                                {
                                    TypeName = "OtherTestNamespace.OrderComplexType",
                                    Properties = null
                                }
                            },
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", "OtherTestNamespace.OrderComplexType", "TestNS.AddressComplexType"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            // inconsistent complex type (different kind)
                            new ODataProperty()
                            {
                                Name = "Address", 
                                Value = "some"
                            },
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_NonPrimitiveTypeForPrimitiveValue", "TestNS.AddressComplexType"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            // inconsistent complex type (different kind)
                            new ODataProperty()
                            {
                                Name = "Address", 
                                Value = new ODataCollectionValue { }
                            },
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKindNoTypeName", "Collection", "Complex"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            // inconsistent complex type (different kind)
                            new ODataProperty()
                            {
                                Name = "Address", 
                                Value = new ODataStreamReferenceValue { }
                            },
                            defaultProperties[2],
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_MismatchPropertyKindForStreamProperty", "Address"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            defaultProperties[1],
                            // inconsistent collection type
                            new ODataProperty()
                            {
                                Name = "Scores",
                                Value = new ODataCollectionValue()
                                {
                                    TypeName = EntityModelUtils.GetCollectionTypeName("Int32"),
                                    Items = null
                                }
                            },
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", EntityModelUtils.GetCollectionTypeName("Edm.Int32"), EntityModelUtils.GetCollectionTypeName("Edm.String")),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            defaultProperties[1],
                            new ODataProperty()
                            {
                                Name = "Scores",
                                Value = new ODataCollectionValue()
                                {
                                    TypeName = EntityModelUtils.GetCollectionTypeName("String"),
                                    // inconsistent collection item type (same kind)
                                    Items = new int[] { 1, 2, 3 }
                                }
                            },
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            defaultProperties[1],
                            new ODataProperty()
                            {
                                Name = "Scores",
                                Value = new ODataCollectionValue()
                                {
                                    TypeName = EntityModelUtils.GetCollectionTypeName("String"),
                                    // inconsistent collection item type (different kind)
                                    Items = new object[] 
                                    {
                                        new ODataComplexValue()
                                        {
                                            TypeName = "OtherTestNamespace.OrderComplexType",
                                            Properties = new ODataProperty[]
                                            {
                                                new ODataProperty { Name = "Street", Value = "First" }
                                            }
                                        }
                                    }
                                }
                            },
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            defaultProperties[1],
                            new ODataProperty()
                            {
                                Name = "Scores",
                                Value = new ODataCollectionValue()
                                {
                                    TypeName = EntityModelUtils.GetCollectionTypeName("String"),
                                    // inconsistent collection item type (different kind)
                                    Items = new object[] { new ODataStreamReferenceValue {} }
                                }
                            },
                            defaultProperties[3]
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections", EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.OrderComplexType"), EntityModelUtils.GetCollectionTypeName("TestNS.AddressComplexType")),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            defaultProperties[1],
                            defaultProperties[2],
                            // inconsistent collection type
                            new ODataProperty()
                            {
                                Name = "Addresses",
                                Value = new ODataCollectionValue()
                                {
                                    TypeName = EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.OrderComplexType"),
                                    Items = null
                                }
                            },
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", EntityModelUtils.GetCollectionTypeName("OtherTestNamespace.OrderComplexType"), EntityModelUtils.GetCollectionTypeName("TestNS.AddressComplexType")),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            defaultProperties[1],
                            defaultProperties[2],
                            new ODataProperty()
                            {
                                Name = "Addresses",
                                Value = new ODataCollectionValue()
                                {
                                    TypeName = EntityModelUtils.GetCollectionTypeName("TestNS.AddressComplexType"),
                                    Items = new object[]
                                    {
                                        new ODataComplexValue()
                                        {
                                            // inconsistent item type (same kind)
                                            TypeName = "OtherTestNamespace.OrderComplexType",
                                            Properties = new ODataProperty[]
                                            {
                                                new ODataProperty { Name = "Street", Value = "First" }
                                            }
                                        }
                                    }
                                }
                            },
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "OtherTestNamespace.OrderComplexType", "TestNS.AddressComplexType"),
                },
                new InconsistentTypeNamesTestCase {
                    CreateProperties = () => new ODataProperty[] 
                        { 
                            defaultProperties[0],
                            defaultProperties[1],
                            defaultProperties[2],
                            new ODataProperty()
                            {
                                Name = "Addresses",
                                Value = new ODataCollectionValue()
                                {
                                    TypeName = EntityModelUtils.GetCollectionTypeName("TestNS.AddressComplexType"),
                                    // inconsistent item type (different kind)
                                    Items = new object[] { "foo" }
                                }
                            },
                        },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                },
            };

            var testDescriptors = testCases.Select(tc => 
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName = "TestNS.EntityType";

                ODataProperty idProperty = new ODataProperty() { Name = "Id", Value = "1" };
                entry.Properties = tc.CreateProperties();

                var descriptor = new PayloadWriterTestDescriptor<ODataItem>(
                    this.Settings,
                    entry,
                    (testConfiguration) =>
                    {
                        ExpectedException expectedException = tc.ExpectedException;
                       
                        return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            ExpectedException2 = expectedException
                        };
                    });
                EdmModel model = new EdmModel();
                entityType(model);
                var container = new EdmEntityContainer("TestNS", "TestContainer");
                model.AddElement(container);

                descriptor.Model = model;
                return descriptor;
            });

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

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
Esempio n. 27
0
        private PayloadWriterTestDescriptor<ODataItem> CreateNullPropertyOnEntryTestDescriptor(
            IEdmTypeReference dataType,
            ODataVersion version,
            bool allowNulls)
        {
            EdmPrimitiveTypeReference primitiveDataType = dataType as EdmPrimitiveTypeReference;
            EdmComplexTypeReference complexDataType = dataType as EdmComplexTypeReference;
            string typeName = primitiveDataType == null ? complexDataType.Definition.TestFullName() : primitiveDataType.Definition.TestFullName();

            var td = new PayloadWriterTestDescriptor<ODataItem>(
                this.Settings,
                new ODataEntry
                {
                    TypeName = "TestModel.EntityType",
                    Properties = new[] { new ODataProperty { 
                                Name = "nullProperty", 
                                Value = null } },
                    SerializationInfo = MySerializationInfo
                },
                (tc) =>
                {
                    if (allowNulls)
                    {
                        if (tc.Format == ODataFormat.Atom)
                        {
                            return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                Xml = "<d:nullProperty " +
                                    "m:null='true' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' xmlns:d='http://docs.oasis-open.org/odata/ns/data' />",
                                FragmentExtractor = (result) => TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + "nullProperty")
                            };
                        }
                        else
                        {
                            return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                Json = "\"nullProperty\":null",
                                FragmentExtractor = (result) => JsonUtils.UnwrapTopLevelValue(tc, result).Object().Property("nullProperty")
                            };
                        }
                    }
                    else
                    {
                        return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            ExpectedException2 = ODataExpectedExceptions.ODataException("WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue", "nullProperty", typeName),
                        };
                    }
                });

            // doesn't have a clone method so has to new an EdmModel
            EdmModel edmModel = new EdmModel();

            var entityType = new EdmEntityType("TestModel", "EntityType");
            edmModel.AddElement(entityType);

            var container = new EdmEntityContainer("TestNS", "TestContainer");
            entityType.AddStructuralProperty("nullProperty", dataType);
            edmModel.AddElement(container);

            td.Model = edmModel as IEdmModel;

            // NOTE: important to set Edm version and to control null value validation!
            td.Model.SetEdmVersion(version.ToSystemVersion());

            return td;
        }
Esempio n. 28
0
        private PayloadWriterTestDescriptor<ODataItem> CreateNonNullPropertyOnEntryTestDescriptor(
            NonNullableEdmPrimitiveTypeWithValue nonNullablePrimitiveTypeWithValue,
            bool typeAttributeExpected,
            ODataVersion version,
            string propertyName)
        {
            string typeName = EdmCoreModel.Instance.GetPrimitive(nonNullablePrimitiveTypeWithValue.Type, true).Definition.TestFullName();

            bool isInvalidPropertyName = propertyName.IndexOfAny(InvalidCharactersInPropertyNames) >= 0;

            var td = new PayloadWriterTestDescriptor<ODataItem>(
                this.Settings,
                new ODataEntry
                {
                    TypeName = "TestModel.EntityType",
                    Properties = new[] { new ODataProperty { 
                                Name = propertyName, 
                                Value = nonNullablePrimitiveTypeWithValue.Value } },
                    SerializationInfo = MySerializationInfo
                },
                (tc) =>
                {
                    if (tc.Format == ODataFormat.Atom)
                    {
                        return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Xml = "<d:" + propertyName + " " +
                                (typeAttributeExpected ? ("m:type='" + typeName + "' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' ") : string.Empty) +
                                "xmlns:d='http://docs.oasis-open.org/odata/ns/data'>" +
                                nonNullablePrimitiveTypeWithValue.AtomRepresentation +
                                "</d:" + propertyName + ">",
                            FragmentExtractor = (result) => TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + propertyName),
                            ExpectedException2 = isInvalidPropertyName
                                    ? ODataExpectedExceptions.ODataException("ValidationUtils_PropertiesMustNotContainReservedChars", propertyName, "':', '.', '@'")
                                    : null,
                        };
                    }
                    else if (tc.Format == ODataFormat.Json)
                    {
                        return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = "\"" + JsonLightConstants.ODataValuePropertyName + "\":" + nonNullablePrimitiveTypeWithValue.JsonLightRepresentation,
                            FragmentExtractor = (result) => JsonLightWriterUtils.TrimWhitespace(result).Object().Property(propertyName),
                            ExpectedException2 = isInvalidPropertyName
                                    ? ODataExpectedExceptions.ODataException("ValidationUtils_PropertiesMustNotContainReservedChars", propertyName, "':', '.', '@'")
                                    : null,
                        };
                    }
                    else
                    {
                        string formatName = tc.Format == null ? "null" : tc.Format.GetType().Name;
                        throw new NotSupportedException("Format " + formatName + " + is not supported.");
                    }
                });

            EdmModel edmModel = new EdmModel();

            var entityType = new EdmEntityType("TestModel", "EntityType");
            entityType.AddStructuralProperty(propertyName, EdmCoreModel.Instance.GetPrimitive(nonNullablePrimitiveTypeWithValue.Type, false));
            edmModel.AddElement(entityType);

            var container = new EdmEntityContainer("TestNS", "TestContainer");
            edmModel.AddElement(container);

            td.Model = edmModel as IEdmModel;


            // NOTE: important to set Edm version and to control null value validation!
            td.Model.SetEdmVersion(version.ToSystemVersion());

            return td;
        }
Esempio n. 29
0
        public void PropertyInStreamErrorTests()
        {
            EdmModel model = new EdmModel();
            ODataProperty property = ObjectModelUtils.CreateDefaultPrimitiveProperties(model)[0];
            var container = new EdmEntityContainer("TestModel", "DefaultContainer");
            model.AddElement(container);

            var entityType = model.FindType("TestModel.EntryWithPrimitiveProperties") as EdmEntityType;

            this.Assert.AreEqual("Null", property.Name, "Expected null property to be the first primitive property.");

            PayloadWriterTestDescriptor<ODataProperty>[] testDescriptors = new PayloadWriterTestDescriptor<ODataProperty>[]
                {
                    new PayloadWriterTestDescriptor<ODataProperty>(this.Settings, property, (string)null, (string)null)
                    {
                        Model = model,
                        PayloadEdmElementContainer = entityType
                    },
                };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                TestWriterUtils.InvalidSettingSelectors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, selector, testConfiguration) =>
                {
                    TestWriterUtils.WriteWithStreamErrors(
                        testDescriptor,
                        selector,
                        testConfiguration,
                        (messageWriter) => messageWriter.WriteProperty(testDescriptor.PayloadItems.Single()),
                        this.Assert);
                });
        }
        public void WriterStreamPropertiesTests()
        {
            Uri baseUri = new Uri("http://www.odata.org/", UriKind.Absolute);
            Uri relativeReadLinkUri = new Uri("readlink", UriKind.RelativeOrAbsolute);
            Uri relativeEditLinkUri = new Uri("editlink", UriKind.RelativeOrAbsolute);
            Uri absoluteReadLinkUri = new Uri(baseUri, relativeReadLinkUri.OriginalString);
            Uri absoluteEditLinkUri = new Uri(baseUri, relativeEditLinkUri.OriginalString);

            string contentType = "application/binary";
            string etag = "\"myetagvalue\"";
            string streamPropertyName = "stream1";

            var namedStreamProperties = new[]
            {
                // with only read link
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = relativeReadLinkUri }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = relativeReadLinkUri, ContentType = contentType}},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = absoluteReadLinkUri }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = absoluteReadLinkUri, ContentType = contentType}},
                // with only edit link
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { EditLink = relativeEditLinkUri }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { EditLink = relativeEditLinkUri, ContentType = contentType }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { EditLink = absoluteEditLinkUri }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { EditLink = absoluteEditLinkUri, ContentType = contentType }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { EditLink = absoluteEditLinkUri, ContentType = contentType, ETag = etag }},
                // with both edit and read link
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType}},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri }},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType}},
                new ODataProperty { Name = streamPropertyName, Value = new ODataStreamReferenceValue { ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag }},
            };

            var testCases = namedStreamProperties.Select(property =>
            {
                var propertyName = property.Name;
                var streamReferenceValue = (ODataStreamReferenceValue)property.Value;
                return new StreamPropertyTestCase
                {
                    NamedStreamProperty = property,
                    GetExpectedAtomPayload = (testConfiguration) =>
                        {
                            return
                                (streamReferenceValue.ReadLink == null
                                    ? string.Empty
                                    : (
                                        "<link rel=\"http://docs.oasis-open.org/odata/ns/mediaresource/" + property.Name + "\" " +
                                        (streamReferenceValue.ContentType == null ? string.Empty : "type=\"" + streamReferenceValue.ContentType + "\" ") +
                                        "title=\"" + property.Name + "\" " +
                                        "href=\"" + (((ODataStreamReferenceValue)property.Value).ReadLink.IsAbsoluteUri ? absoluteReadLinkUri.OriginalString : relativeReadLinkUri.OriginalString) + "\" " +
                                        "xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />")) +

                                (streamReferenceValue.EditLink == null
                                    ? string.Empty
                                    : (
                                        "<link rel=\"http://docs.oasis-open.org/odata/ns/edit-media/" + property.Name + "\" " +
                                        (streamReferenceValue.ContentType == null ? string.Empty : "type=\"" + streamReferenceValue.ContentType + "\" ") +
                                        "title=\"" + property.Name + "\" " +
                                        "href=\"" + (((ODataStreamReferenceValue)property.Value).EditLink.IsAbsoluteUri ? absoluteEditLinkUri.OriginalString : relativeEditLinkUri.OriginalString) + "\" " +
                                        (streamReferenceValue.ETag == null ? string.Empty : "m:etag=\"" + streamReferenceValue.ETag.Replace("\"", "&quot;") + "\" xmlns:m=\"" + TestAtomConstants.ODataMetadataNamespace + "\" ") +
                                        "xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />"));
                        },
                    GetExpectedJsonLightPayload = (testConfiguration) =>
                        {
                            return JsonLightWriterUtils.CombineProperties(
                                (streamReferenceValue.EditLink == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"" + absoluteEditLinkUri.OriginalString + "\"")),
                                (streamReferenceValue.ReadLink == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"" + absoluteReadLinkUri.OriginalString + "\"")),
                                (streamReferenceValue.ContentType == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"" + streamReferenceValue.ContentType + "\"")),
                                (streamReferenceValue.ETag == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"" + streamReferenceValue.ETag.Replace("\"", "\\\"") + "\"")));
                        },
                };
            });

            var testDescriptors = testCases.SelectMany(testCase =>
                {
                    EdmModel model = new EdmModel();
                    
                    EdmEntityType edmEntityType = new EdmEntityType("TestModel", "StreamPropertyEntityType");
                    EdmStructuralProperty edmStructuralProperty= edmEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false);
                    edmEntityType.AddKeys(new IEdmStructuralProperty[]{edmStructuralProperty});
                    model.AddElement(edmEntityType);

                    EdmEntityContainer edmEntityContainer = new EdmEntityContainer("TestModel", "DefaultContainer");
                    model.AddElement(edmEntityContainer);

                    EdmEntitySet edmEntitySet = new EdmEntitySet(edmEntityContainer, "StreamPropertyEntitySet", edmEntityType);
                    edmEntityContainer.AddElement(edmEntitySet);

                    ODataEntry entry = new ODataEntry()
                    {
                        Id = ObjectModelUtils.DefaultEntryId,
                        ReadLink = ObjectModelUtils.DefaultEntryReadLink,
                        TypeName = edmEntityType.FullName()
                    };
                    
                    var streamReference = (ODataStreamReferenceValue)testCase.NamedStreamProperty.Value;
                    bool needBaseUri = (streamReference.ReadLink != null && !streamReference.ReadLink.IsAbsoluteUri) || (streamReference.EditLink != null && !streamReference.EditLink.IsAbsoluteUri);
                    entry.Properties = new ODataProperty[] { testCase.NamedStreamProperty };

                    var resultDescriptor = new PayloadWriterTestDescriptor<ODataItem>(
                        this.Settings,
                        entry,
                        (testConfiguration) =>
                        {
                            if (testConfiguration.Format == ODataFormat.Atom)
                            {
                                return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                {
                                    Xml = "<NamedStream>" + testCase.GetExpectedAtomPayload(testConfiguration) + "</NamedStream>",
                                    FragmentExtractor = result => result,
                                };
                            }
                            else if (testConfiguration.Format == ODataFormat.Json)
                            {
                                return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                                {
                                    Json = string.Join(
                                        "$(NL)",
                                        "{",
                                        testCase.GetExpectedJsonLightPayload(testConfiguration),
                                        "}"),
                                    FragmentExtractor = result => result.RemoveAllAnnotations(true),
                                };
                            }
                            else
                            {
                                throw new NotSupportedException("Unsupported ODataFormat found: " + testConfiguration.Format.ToString());
                            }
                        })
                        {
                            Model = model,
                            PayloadEdmElementContainer = edmEntityContainer,
                            PayloadEdmElementType = edmEntityType,
                        };

                    var resultTestCases = new List<StreamPropertyTestDescriptor>();
                    if (needBaseUri)
                    {
                        resultTestCases.Add(new StreamPropertyTestDescriptor { BaseUri = baseUri, TestDescriptor = resultDescriptor });
                    }
                    else
                    {
                        resultTestCases.Add(new StreamPropertyTestDescriptor { BaseUri = null, TestDescriptor = resultDescriptor });
                        resultTestCases.Add(new StreamPropertyTestDescriptor { BaseUri = baseUri, TestDescriptor = resultDescriptor });
                        resultTestCases.Add(new StreamPropertyTestDescriptor { BaseUri = new Uri("http://mybaseuri/", UriKind.Absolute), TestDescriptor = resultDescriptor });
                    }

                    return resultTestCases;
                });

            var testDescriptorBaseUriPairSet = testDescriptors.SelectMany(descriptor =>
                WriterPayloads.NamedStreamPayloads(descriptor.TestDescriptor).Select(namedStreamPayload =>
                     new Tuple<PayloadWriterTestDescriptor<ODataItem>, Uri>(namedStreamPayload, descriptor.BaseUri)));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptorBaseUriPairSet,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptorBaseUriPair, testConfiguration) =>
                {
                    var testDescriptor = testDescriptorBaseUriPair.Item1;

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

                    ODataMessageWriterSettings settings = testConfiguration.MessageWriterSettings.Clone();
                    settings.PayloadBaseUri = testDescriptorBaseUriPair.Item2;
                    settings.SetServiceDocumentUri(ServiceDocumentUri);

                    WriterTestConfiguration config =
                        new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);

                    if (testConfiguration.IsRequest)
                    {
                        ODataEntry payloadEntry = (ODataEntry)testDescriptor.PayloadItems[0];
                        ODataProperty firstStreamProperty = payloadEntry.Properties.Where(p => p.Value is ODataStreamReferenceValue).FirstOrDefault();
                        this.Assert.IsNotNull(firstStreamProperty, "firstStreamProperty != null");

                        testDescriptor = new PayloadWriterTestDescriptor<ODataItem>(testDescriptor)
                        {
                            ExpectedResultCallback = tc => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                            {
                                ExpectedException2 = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamPropertyInRequest", firstStreamProperty.Name)
                            }
                        };
                    }

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, config, this.Assert, this.Logger);
                });
        }
Esempio n. 31
0
        private Action<WriterTestConfiguration> WriteEntityReferenceLink(Func<XElement, XElement> fragmentExtractor, string expectedXml, bool isClient, string odataNamespace)
        {
            var sampleLink = new ODataEntityReferenceLink { Url = new Uri("http://odata.org/link") };

            return (testConfiguration) =>
            {
                PayloadWriterTestDescriptor<ODataEntityReferenceLink> descriptor = null;
                    descriptor = new PayloadWriterTestDescriptor<ODataEntityReferenceLink>(
                        this.Settings,
                        sampleLink,
                        expectedXml,
                        null,
                        fragmentExtractor,
                        null);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    descriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLink(sampleLink),
                    this.Assert,
                    baselineLogger: this.Logger);
            };
        }