Exemplo n.º 1
0
        public void ContentTypeHeaderParsingTest()
        {
            IEnumerable <ContentTypeTestCase> testCases = new ContentTypeTestCase[]
            {
                #region Atom test cases
                new ContentTypeTestCase
                {
                    // only reading an entry or feed should succeed
                    ContentType    = "application/atom+xml;type=feed",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // only reading an entry or feed should succeed
                    ContentType    = "application/atom+xml;type=entry",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a feed, an entry, and metadata should succeed
                    ContentType    = "application/atom+xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a property, an entity reference link, entity reference links, a collection, a service document, and an error should succeed
                    ContentType    = "application/xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a property, an entity reference link, entity reference links, and a collection should succeed
                    ContentType    = "text/xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a service document should succeed
                    ContentType    = "application/atomsvc+xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                #endregion Atom test cases

                #region RawValue test cases
                new ContentTypeTestCase
                {
                    // only reading a raw value will succeed
                    ContentType    = "text/plain",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk == ODataPayloadKind.Value ||
                                                  pk == ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only reading a raw value or binary value will succeed; raw values can be read as binary values when the content type is application/octet-stream
                    ContentType    = "application/octet-stream",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk == ODataPayloadKind.Value ||
                                                  pk == ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only raw value / binary value will succeed
                    ContentType    = "multipart/mixed",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // Test for: MimeType allows 0x7F character, but ContentType parsing doesn't
                    ContentType    = "application/" + 0x7F,
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => false,
                },

                #endregion RawValue test cases

                #region JSON Lite test cases
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLight,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLightStreaming,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLightNonStreaming,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                #endregion JSON Lite test cases

                #region Error test cases
                new ContentTypeTestCase
                {
                    // unsupported content type; everything will fail
                    ContentType = "application/foo",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // unsupported content type with parameters; everything will fail
                    ContentType = "abc/pqr;a=b;c=d",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // "image/jpeg" is not supported, even for raw values.
                    ContentType = "image/jpeg",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                #endregion Error test cases

                #region Content Type is null or empty
                new ContentTypeTestCase
                {
                    // null content type and zero content length should be default to Json if the payload kind is not binary value or value.
                    ContentType    = null,
                    ContentLength  = 0,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk => true,
                    ShouldIgnoreTest            = pk => pk == ODataPayloadKind.BinaryValue || pk == ODataPayloadKind.Value
                },
                new ContentTypeTestCase
                {
                    // null content type and zero content length should be default to RawValue if the payload kind is binary value or value.
                    ContentType    = null,
                    ContentLength  = 0,
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => true,
                    ShouldIgnoreTest            = pk => pk != ODataPayloadKind.Value
                },
                #endregion
            };

            string[] parameters = new string[]
            {
                "foo=bar",
                "foo1=bar1;foo2=bar2"
            };

            testCases = testCases.Concat(testCases.Where(tc => tc.ContentType != null).SelectMany(tc => parameters.Select(p => new ContentTypeTestCase(tc)
            {
                ContentType = tc.ContentType + ";" + p
            })));

            int oDataPayloadKindCount = EnumExtensionMethods.GetValues <ODataPayloadKind>().Length;

            this.Assert.AreEqual(oDataPayloadKindCount, TestReaderUtils.ODataPayloadKinds.Length, "The number of payload kind have changed, please update this test.");

            IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            // We don't support batch payloads here; we test those separately in BatchContentTypeHeaderParsingTest
            IEnumerable <ODataPayloadKind> payloadKinds =
                TestReaderUtils.ODataPayloadKinds.Where(k => k != ODataPayloadKind.Batch && k != ODataPayloadKind.Unsupported);

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                payloadKinds,
                this.ReaderTestConfigurationProvider.AllFormatConfigurations,
                (testCase, payloadKind, testConfiguration) =>
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.EnableAtom = false;
                if (IgnoreTestCase(payloadKind, testConfiguration))
                {
                    return;
                }

                if (testCase.ShouldIgnoreTest != null && testCase.ShouldIgnoreTest(payloadKind))
                {
                    return;
                }

                string supportedMediaTypes;

                if (payloadKind == ODataPayloadKind.Value || payloadKind == ODataPayloadKind.BinaryValue)
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Value) + ", " + TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.BinaryValue);
                }
                else
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(payloadKind, /*includeAppJson*/ true);
                }

                ExpectedException expectedException = testCase.ExpectedException == null
                         ? testCase.ShouldSucceedForPayloadKind != null && testCase.ShouldSucceedForPayloadKind(payloadKind)
                             ? null
                             : ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", supportedMediaTypes, testCase.ContentType ?? "")
                         : testCase.ExpectedException;

                // Make sure to run success test cases only in configurations that will work.
                if (expectedException == null &&
                    testConfiguration.Format != null &&
                    testCase.ExpectedFormat != testConfiguration.Format)
                {
                    return;
                }

                ODataPayloadElement payloadElement = CreatePayloadElement(model, payloadKind, testConfiguration);

                // When we write a value with a content type different than 'text/plain', we will read it as binary.
                // Likewise, when we write a binary value with a 'text/plain' content type, we will read it as a string.
                Func <ReaderTestConfiguration, ODataPayloadElement> expectedResultElementFunc = null;
                if (payloadKind == ODataPayloadKind.Value && testCase.ContentType != null && !testCase.ContentType.StartsWith("text/plain"))
                {
                    expectedResultElementFunc = (testConfig) => ConvertToBinaryPayloadElement(payloadElement);
                }
                else if (payloadKind == ODataPayloadKind.BinaryValue && testCase.ContentType != null && testCase.ContentType.StartsWith("text/plain"))
                {
                    expectedResultElementFunc = (testConfig) => ConvertToStringPayloadElement(payloadElement);
                }

                ODataFormat expectedFormat = testCase.ExpectedFormat;

                ReaderContentTypeTestDescriptor testDescriptor = new ReaderContentTypeTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                    ExpectedResultPayloadElement = expectedResultElementFunc,
                    PayloadEdmModel   = model,
                    ExpectedFormat    = expectedFormat,
                    ContentType       = testCase.ContentType,
                    ExpectedException = expectedException
                };

                testDescriptor.RunTest(testConfiguration);
                testConfiguration.MessageReaderSettings.EnableAtom = true;
            });
        }
