Beispiel #1
0
        /// <summary>
        /// Creates an <see cref="ODataCollectionWriter"/> for the specified format and the specified version and
        /// invokes the specified methods on it. It then parses
        /// the written Xml/JSON and compares it to the expected result as specified in the descriptor.
        /// </summary>
        /// <param name="descriptor">The test descriptor to process.</param>
        /// <param name="testConfiguration">The configuration of the test.</param>
        /// <param name="assert">The assertion handler to report errors to.</param>
        /// <param name="baselineLogger">Logger to log baseline.</param>
        internal static void WriteAndVerifyCollectionPayload(CollectionWriterTestDescriptor descriptor, WriterTestConfiguration testConfiguration, AssertionHandler assert, BaselineLogger baselineLogger)
        {
            baselineLogger.LogConfiguration(testConfiguration);
            baselineLogger.LogModelPresence(descriptor.Model);

            // serialize to a memory stream
            using (var memoryStream = new MemoryStream())
                using (var testMemoryStream = new TestStream(memoryStream, ignoreDispose: true))
                {
                    TestMessage testMessage = null;
                    Exception   exception   = TestExceptionUtils.RunCatching(() =>
                    {
                        using (var messageWriter = TestWriterUtils.CreateMessageWriter(testMemoryStream, testConfiguration, assert, out testMessage, null, descriptor.Model))
                        {
                            IEdmTypeReference itemTypeReference = descriptor.ItemTypeParameter;
                            ODataCollectionWriter writer        = itemTypeReference == null
                            ? messageWriter.CreateODataCollectionWriter()
                            : messageWriter.CreateODataCollectionWriter(itemTypeReference);
                            WriteCollectionPayload(messageWriter, writer, true, descriptor);
                        }
                    });
                    exception = TestExceptionUtils.UnwrapAggregateException(exception, assert);

                    WriterTestExpectedResults expectedResults = descriptor.ExpectedResultCallback(testConfiguration);
                    TestWriterUtils.ValidateExceptionOrLogResult(testMessage, testConfiguration, expectedResults, exception, assert, descriptor.TestDescriptorSettings.ExpectedResultSettings.ExceptionVerifier, baselineLogger);
                    TestWriterUtils.ValidateContentType(testMessage, expectedResults, true, assert);
                }
        }
        /// <summary>
        /// Creates the expected result callback by computing the expected Xml and JSON responses
        /// based on the expected results for the items in a collection.
        /// </summary>
        /// <param name="collectionName">The name of the collection.</param>
        /// <param name="itemDescriptions">The items descriptions to created the expected result for.</param>
        /// <param name="errorOnly">A flag indicating whether we are writing only error items or not.</param>
        /// <param name="assert">The assertion handler to use.</param>
        /// <returns>
        /// A <see cref="PayloadWriterTestDescriptor.WriterTestExpectedResultCallback"/> that will be used 
        /// during test execution to validate the results.
        /// </returns>
        internal static PayloadWriterTestDescriptor.WriterTestExpectedResultCallback CreateExpectedResultCallback(
            string collectionName,
            CollectionWriterTestDescriptor.ItemDescription[] itemDescriptions,
            bool errorOnly,
            WriterTestExpectedResults.Settings settings)
        {
            CollectionWriterTestDescriptor.ItemDescription[] items = itemDescriptions;
            bool writeCollection = items != null;
            items = items ?? new CollectionWriterTestDescriptor.ItemDescription[0];

            string xmlResultTemplate, jsonLightResultTemplate;
            CreateResultTemplates(writeCollection, items, out xmlResultTemplate, out jsonLightResultTemplate);

            return (testConfiguration) =>
                {
                    if (testConfiguration.Format == ODataFormat.Atom)
                    {
                        return new AtomWriterTestExpectedResults(settings) 
                        {
                            Xml = PopulateXmlResultTemplate(collectionName, xmlResultTemplate),
                            FragmentExtractor = (result) => NormalizeNamespacePrefixes(result),
                        };
                    }
                    else if (testConfiguration.Format == ODataFormat.Json)
                    {
                        return new JsonWriterTestExpectedResults(settings)
                        {
                            Json = jsonLightResultTemplate,
                            FragmentExtractor = (result) => errorOnly
                                ? result.Object().PropertyValue(JsonLightConstants.ODataErrorPropertyName)
                                : result.Object().PropertyValue("value"),
                        };
                    }
                    else
                    {
                        throw new NotSupportedException("Unsupported format " + testConfiguration.Format.ToString() + " found.");
                    }
                };
        }
 public CollectionWriterTestCase(CollectionWriterTestDescriptor.ItemDescription[] items, IEdmOperationImport functionImport)
 {
     this.items = items;
     this.functionImport = functionImport;
 }
        public void HeterogeneousCollectionWriterWithoutMetadataTest()
        {
            var collections = new[]
            {
                // Collection with different item type kinds (complex instead of primitive)
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { intItem(0), complexItem(/*typeName*/null) },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                },

                // Collection where item type kind does not match item type name (primitive and complex items)
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { stringItem(string.Empty), complexItem(/*typeName*/null) },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                },

                // Collection where item type names don't match (Edm.String and Edm.Int32)
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { stringItem(string.Empty), intItem(2) },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String"),
                },

                // Collection where item type names don't match (Edm.String and Edm.Int32); including some null items
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { nullItem, stringItem(string.Empty), nullItem, intItem(2), nullItem },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.Int32", "Edm.String"),
                },

                // Collection where item type names don't match (TestModel.SomeComplexType and TestModel.OtherComplexType)
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { complexItem("TestModel.SomeComplexType"), complexItem("TestModel.OtherComplexType") },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "TestModel.OtherComplexType", "TestModel.SomeComplexType"),
                },

                // Collection where item type names don't match (TestModel.SomeComplexType and TestModel.OtherComplexType); including some null items
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { nullItem, complexItem("TestModel.SomeComplexType"), nullItem, complexItem("TestModel.OtherComplexType"), nullItem },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "TestModel.OtherComplexType", "TestModel.SomeComplexType"),
                },

                // Collection where different item type kinds (primitive instead of complex)
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { complexItem("TestModel.SomeComplexType"), intItem(0) },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                },

                // Collection with primitive and complex elements
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { stringItem("Foo"), complexItem("TestModel.SomeComplexType"), stringItem("Perth") },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                },

                // Collection with primitive and geographic elements
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { stringItem("Foo"), GetGeographyMultiLineStringItem() },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.GeographyMultiLineString", "Edm.String"),
                },

                // Collection with primitive and geometric elements
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { stringItem("Foo"), GetGeometryPointItem() },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.GeometryPoint", "Edm.String"),
                },

                // Collection with geographic and geometric elements
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { GetGeographyPointItem(), GetGeometryPointItem() },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.GeometryPoint", "Edm.GeographyPoint"),
                },

                // Collection with complex and geometric elements
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { complexItem(/*typename*/ null), GetGeometryPointItem() },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                },

                // Collection with complex and geometric elements
                new 
                {
                    Items = new CollectionWriterTestDescriptor.ItemDescription[] { complexItem(/*typename*/ null), GetGeometryPointItem() },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                },
            };

            const string collectionName = "TestCollection";

            this.CombinatorialEngineProvider.RunCombinations(
                collections,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => tc.IsRequest == false),
                (collection, testConfig) =>
                {
                    CollectionWriterTestDescriptor testDescriptor = new CollectionWriterTestDescriptor(this.Settings, collectionName, collection.Items, collection.ExpectedException, null);
                    CollectionWriterUtils.WriteAndVerifyCollectionPayload(testDescriptor, testConfig, this.Assert, this.Logger);
                });
        }
        public void HomogeneousCollectionWriterWithoutMetadataTest()
        {
            var collections = new[]
            {
                // Primitive collection with only nulls
                new CollectionWriterTestDescriptor.ItemDescription[] { nullItem, nullItem, nullItem },

                // Primitive collection with type names on string values
                new CollectionWriterTestDescriptor.ItemDescription[] { stringItem("foo"), stringItem("bar") },

                // Primitive collection with type names on Int32 values
                new CollectionWriterTestDescriptor.ItemDescription[] { intItem(1), intItem(2) },

                // Primitive collection with type names on Int32 values and null values
                new CollectionWriterTestDescriptor.ItemDescription[] { intItem(1), nullItem, intItem(2), nullItem },

                // Complex collection with type names on complex values
                new CollectionWriterTestDescriptor.ItemDescription[] { complexItem("TestNS.AddressType"), complexItem("TestNS.AddressType") },
                
                // Complex collection with type names on complex values and null values
                new CollectionWriterTestDescriptor.ItemDescription[] { complexItem("TestNS.AddressType"), nullItem, complexItem("TestNS.AddressType") },

                // Complex collection without type names on complex values
                new CollectionWriterTestDescriptor.ItemDescription[] { complexItem(/*typeName*/null), complexItem(/*typeName*/null) },

                // Complex collection without type names on complex values and null values
                new CollectionWriterTestDescriptor.ItemDescription[] { complexItem(/*typeName*/null), nullItem, complexItem(/*typeName*/null) },

                // Primitive collection with different geographic and null values
                new CollectionWriterTestDescriptor.ItemDescription[] {
                    GetGeographyPointItem("GeographyPoint"),
                    nullItem,
                    GetGeographyPolygonItem("GeographyPolygon"),
                    GetGeographyMultiLineStringItem("GeographyMultiLineString"),
                    GetGeographyCollectionItem("GeographyCollection")
                },

                // Primitive collection with different geometric and null values
                new CollectionWriterTestDescriptor.ItemDescription[] {
                    GetGeometryPointItem("GeometryPoint"),
                    nullItem,
                    GetGeometryPolygonItem("GeometryPolygon"),
                    GetGeometryMultiLineStringItem("GeometryMultiLineString"),
                    GetGeometryCollectionItem("GeometryCollection") },
                };

            const string collectionName = "TestCollection";

            this.CombinatorialEngineProvider.RunCombinations(
                collections,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => tc.IsRequest == false),
                (collection, testConfig) =>
                {
                    CollectionWriterTestDescriptor testDescriptor = new CollectionWriterTestDescriptor(this.Settings, collectionName, collection, null);
                    CollectionWriterUtils.WriteAndVerifyCollectionPayload(testDescriptor, testConfig, this.Assert, this.Logger);
                });
        }
        public void CollectionPayloadErrorTest()
        {
            EdmModel model = new EdmModel();
            var addressType = new EdmComplexType("TestNS", "AddressType");
            addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String, isNullable: true);
            addressType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String, isNullable: true);
            addressType.AddStructuralProperty("Zip", EdmPrimitiveTypeKind.Int32, isNullable: false);
            model.AddElement(addressType);
            var container = new EdmEntityContainer("TestNS", "TestContainer");
            model.AddElement(container);

            var testCases = new[]
            {
                new
                {
                    Items = new [] { nullItem, intItem(1), stringItem("One")},
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.String", "Edm.Int32"),
                },
                new
                {
                    Items = new [] { complexItem("TestNS.AddressType"), nullItem, intItem(1) },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Primitive", "Complex"),
                },
                new
                {
                    Items = new [] { stringItem("One"), nullItem, complexItem("TestNS.AddressType") },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeKind", "Complex", "Primitive"),
                },
                new
                {
                    Items = new [] { stringItem("One"), nullItem, GetGeometryPointItem() },
                    ExpectedException = ODataExpectedExceptions.ODataException("CollectionWithoutExpectedTypeValidator_IncompatibleItemTypeName", "Edm.GeometryPoint", "Edm.String"),
                }
            };

            const string collectionName = "TestCollection";

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => tc.IsRequest == false && tc.Format == ODataFormat.Atom),
                (testCase, testConfig) =>
                {
                    CollectionWriterTestDescriptor testDescriptor = new CollectionWriterTestDescriptor(this.Settings, collectionName, testCase.Items, testCase.ExpectedException, /*model*/ null);
                    CollectionWriterUtils.WriteAndVerifyCollectionPayload(testDescriptor, testConfig, this.Assert, this.Logger);

                    testDescriptor = new CollectionWriterTestDescriptor(this.Settings, collectionName, testCase.Items, testCase.ExpectedException, model);
                    CollectionWriterUtils.WriteAndVerifyCollectionPayload(testDescriptor, testConfig, this.Assert, this.Logger);
                });
        }
        public void CollectionPayloadTest()
        {
            IEdmPrimitiveTypeReference int32NullableTypeRef = EdmCoreModel.Instance.GetInt32(isNullable: true);
            IEdmStringTypeReference stringTypeRef = EdmCoreModel.Instance.GetString(isNullable: true);
            var model = new EdmModel();
            var addressType = new EdmComplexType("TestNS", "AddressType");
            addressType.AddStructuralProperty("Street", stringTypeRef);
            addressType.AddStructuralProperty("City", stringTypeRef);
            addressType.AddStructuralProperty("Zip", EdmPrimitiveTypeKind.Int32);
            model.AddElement(addressType);

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

            var intServiceOp = new EdmFunction("TestNS", "GetIntCollection", EdmCoreModel.GetCollection(int32NullableTypeRef));
            intServiceOp.AddParameter("a", int32NullableTypeRef);
            intServiceOp.AddParameter("b", stringTypeRef);
            var intServiceOpFunctionImport = container.AddFunctionImport("GetIntCollection", intServiceOp);

            EdmFunction stringServiceOp = new EdmFunction("TestNS", "GetStringCollection", EdmCoreModel.GetCollection(stringTypeRef));
            stringServiceOp.AddParameter("a", int32NullableTypeRef);
            stringServiceOp.AddParameter("b", stringTypeRef);
            var stringServiceOpFunctionImport = container.AddFunctionImport("GetStringCollection", stringServiceOp);

            EdmFunction complexServiceOp = new EdmFunction("TestNS", "GetComplexCollection", EdmCoreModel.GetCollection(new EdmComplexTypeReference(addressType, true)));
            complexServiceOp.AddParameter("a", int32NullableTypeRef);
            complexServiceOp.AddParameter("b", stringTypeRef);
            var complexServiceOpFunctionImport = container.AddFunctionImport("GetComplexCollection", complexServiceOp);

            EdmFunction geometryServiceOp = new EdmFunction("TestNS", "GetGeometryCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geometry, true)));
            geometryServiceOp.AddParameter("a", int32NullableTypeRef);
            geometryServiceOp.AddParameter("b", stringTypeRef);
            var geometryServiceOpFunctionImport = container.AddFunctionImport("GetGeometryCollection", geometryServiceOp);

            EdmFunction geographyServiceOp = new EdmFunction("TestNS", "GetGeographyCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geography, true)));
            geographyServiceOp.AddParameter("a", int32NullableTypeRef);
            geographyServiceOp.AddParameter("b", stringTypeRef);
            var geographyServiceOpFunctionImport = container.AddFunctionImport("GetGeographyCollection", geographyServiceOp);

            model.AddElement(container);
            model.AddElement(intServiceOp);
            model.AddElement(stringServiceOp);
            model.AddElement(complexServiceOp);
            model.AddElement(geometryServiceOp);
            model.AddElement(geographyServiceOp);

            IEnumerable<CollectionWriterTestCase> testCases = new[]
            {
                new CollectionWriterTestCase(new CollectionWriterTestDescriptor.ItemDescription[]
                         {
                             nullItem,
                             intItem(1),
                             intItem(2),
                         }, intServiceOpFunctionImport),

                new CollectionWriterTestCase(new CollectionWriterTestDescriptor.ItemDescription[]
                         {
                             nullItem,
                             stringItem("One"),
                             stringItem("Two"),
                         }, stringServiceOpFunctionImport),

                new CollectionWriterTestCase(new CollectionWriterTestDescriptor.ItemDescription[]
                         {
                             nullItem,
                             complexItem("TestNS.AddressType"),
                             complexItem("TestNS.AddressType"),
                         }, complexServiceOpFunctionImport),

                new CollectionWriterTestCase(new CollectionWriterTestDescriptor.ItemDescription[]
                         {
                             nullItem,
                             GetGeometryPointItem("GeometryPoint"),
                             GetGeometryPolygonItem("GeometryPolygon"),
                             GetGeometryCollectionItem("GeometryCollection"),
                             GetGeometryMultiLineStringItem("GeometryMultiLineString"),
                         }, geometryServiceOpFunctionImport),

                new CollectionWriterTestCase(new CollectionWriterTestDescriptor.ItemDescription[]
                         {
                             nullItem,
                             GetGeographyPointItem("GeographyPoint"),
                             GetGeographyPolygonItem("GeographyPolygon"),
                             GetGeographyCollectionItem("GeographyCollection"),
                             GetGeographyMultiLineStringItem("GeographyMultiLineString"),
                         }, geographyServiceOpFunctionImport),
            };

            IEnumerable<CollectionWriterTestCase> cases = testCases;
            int[] collectionSizes = new int[] { 0, 1, 3 };
            testCases = collectionSizes.SelectMany(length =>
                cases.SelectMany(tc =>
                    tc.Items.Combinations(true, length).Select(items =>
                       new CollectionWriterTestCase(items, tc.FunctionImport))));

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                new bool[] { false, true },
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => tc.IsRequest == false),
                (testCase, withModel, testConfig) =>
                {
                    if (testConfig.Format == ODataFormat.Json && !withModel)
                    {
                        return;
                    }

                    IEdmTypeReference type = null;

                    if (withModel)
                    {
                        type = testCase.FunctionImport.Operation.ReturnType.AsCollection().ElementType(); 
                    }

                    CollectionWriterTestDescriptor testDescriptor = new CollectionWriterTestDescriptor(this.Settings, testCase.FunctionImport.Name, testCase.Items, withModel ? model : null)
                    {
                        ItemTypeParameter = type
                    };

                    CollectionWriterUtils.WriteAndVerifyCollectionPayload(testDescriptor, testConfig, this.Assert, this.Logger);
                });
        }
        private static object[] CreatePayloadItems(
            CollectionWriterTestDescriptor.WriterInvocations[] invocations,
            ItemDescription payloadItem,
            ItemDescription errorItem,
            out ItemDescription[] itemDescriptions,
            out bool errorOnly)
        {
            if (invocations == null || invocations.Length == 0)
            {
                itemDescriptions = null;
                errorOnly = false;
                return null;
            }

            List<object> payloadItems = new List<object>();
            List<ItemDescription> descriptions = new List<ItemDescription>();

            bool? onlyErrorsWritten = null;
            for (int i = 0; i < invocations.Length; ++i)
            {
                switch (invocations[i])
                {
                    case CollectionWriterTestDescriptor.WriterInvocations.StartCollection:
                        break;
                    case CollectionWriterTestDescriptor.WriterInvocations.Item:
                        payloadItems.Add(payloadItem.Item);
                        descriptions.Add(payloadItem);
                        onlyErrorsWritten = false;
                        break;
                    case CollectionWriterTestDescriptor.WriterInvocations.Error:
                        payloadItems.Add(errorItem.Item);
                        descriptions.Add(errorItem);
                        if (!onlyErrorsWritten.HasValue)
                        {
                            onlyErrorsWritten = true;
                        }
                        break;
                    case CollectionWriterTestDescriptor.WriterInvocations.EndCollection:
                        break;

                    case CollectionWriterTestDescriptor.WriterInvocations.UserException:
                        break;

                    default:
                        throw new NotSupportedException("Unsupported invocation kind.");
                }
            }

            itemDescriptions = descriptions.ToArray();
            errorOnly = onlyErrorsWritten.HasValue && onlyErrorsWritten.Value;
            return payloadItems.ToArray();
        }
        /// <summary>
        /// Writes the collection payload as specified in the <paramref name="testDescriptor"/>.
        /// </summary>
        /// <param name="messageWriter">The message writer.</param>
        /// <param name="writer">The writer to write to.</param>
        /// <param name="flush">True if the stream should be flush before returning; otherwise false.</param>
        /// <param name="testDescriptor">The test descriptor specifying the collection to write.</param>
        internal static void WriteCollectionPayload(ODataMessageWriterTestWrapper messageWriter, ODataCollectionWriter writer, bool flush, CollectionWriterTestDescriptor testDescriptor)
        {
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(testDescriptor != null, "testDescriptor != null");

            object[] payloadItems = testDescriptor.PayloadItems;
            int payloadItemIndex = 0;
            foreach (CollectionWriterTestDescriptor.WriterInvocations invocation in testDescriptor.Invocations)
            {
                switch (invocation)
                {
                    case CollectionWriterTestDescriptor.WriterInvocations.StartCollection:
                        ODataCollectionStartSerializationInfo serInfo = null;
                        if (!string.IsNullOrEmpty(testDescriptor.CollectionTypeName))
                        {
                            serInfo = new ODataCollectionStartSerializationInfo();
                            serInfo.CollectionTypeName = testDescriptor.CollectionTypeName;
                        }

                        writer.WriteStart(new ODataCollectionStart { Name = testDescriptor.CollectionName, SerializationInfo = serInfo });
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.Item:
                        object payloadItem = payloadItems[payloadItemIndex];

                        ODataError error = payloadItem as ODataError;
                        if (error != null)
                        {
                            throw new InvalidOperationException("Expected payload item but found an error.");
                        }

                        writer.WriteItem(payloadItem);
                        payloadItemIndex++;
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.Error:
                        ODataAnnotatedError error2 = testDescriptor.PayloadItems[payloadItemIndex] as ODataAnnotatedError;
                        if (error2 == null)
                        {
                            throw new InvalidOperationException("Expected an error but found a payload item.");
                        }

                        messageWriter.WriteError(error2.Error, error2.IncludeDebugInformation);
                        payloadItemIndex++;
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.EndCollection:
                        writer.WriteEnd();
                        break;
                    
                    case CollectionWriterTestDescriptor.WriterInvocations.UserException:
                        throw new Exception("User code triggered an exception.");

                    default:
                        break;
                }
            }

            if (flush)
            {
                writer.Flush();
            }
        }
        /// <summary>
        /// Creates an <see cref="ODataCollectionWriter"/> for the specified format and the specified version and
        /// invokes the specified methods on it. It then parses
        /// the written Xml/JSON and compares it to the expected result as specified in the descriptor.
        /// </summary>
        /// <param name="descriptor">The test descriptor to process.</param>
        /// <param name="testConfiguration">The configuration of the test.</param>
        /// <param name="assert">The assertion handler to report errors to.</param>
        /// <param name="baselineLogger">Logger to log baseline.</param>
        internal static void WriteAndVerifyCollectionPayload(CollectionWriterTestDescriptor descriptor, WriterTestConfiguration testConfiguration, AssertionHandler assert, BaselineLogger baselineLogger)
        {
            baselineLogger.LogConfiguration(testConfiguration);
            baselineLogger.LogModelPresence(descriptor.Model);

            // serialize to a memory stream
            using (var memoryStream = new MemoryStream())
            using (var testMemoryStream = new TestStream(memoryStream, ignoreDispose: true))
            {
                TestMessage testMessage = null;
                Exception exception = TestExceptionUtils.RunCatching(() =>
                {
                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(testMemoryStream, testConfiguration, assert, out testMessage, null, descriptor.Model))
                    {
                        IEdmTypeReference itemTypeReference = descriptor.ItemTypeParameter;
                        ODataCollectionWriter writer = itemTypeReference == null
                            ? messageWriter.CreateODataCollectionWriter()
                            : messageWriter.CreateODataCollectionWriter(itemTypeReference);
                        WriteCollectionPayload(messageWriter, writer, true, descriptor);
                    }
                });
                exception = TestExceptionUtils.UnwrapAggregateException(exception, assert);

                WriterTestExpectedResults expectedResults = descriptor.ExpectedResultCallback(testConfiguration);
                TestWriterUtils.ValidateExceptionOrLogResult(testMessage, testConfiguration, expectedResults, exception, assert, descriptor.TestDescriptorSettings.ExpectedResultSettings.ExceptionVerifier, baselineLogger);
                TestWriterUtils.ValidateContentType(testMessage, expectedResults, true, assert);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Writes the collection payload as specified in the <paramref name="testDescriptor"/>.
        /// </summary>
        /// <param name="messageWriter">The message writer.</param>
        /// <param name="writer">The writer to write to.</param>
        /// <param name="flush">True if the stream should be flush before returning; otherwise false.</param>
        /// <param name="testDescriptor">The test descriptor specifying the collection to write.</param>
        internal static void WriteCollectionPayload(ODataMessageWriterTestWrapper messageWriter, ODataCollectionWriter writer, bool flush, CollectionWriterTestDescriptor testDescriptor)
        {
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(testDescriptor != null, "testDescriptor != null");

            object[] payloadItems     = testDescriptor.PayloadItems;
            int      payloadItemIndex = 0;

            foreach (CollectionWriterTestDescriptor.WriterInvocations invocation in testDescriptor.Invocations)
            {
                switch (invocation)
                {
                case CollectionWriterTestDescriptor.WriterInvocations.StartCollection:
                    ODataCollectionStartSerializationInfo serInfo = null;
                    if (!string.IsNullOrEmpty(testDescriptor.CollectionTypeName))
                    {
                        serInfo = new ODataCollectionStartSerializationInfo();
                        serInfo.CollectionTypeName = testDescriptor.CollectionTypeName;
                    }

                    writer.WriteStart(new ODataCollectionStart {
                        Name = testDescriptor.CollectionName, SerializationInfo = serInfo
                    });
                    break;

                case CollectionWriterTestDescriptor.WriterInvocations.Item:
                    object payloadItem = payloadItems[payloadItemIndex];

                    ODataError error = payloadItem as ODataError;
                    if (error != null)
                    {
                        throw new InvalidOperationException("Expected payload item but found an error.");
                    }

                    writer.WriteItem(payloadItem);
                    payloadItemIndex++;
                    break;

                case CollectionWriterTestDescriptor.WriterInvocations.Error:
                    ODataAnnotatedError error2 = testDescriptor.PayloadItems[payloadItemIndex] as ODataAnnotatedError;
                    if (error2 == null)
                    {
                        throw new InvalidOperationException("Expected an error but found a payload item.");
                    }

                    messageWriter.WriteError(error2.Error, error2.IncludeDebugInformation);
                    payloadItemIndex++;
                    break;

                case CollectionWriterTestDescriptor.WriterInvocations.EndCollection:
                    writer.WriteEnd();
                    break;

                case CollectionWriterTestDescriptor.WriterInvocations.UserException:
                    throw new Exception("User code triggered an exception.");

                default:
                    break;
                }
            }

            if (flush)
            {
                writer.Flush();
            }
        }