Exemplo n.º 2
0
        public void BatchContentTypeHeaderParsingTest()
        {
            IEnumerable <ContentTypeTestCase> testCases = new ContentTypeTestCase[]
            {
                // correct batch content type
                new ContentTypeTestCase
                {
                    ContentType    = "multipart/mixed;boundary=--aa_bb_cc--",
                    ExpectedFormat = ODataFormat.Batch,
                },

                // missing batch boundary
                new ContentTypeTestCase
                {
                    ContentType       = "multipart/mixed",
                    ExpectedFormat    = ODataFormat.Batch,
                    ExpectedException = ODataExpectedExceptions.ODataException("MediaTypeUtils_BoundaryMustBeSpecifiedForBatchPayloads", "multipart/mixed", "boundary")
                },

                // multiple batch boundary parameters
                new ContentTypeTestCase
                {
                    ContentType       = "multipart/mixed;boundary=boundary1;boundary=boundary2",
                    ExpectedFormat    = ODataFormat.Batch,
                    ExpectedException = ODataExpectedExceptions.ODataException("MediaTypeUtils_BoundaryMustBeSpecifiedForBatchPayloads", "multipart/mixed;boundary=boundary1;boundary=boundary2", "boundary")
                },

                // invalid batch content types
                new ContentTypeTestCase
                {
                    ContentType       = "multipart/bar",
                    ExpectedFormat    = ODataFormat.Batch,
                    ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), "multipart/bar")
                },
                new ContentTypeTestCase
                {
                    ContentType       = "foo/mixed",
                    ExpectedFormat    = ODataFormat.Batch,
                    ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), "foo/mixed")
                },
                new ContentTypeTestCase
                {
                    ContentType       = "abc/pqr",
                    ExpectedFormat    = ODataFormat.Batch,
                    ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), "abc/pqr")
                },
                new ContentTypeTestCase
                {
                    ContentType       = ApplicationJson,
                    ExpectedFormat    = ODataFormat.Batch,
                    ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), ApplicationJson)
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.ReaderTestConfigurationProvider.DefaultFormatConfigurations,
                (testCase, testConfiguration) =>
            {
                // create a message reader and call GetFormat; this should fail with the expected error message
                TestMessage testMessage = TestReaderUtils.CreateInputMessageFromStream(new TestStream(), testConfiguration);
                testMessage.SetHeader(Microsoft.OData.Core.ODataConstants.ContentTypeHeader, testCase.ContentType);

                TestExceptionUtils.ExpectedException(
                    this.Assert,
                    () =>
                {
                    using (ODataMessageReaderTestWrapper messageReader = TestReaderUtils.CreateMessageReader(testMessage, null, testConfiguration))
                    {
                        messageReader.CreateODataBatchReader();
                        ODataFormat actualFormat = ODataUtils.GetReadFormat(messageReader.MessageReader);
                        this.Assert.AreEqual(testCase.ExpectedFormat, actualFormat, "Formats don't match.");
                    }
                },
                    testCase.ExpectedException,
                    this.ExceptionVerifier);
            });
        }
Exemplo n.º 3
0
        public void ContentTypeHeaderParsingWithClientBehaviorTest()
        {
            // In V1 and V2 clients, application/xml and application/atom+xml are valid for all of the following payload kinds.
            Func <ODataPayloadKind, bool> isXmlPayloadKind =
                pk =>
                pk == ODataPayloadKind.Feed ||
                pk == ODataPayloadKind.Entry ||
                pk == ODataPayloadKind.MetadataDocument ||
                pk == ODataPayloadKind.Property ||
                pk == ODataPayloadKind.EntityReferenceLink ||
                pk == ODataPayloadKind.Collection ||
                pk == ODataPayloadKind.ServiceDocument ||
                pk == ODataPayloadKind.Error;

            // In V3 (whether under client knob or not), we should be spec
            // compliant and only allow application/atom+xml for feeds and
            // entries and application/xml for all other xml payload kinds.
            // When running the test cases, we replace ShouldSucceedForPayloadKind
            // with isXmlPayloadKind when dealing with pre-V3 clients.
            var testCases = new[]
            {
                new ContentTypeTestCase
                {
                    ContentType    = "application/atom+xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    ContentType    = "application/xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
            };

            IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            IEnumerable <ODataPayloadKind> payloadKinds =
                TestReaderUtils.ODataPayloadKinds.Where(k => k != ODataPayloadKind.Batch && k != ODataPayloadKind.Unsupported);

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                payloadKinds,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testCase, payloadKind, testConfiguration) =>
            {
                // Run under the client knob.
                testConfiguration = testConfiguration.CloneAndApplyBehavior(TestODataBehaviorKind.WcfDataServicesClient);
                testConfiguration.MessageReaderSettings.EnableAtom = false;

                if (IgnoreTestCase(payloadKind, testConfiguration))
                {
                    return;
                }

                // If version is V1 or V2, we should succeed for all xml payload kinds if the mime type is application/atom+xml or application/xml.
                Func <ODataPayloadKind, bool> shouldSucceedForPayloadKind = testCase.ShouldSucceedForPayloadKind;

                // Get supported media types to use in expected error message.
                string supportedMediaTypes;

                if (payloadKind == ODataPayloadKind.Value || payloadKind == ODataPayloadKind.BinaryValue)
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Value) + ", " + TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.BinaryValue);
                }
                else
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(payloadKind);
                }

                ExpectedException expectedException = testCase.ExpectedException == null
                        ? shouldSucceedForPayloadKind != null && shouldSucceedForPayloadKind(payloadKind)
                            ? null
                            : ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", supportedMediaTypes, testCase.ContentType)
                        : testCase.ExpectedException;

                ODataPayloadElement payloadElement = CreatePayloadElement(model, payloadKind, testConfiguration);
                ODataFormat expectedFormat         = testCase.ExpectedFormat;

                ReaderContentTypeTestDescriptor testDescriptor = new ReaderContentTypeTestDescriptor(this.Settings)
                {
                    PayloadElement    = payloadElement,
                    PayloadEdmModel   = model,
                    ExpectedFormat    = expectedFormat,
                    ContentType       = testCase.ContentType,
                    ExpectedException = expectedException
                };

                testDescriptor.RunTest(testConfiguration);
            });
        }
Exemplo n.º 4
0
        /// <summary>
        /// Helper method to run a single iteration of the URI reading tests in a specified configuration.
        /// </summary>
        /// <typeparam name="T">The type of the payload to read.</typeparam>
        /// <param name="payloadElement">The payload to read.</param>
        /// <param name="setExpectedUriAction">An action to set the URI in question on the payload.</param>
        /// <param name="model">The metadata model.</param>
        /// <param name="payloadUri">The payload URI for the current iteration.</param>
        /// <param name="baseUriValue">The base URI value for the current iteration.</param>
        /// <param name="resolver">The resolver to use.</param>
        /// <param name="testConfiguration">The reader test configuration.</param>
        private void RunBaseUriReadingTest <T>(
            T payloadElement,
            Action <T, Uri, ReaderTestConfiguration> setExpectedUriAction,
            IEdmModel model,
            Uri payloadUri,
            BaseUriValue baseUriValue,
            KeyValuePair <Func <Uri, Uri, Uri, Uri>, Uri> resolver,
            ReaderTestConfiguration testConfiguration,
            bool runInBatch = false) where T : ODataPayloadElement
        {
            this.Assert.IsNull(testConfiguration.MessageReaderSettings.BaseUri, "No base URI expected on reader settings.");
            ExpectedException expectedException = null;

            Uri settingsBaseUri = baseUriValue.ReaderSettingBaseUri;

            // Set the base URI on the message reader settings if specified
            if (settingsBaseUri != null)
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.BaseUri = settingsBaseUri;
            }

            // Create the payload element
            T clonedPayloadElement = payloadElement.DeepCopy();

            setExpectedUriAction(clonedPayloadElement, payloadUri, testConfiguration);

            if (testConfiguration.Format == ODataFormat.Atom)
            {
                XElement xmlRepresentation = this.PayloadElementToXmlConverter.ConvertToXml(clonedPayloadElement);

                // add an xml:base attribute if specified
                Uri xmlBaseUri = baseUriValue.XmlBaseUri;
                if (xmlBaseUri != null)
                {
                    xmlRepresentation.Add(new XAttribute(XNamespace.Xml.GetName("base"), xmlBaseUri.OriginalString));
                }

                clonedPayloadElement.XmlRepresentation(xmlRepresentation);

                if (resolver.Value != null)
                {
                    setExpectedUriAction(clonedPayloadElement, resolver.Value, testConfiguration);
                }
                else
                {
                    // compute the expected URI value for ATOM
                    if (!payloadUri.IsAbsoluteUri)
                    {
                        if (xmlBaseUri != null)
                        {
                            setExpectedUriAction(clonedPayloadElement, new Uri(xmlBaseUri, payloadUri), testConfiguration);
                        }
                        else if (settingsBaseUri != null)
                        {
                            setExpectedUriAction(clonedPayloadElement, new Uri(settingsBaseUri, payloadUri), testConfiguration);
                        }
                        else
                        {
                            // fail for relative URIs without base URI
                            expectedException = ODataExpectedExceptions.ODataException("ODataAtomDeserializer_RelativeUriUsedWithoutBaseUriSpecified", payloadUri.OriginalString);
                        }
                    }
                }
            }
            else
            {
                throw new NotSupportedException("Unsupported configuration format: " + testConfiguration.Format.ToString());
            }

            PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(resolver.Key == null ? this.Settings : this.NoValidatorSettings)
            {
                PayloadElement    = clonedPayloadElement,
                PayloadEdmModel   = model,
                ExpectedException = expectedException,
                UrlResolver       = resolver.Key == null ? null : new TestUrlResolver {
                    ResolutionCallback = (baseUri, realPayloadUri) => resolver.Key(payloadUri, baseUri, realPayloadUri)
                },
                SkipTestConfiguration = tc => ODataPayloadElementConfigurationValidator.GetSkipTestConfiguration(payloadElement, ODataPayloadElementConfigurationValidator.AllValidators)(tc),
            };

            if (runInBatch)
            {
                // TODO: Batch reader does not enter Exception state upon cross reference error in payload.
                // Once fixed allow the batch tests to run even for error cases.
                if (expectedException != null)
                {
                    return;
                }

                if (testConfiguration.IsRequest)
                {
                    testDescriptor = new PayloadReaderTestDescriptor(testDescriptor)
                    {
                        PayloadElement =
                            PayloadBuilder.BatchRequestPayload(
                                BatchUtils.GetRequestChangeset(
                                    new IMimePart[] { testDescriptor.PayloadDescriptor.InRequestOperation(
                                                          HttpVerb.Put,
                                                          new ODataUri(ODataUriBuilder.Root(new Uri("http://odata.org/service"))),
                                                          this.RequestManager,
                                                          TestMediaTypeUtils.GetDefaultContentType(testDescriptor.PayloadDescriptor.PayloadKind, testConfiguration.Format)) },
                                    this.RequestManager))
                            .AddAnnotation(new BatchBoundaryAnnotation("bb_request"))
                    };
                }
                else
                {
                    testDescriptor = new PayloadReaderTestDescriptor(testDescriptor)
                    {
                        PayloadElement =
                            PayloadBuilder.BatchResponsePayload(
                                testDescriptor.PayloadDescriptor.InResponseOperation(
                                    200,
                                    this.RequestManager,
                                    TestMediaTypeUtils.GetDefaultContentType(testDescriptor.PayloadDescriptor.PayloadKind, testConfiguration.Format)))
                            .AddAnnotation(new BatchBoundaryAnnotation("bb_response"))
                    };
                }

                testConfiguration = new ReaderTestConfiguration(null, testConfiguration.MessageReaderSettings, testConfiguration.IsRequest, testConfiguration.Synchronous, testConfiguration.Version);
            }

            testDescriptor.RunTest(testConfiguration);
        }