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 ODataResource()) }, tc => new WriterTestExpectedResults(this.ExpectedResultSettings) { ExpectedException2 = ODataExpectedExceptions.ODataException("WriterValidationUtils_MissingTypeNameWithMetadata") }) { 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); }); }
private Action <WriterTestConfiguration> WriteEntityReferenceLinks(Func <XElement, XElement> fragmentExtractor, string expectedXml) { var sampleLinks = new ODataEntityReferenceLinks(); return((testConfiguration) => { PayloadWriterTestDescriptor <ODataEntityReferenceLinks> descriptor = new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>( this.Settings, sampleLinks, expectedXml, null, fragmentExtractor, null, /*disableXmlNamespaceNormalization*/ true); // Top-level EntityReferenceLinks payload write requests are not allowed. if (testConfiguration.IsRequest) { descriptor.ExpectedResultCallback = (testConfig) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed") }; } TestWriterUtils.WriteAndVerifyTopLevelContent( descriptor, testConfiguration, (messageWriter) => messageWriter.WriteEntityReferenceLinks(sampleLinks), this.Assert, baselineLogger: this.Logger); }); }
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); }); }
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); }); }
public void EntityReferenceLinkErrorTest() { string resultUriString = "http://odata.org/linkresult"; ODataEntityReferenceLink resultLink = new ODataEntityReferenceLink { Url = new Uri(resultUriString) }; PayloadWriterTestDescriptor <ODataEntityReferenceLink>[] testCases = new PayloadWriterTestDescriptor <ODataEntityReferenceLink>[] { new PayloadWriterTestDescriptor <ODataEntityReferenceLink>(this.Settings, resultLink, (string)null, (string)null), }; this.CombinatorialEngineProvider.RunCombinations( testCases, this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent, TestWriterUtils.InvalidSettingSelectors, (testCase, testConfiguration, selector) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); if (testConfiguration.Format == ODataFormat.Json) { testCase.Model = CreateModelWithNavProps(); var edmModel = testCase.GetMetadataProvider(); } TestWriterUtils.WriteWithStreamErrors( testCase, selector, testConfiguration, (messageWriter) => messageWriter.WriteEntityReferenceLink(testCase.PayloadItems.Single()), this.Assert); }); }
public void EntityReferenceLinksErrorTest() { string resultUri1String = "http://odata.org/linkresult1"; string resultUri2String = "http://odata.org/linkresult2"; string resultUri3String = "http://odata.org/linkresult3"; ODataEntityReferenceLink resultUri1 = new ODataEntityReferenceLink { Url = new Uri(resultUri1String) }; ODataEntityReferenceLink resultUri2 = new ODataEntityReferenceLink { Url = new Uri(resultUri2String) }; ODataEntityReferenceLink resultUri3 = new ODataEntityReferenceLink { Url = new Uri(resultUri3String) }; var testCase = new ODataEntityReferenceLinks { Links = new ODataEntityReferenceLink[] { resultUri1, resultUri2, resultUri3 }, }; PayloadWriterTestDescriptor <ODataEntityReferenceLinks>[] testCases = new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>[] { new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>( this.Settings, testCase, (testConfiguration) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { // Top-level EntityReferenceLinks payload write requests are not allowed. ExpectedException2 = testConfiguration.IsRequest ? ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed") : null }) }; this.CombinatorialEngineProvider.RunCombinations( testCases, TestWriterUtils.InvalidSettingSelectors, this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent, (descriptor, selector, testConfiguration) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); if (testConfiguration.Format == ODataFormat.Json) { descriptor.Model = CreateModelWithNavProps(); var edmModel = descriptor.GetMetadataProvider(); } TestWriterUtils.WriteWithStreamErrors( descriptor, selector, testConfiguration, (messageWriter) => { messageWriter.WriteEntityReferenceLinks(testCase); }, this.Assert); }); }
public void RelativeUriTest() { var testCases = new[] { new { BaseUri = new Uri("http://odata.org/"), RelativeUri = new Uri("relative", UriKind.Relative), }, new { BaseUri = new Uri("http://odata.org/"), RelativeUri = new Uri("relative that needs escaping", UriKind.Relative), }, new { BaseUri = new Uri("http://odata.org/a/b/"), RelativeUri = new Uri("../../relative that needs escaping", UriKind.Relative), }, }; var testDescriptors = uriTestCases.SelectMany(uriTestCase => testCases.Select(testCase => { return(new { TestCase = uriTestCase, BaseUri = testCase.BaseUri, Descriptor = new PayloadWriterTestDescriptor <ODataItem>( this.Settings, uriTestCase.ItemFunc(testCase.RelativeUri), CreateUriTestCaseExpectedResultCallback(testCase.BaseUri, testCase.RelativeUri, uriTestCase)) }); })); //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight this.CombinatorialEngineProvider.RunCombinations( testDescriptors, this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => false), new bool[] { false, true }, (testDescriptor, testConfiguration, implementUrlResolver) => { if (testConfiguration.Format == ODataFormat.Json && testDescriptor.TestCase.JsonExtractor != null) { PayloadWriterTestDescriptor <ODataItem> payloadTestDescriptor = testDescriptor.Descriptor; if (implementUrlResolver) { payloadTestDescriptor = new PayloadWriterTestDescriptor <ODataItem>(payloadTestDescriptor); payloadTestDescriptor.UrlResolver = new TestUrlResolver(); } testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.BaseUri = testDescriptor.BaseUri; testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); TestWriterUtils.WriteAndVerifyODataPayload(payloadTestDescriptor, testConfiguration, this.Assert, this.Logger); } }); }
public void EntityReferenceLinkTest() { ODataEntityReferenceLink[] resultLinks = new ODataEntityReferenceLink[] { new ODataEntityReferenceLink { Url = new Uri("http://odata.org/linkresult") }, new ODataEntityReferenceLink { Url = new Uri("relative", UriKind.Relative) }, }; this.CombinatorialEngineProvider.RunCombinations( resultLinks, TestWriterUtils.ODataBehaviorKinds, this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent, (resultLink, behaviorKind, testConfiguration) => { bool expectMetadataNamespace = false; PayloadWriterTestDescriptor <ODataEntityReferenceLink> testDescriptor = new PayloadWriterTestDescriptor <ODataEntityReferenceLink>( this.Settings, resultLink, CreateExpectedCallback(resultLink, expectMetadataNamespace, "http://odata.org/test/$metadata#$ref")); // When writing JSON lite, always provide a model and a non-null nav prop. // The error cases when a model isn't provided or the nav prop is null are tested in JsonLightEntityReferenceLinkWriterTests if (testConfiguration.Format == ODataFormat.Json) { testDescriptor.Model = CreateModelWithNavProps(); var model = testDescriptor.GetMetadataProvider(); } testConfiguration = testConfiguration.CloneAndApplyBehavior(behaviorKind); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); TestWriterUtils.WriteAndVerifyTopLevelContent( testDescriptor, testConfiguration, (messageWriter) => messageWriter.WriteEntityReferenceLink(testDescriptor.PayloadItems.Single()), this.Assert, baselineLogger: this.Logger); }); }
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 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("\"", """) + "\" 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); }); }
public void EntityReferenceLinksPropertyAccessOrderTest() { //// NOTE: this tests is important as Astoria relies on this behavior. Astoria only provides a next link after all the entity reference //// links have been written so we must not access the next link before that point. ODataEntityReferenceLink entityReferenceLink1 = new ODataEntityReferenceLink { Url = new Uri("http://odata.org/linkresult1") }; ODataEntityReferenceLink entityReferenceLink2 = new ODataEntityReferenceLink { Url = new Uri("http://odata.org/linkresult2") }; ODataEntityReferenceLink entityReferenceLink3 = new ODataEntityReferenceLink { Url = new Uri("http://odata.org/linkresult3") }; Uri nextPageLink = new Uri("http://odata.org/nextpage"); Uri incorrectNextPageLink = new Uri("http://odata.org/incorrectnextpage"); long correctCountValue = 3; // the expected result instance ODataEntityReferenceLinks expectedResult = new ODataEntityReferenceLinks { Count = 3, Links = new ODataEntityReferenceLink[] { entityReferenceLink1, entityReferenceLink2, entityReferenceLink3 }, NextPageLink = nextPageLink }; PayloadWriterTestDescriptor.WriterTestExpectedResultCallback expectedResultCallback = this.CreateExpectedCallback(expectedResult, /*forceNextLinkAndCountAtEnd*/ true); this.CombinatorialEngineProvider.RunCombinations( this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => !tc.IsRequest), (testConfiguration) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); // The instance with the proper inline count set but an incorrect next link; as we enumerate the links themselves // we will invalidate the inline count and set the correct next link to guarantee the correct order of property accesses // NOTE: we need to create this new for each iteration since the checking enumerable can (intentionally) only be enumerated once. ODataEntityReferenceLinks testReferenceLink = new ODataEntityReferenceLinks { Count = correctCountValue, // In JSON lite, we will write the next link first if one is available. Otherwise, we'll write it at the end. NextPageLink = testConfiguration.Format == ODataFormat.Json ? null : incorrectNextPageLink }; testReferenceLink.Links = new CheckingEntityReferenceLinkEnumerable( testReferenceLink, correctCountValue, nextPageLink /* correct next link */, entityReferenceLink1, entityReferenceLink2, entityReferenceLink3); PayloadWriterTestDescriptor <ODataEntityReferenceLinks> testDescriptor = new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(this.Settings, testReferenceLink, expectedResultCallback); IEdmNavigationProperty navProp = null; IEdmEntitySet entitySet = null; // When writing JSON lite, always provide a model and a non-null nav prop. // The error cases when a model isn't provided or the nav prop is null are tested in JsonLightEntityReferenceLinkWriterTests if (testConfiguration.Format == ODataFormat.Json) { testDescriptor.Model = CreateModelWithNavProps(); var edmModel = testDescriptor.GetMetadataProvider(); navProp = GetCollectionNavProp(edmModel); entitySet = GetCollectionEntitySet(edmModel); } ODataEntityReferenceLinks entityReferenceLinks = testDescriptor.PayloadItems.Single(); TestWriterUtils.WriteAndVerifyTopLevelContent( testDescriptor, testConfiguration, (messageWriter) => messageWriter.WriteEntityReferenceLinks(entityReferenceLinks), this.Assert, baselineLogger: this.Logger); }); }
/// <summary> /// Returns all interesting payloads for a named stream. /// </summary> /// <param name="testDescriptor">Test descriptor which will end up writing a single entry with a single named stream. /// The entry is not going to be used, but the named stream from it will.</param> /// <returns>Enumeration of test descriptors which will include the original named stream in some interesting scenarios.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > NamedStreamPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { ODataResource tempEntry = testDescriptor.PayloadItems[0] as ODataResource; Debug.Assert(tempEntry != null, "A single entry payload is expected."); ODataProperty namedStreamProperty = tempEntry.Properties.FirstOrDefault(p => p != null && p.Value is ODataStreamReferenceValue); // Note - the named stream can be null - it is a valid test case !!!! var payloadCases = new WriterPayloadCase <ODataItem>[] { new WriterPayloadCase <ODataItem>() // Single named stream on an entry { GetPayloadItems = () => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.TypeName = "TestModel.EntityWithStreamProperty"; entry.Properties = new ODataProperty[] { namedStreamProperty }; return(new ODataItem[] { entry }); }, ModelBuilder = (model) => { model = model.Clone(); model.EntityType("EntityWithStreamProperty", "TestModel") .StreamProperty(namedStreamProperty.Name); return(model); }, AtomFragmentExtractor = (testConfiguration, result) => { return(TestAtomUtils.ExtractNamedStreamLinksFromEntry(result, namedStreamProperty.Name)); }, JsonLightFragmentExtractor = (testConfiguration, result) => { return(new JsonObject().AddProperties(result.Object().GetPropertyAnnotationsAndProperty(namedStreamProperty.Name))); }, }, new WriterPayloadCase <ODataItem>() // Single named stream on an entry with other properties before/after it { GetPayloadItems = () => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.TypeName = "TestModel.EntityWithStreamPropertyAndOtherProperties"; entry.Properties = new ODataProperty[] { new ODataProperty { Name = "Id", Value = 1 }, new ODataProperty { Name = "Name", Value = "Clemens" }, namedStreamProperty, new ODataProperty { Name = "Address", Value = new ODataComplexValue { TypeName = "TestModel.AddressType", Properties = new ODataProperty[] { new ODataProperty { Name = "Street", Value = "Am Euro Platz" }, new ODataProperty { Name = "City", Value = "Vienna" } } } } }; return(new ODataItem[] { entry }); }, ModelBuilder = (model) => { model = model.Clone(); var addressType = model.ComplexType("AddressType", "TestModel") .Property("Street", EdmPrimitiveTypeKind.String) .Property("City", EdmPrimitiveTypeKind.String); model.EntityType("EntityWithStreamPropertyAndOtherProperties", "TestModel") .KeyProperty("Id", (EdmTypeReference)EdmCoreModel.Instance.GetInt32(false)) .Property("Name", EdmPrimitiveTypeKind.String) .StreamProperty(namedStreamProperty.Name) .Property("Address", new EdmComplexTypeReference(addressType, false)); return(model); }, AtomFragmentExtractor = (testConfiguration, result) => { return(TestAtomUtils.ExtractNamedStreamLinksFromEntry(result, namedStreamProperty.Name)); }, JsonLightFragmentExtractor = (testConfiguration, result) => { return(new JsonObject().AddProperties(result.Object().GetPropertyAnnotationsAndProperty(namedStreamProperty.Name))); }, }, new WriterPayloadCase <ODataItem>() // Multiple named stream properties on an entry { GetPayloadItems = () => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.TypeName = "TestModel.EntityWithSeveralStreamProperties"; entry.Properties = new ODataProperty[] { new ODataProperty { Name = "Id", Value = 1 }, new ODataProperty { Name = "__Stream1", Value = new ODataStreamReferenceValue { ReadLink = new Uri("http://odata.org/stream1/readlink") } }, new ODataProperty { Name = "__Stream2", Value = new ODataStreamReferenceValue { EditLink = new Uri("http://odata.org/stream2/editlink") } }, namedStreamProperty, new ODataProperty { Name = "__Stream3", Value = new ODataStreamReferenceValue { ReadLink = new Uri("http://odata.org/stream3/readlink"), ContentType = "stream3:contenttype" } }, }; return(new ODataItem[] { entry }); }, ModelBuilder = (model) => { model = model.Clone(); model.EntityType("EntityWithSeveralStreamProperties", "TestModel") .KeyProperty("Id", (EdmTypeReference)EdmCoreModel.Instance.GetInt32(false)) .StreamProperty("__Stream1") .StreamProperty("__Stream2") .StreamProperty(namedStreamProperty.Name) .StreamProperty("__Stream3"); return(model); }, AtomFragmentExtractor = (testConfiguration, result) => { return(TestAtomUtils.ExtractNamedStreamLinksFromEntry(result, namedStreamProperty.Name)); }, JsonLightFragmentExtractor = (testConfiguration, result) => { return(new JsonObject().AddProperties(result.Object().GetPropertyAnnotationsAndProperty(namedStreamProperty.Name))); }, }, }; return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases)); }
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 => { ODataResource 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.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", "ODataResource.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", "ODataResource.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); }); }
public void ParameterWriterStateMachineErrorTests() { var testCases = new ParameterWriterStateMachineTestCase[] { // WriteStart can only be called once and it must be called before writing anything else. new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.WriteStart(); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteStart"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.WriteValue("p1", null); writer.WriteStart(); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteStart"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.CreateCollectionWriter("p1"); writer.WriteStart(); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteStart"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.WriteEnd(); writer.WriteStart(); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteStart"), }, // WriteValue and CreateCollectionWriter can only be called after WriteStart and before WriteEnd. And they cannot be called until the previously created sub-writer is completed. new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteValue("p1", null); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteParameter"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.CreateCollectionWriter("p1"); writer.WriteValue("p1", null); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteParameter"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.CreateCollectionWriter("p1"); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteParameter"), }, // WriteEnd can only be called after WriteStart and after the previously created sub-writer is completed. new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteEnd(); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteEnd"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.CreateCollectionWriter("p1"); writer.WriteEnd(); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteEnd"), }, // The writer is in error or completed state. No further writes can be performed on this writer. new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.WriteEnd(); writer.WriteValue("p1", null); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteInErrorOrCompletedState"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.WriteEnd(); writer.CreateCollectionWriter("p1"); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteInErrorOrCompletedState"), }, new ParameterWriterStateMachineTestCase { WriteActions = writer => { writer.WriteStart(); writer.WriteEnd(); writer.WriteEnd(); }, ExpectedException = ODataExpectedExceptions.ODataException("ODataParameterWriterCore_CannotWriteInErrorOrCompletedState"), }, // TODO: Add test cases to cause the writer enter error state then verify that no writes can be performed afterwards. }; var testConfigurations = this.WriterTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => tc.IsRequest); this.CombinatorialEngineProvider.RunCombinations(testConfigurations, testCases, (testConfiguration, testCase) => { PayloadWriterTestDescriptor.WriterTestExpectedResultCallback resultCallback = testConfig => new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = testCase.ExpectedException }; var testDescriptor = new PayloadWriterTestDescriptor <ODataParameters>(this.Settings, ObjectModelUtils.CreateDefaultParameter(), resultCallback); TestWriterUtils.WriteActionAndVerifyODataPayload <ODataParameters>( (messageWriter, writerDescriptor, feedWriter) => { ODataParameterWriter writer = messageWriter.CreateODataParameterWriter(null /*functionImport*/); testCase.WriteActions(writer); }, testDescriptor, testConfiguration, this.Assert, this.Logger); }); }
/// <summary> /// Returns all interesting payloads for a value. /// </summary> /// <param name="testDescriptor">Test descriptor which will end up writing a single entry with a single property. /// The entry is not going to be used, the property is not going to be used, but the property value from it will.</param> /// <returns>Enumeration of test descriptors which will include the original value in some interesting scenarios.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > ValuePayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { ODataResource tempEntry = testDescriptor.PayloadItems[0] as ODataResource; Debug.Assert(tempEntry != null, "A single entry payload is expected."); ODataProperty property = tempEntry.Properties.First(); Debug.Assert(property != null, "A single property is expected."); object propertyValue = property.Value; var payloadCases = new WriterPayloadCase <ODataItem>[] { new WriterPayloadCase <ODataItem>() // Value of a property { GetPayloadItems = () => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.Properties = new ODataProperty[] { new ODataProperty() { Name = "TestProperty", Value = propertyValue } }; return(new ODataItem[] { entry }); }, AtomFragmentExtractor = (testConfiguration, result) => { return(TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + property.Name)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, new WriterPayloadCase <ODataItem>() // Value as item in a collection { ShouldSkip = testConfiguration => propertyValue is ODataCollectionValue, GetPayloadItems = () => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.Properties = new ODataProperty[] { new ODataProperty() { Name = "TestProperty", Value = new ODataCollectionValue() { Items = new object[] { propertyValue } } } }; return(new ODataItem[] { entry }); }, AtomFragmentExtractor = (testConfiguration, result) => { return(TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + property.Name)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // TODO: Add other interesting payloads for property values }; // Combine with property payloads to get interesting places where the property itself is used. return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases).PayloadCases(PropertyPayloads)); }
/// <summary> /// Returns the <paramref name="testDescriptor"/> but modified to work as a top-level value payload. /// </summary> /// <param name="testDescriptor">The test descriptor to process.</param> /// <returns>The <paramref name="testDescriptor"/> suitable as top-level value payload.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > TopLevelValuePayload(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { var payloadCases = new WriterPayloadCase <ODataItem>[] { // Top level entry new WriterPayloadCase <ODataItem>() { JsonLightFragmentExtractor = JsonUtils.UnwrapTopLevelValue } }; return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases)); }
public void BaseUriErrorTest() { Uri baseUri = new Uri("http://odata.org"); Uri testUri = new Uri("http://odata.org/relative"); IEnumerable <Func <Uri, BaseUriErrorTestCase> > testCaseFuncs = new Func <Uri, BaseUriErrorTestCase>[] { relativeUri => new BaseUriErrorTestCase { // next page link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed(); feed.NextPageLink = relativeUri; return(new [] { feed }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // entry read link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.ReadLink = relativeUri; return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // entry edit link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.EditLink = relativeUri; return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // media resource (default stream) read link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataStreamReferenceValue mediaResource = new ODataStreamReferenceValue(); mediaResource.ContentType = "image/jpg"; mediaResource.ReadLink = relativeUri; ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.MediaResource = mediaResource; return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // media resource (default stream) edit link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataStreamReferenceValue mediaResource = new ODataStreamReferenceValue(); mediaResource.ContentType = "image/jpg"; // required mediaResource.ReadLink = testUri; // required mediaResource.EditLink = relativeUri; ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.MediaResource = mediaResource; return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // link Url ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataNestedResourceInfo link = ObjectModelUtils.CreateDefaultCollectionLink(); link.Url = relativeUri; ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); return(new ODataItem[] { entry, link }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // association link Url ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataNestedResourceInfo link = ObjectModelUtils.CreateDefaultSingletonLink(); link.AssociationLinkUrl = relativeUri; ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); return(new ODataItem[] { entry, link }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // named stream read link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataStreamReferenceValue namedStream = new ODataStreamReferenceValue() { ContentType = "image/jpg", ReadLink = relativeUri, }; ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); ODataProperty property = new ODataProperty() { Name = "NamedStream", Value = namedStream }; entry.Properties = new[] { property }; return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // named stream edit link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataStreamReferenceValue namedStream = new ODataStreamReferenceValue() { ContentType = "image/jpg", ReadLink = testUri, EditLink = relativeUri }; ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); ODataProperty property = new ODataProperty() { Name = "NamedStream", Value = namedStream }; entry.Properties = new[] { property }; return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: feed generator Uri ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed(); return(new [] { feed }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: feed logo ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed(); return(new [] { feed }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: feed icon ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed(); return(new [] { feed }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: feed author ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed(); return(new [] { feed }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: feed contributor ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed(); return(new [] { feed }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: feed link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed(); return(new [] { feed }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: entry author ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: entry contributor ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, relativeUri => new BaseUriErrorTestCase { // Atom metadata: entry link ItemFunc = new Func <IEnumerable <ODataItem> >(() => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); return(new [] { entry }); }), Formats = new [] { ODataFormat.Json } }, }; // ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight Uri testRelativeUri = baseUri.MakeRelativeUri(testUri); Uri invalidRelativeUri = new Uri("../invalid/relative/uri", UriKind.Relative); this.CombinatorialEngineProvider.RunCombinations( testCaseFuncs, this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => false), new Uri[] { testRelativeUri, invalidRelativeUri }, new bool[] { false, true }, (testCaseFunc, testConfiguration, uri, implementUrlResolver) => { var testCase = testCaseFunc(uri); var testDescriptor = new { Descriptor = new PayloadWriterTestDescriptor <ODataItem>( this.Settings, testCase.ItemFunc(), testConfig => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = ODataExpectedExceptions.ODataException("ODataWriter_RelativeUriUsedWithoutBaseUriSpecified", uri.OriginalString) }), Formats = testCase.Formats }; if (testDescriptor.Formats.Contains(testConfiguration.Format)) { PayloadWriterTestDescriptor <ODataItem> payloadTestDescriptor = testDescriptor.Descriptor; TestUrlResolver urlResolver = null; if (implementUrlResolver) { payloadTestDescriptor = new PayloadWriterTestDescriptor <ODataItem>(payloadTestDescriptor); urlResolver = new TestUrlResolver(); payloadTestDescriptor.UrlResolver = urlResolver; } testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); TestWriterUtils.WriteAndVerifyODataPayload(payloadTestDescriptor, testConfiguration, this.Assert, this.Logger); if (implementUrlResolver) { this.Assert.AreEqual(1, urlResolver.Calls.Where(call => call.Value.OriginalString == uri.OriginalString).Count(), "The resolver should be called exactly once for each URL."); } } }); }
/// <summary> /// Returns all interesting payloads for an entry. /// </summary> /// <param name="testDescriptor">The test descriptor which will end up writing a single entry.</param> /// <returns>Enumeration of test descriptors which will include the original entry in some interesting scenarios.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > EntryPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { Debug.Assert(testDescriptor.PayloadItems[0] is ODataResource, "The payload does not specify an entry."); var payloadCases = new WriterPayloadCase <ODataItem>[] { // Feed with a single entry new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultFeed() }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName).First()); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // Feed with three (identical) entries, picking the second one new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultFeed() } .Concat(testDescriptor.PayloadItems) .Concat(LinqExtensions.FromSingle((ODataItem)null)) .Concat(testDescriptor.PayloadItems) .Concat(LinqExtensions.FromSingle((ODataItem)null)) .Concat(testDescriptor.PayloadItems) .Concat(LinqExtensions.FromSingle((ODataItem)null)), AtomFragmentExtractor = (testConfiguration, result) => { var entries = result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName); Debug.Assert(entries.Count() == 3, "Expected three entries in the feed."); return(entries.ElementAt(2)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // Top-level entry with an expanded link containing a single entry new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultSingletonLink(), }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // Top-level entry with an expanded link containing a feed with a single entry new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), ObjectModelUtils.CreateDefaultFeed() }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // Top-level entry with an expanded link containing a feed with three entries; picking the second one new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), ObjectModelUtils.CreateDefaultFeed() } .Concat(testDescriptor.PayloadItems) .Concat(LinqExtensions.FromSingle((ODataItem)null)) .Concat(testDescriptor.PayloadItems) .Concat(LinqExtensions.FromSingle((ODataItem)null)) .Concat(testDescriptor.PayloadItems) .Concat(LinqExtensions.FromSingle((ODataItem)null)), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName) .Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName) .ElementAt(2)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // Top-level entry with an expanded link containing a feed with a single entry; // that entry has another expanded link containing a feed with the payload entry new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), ObjectModelUtils.CreateDefaultFeed(), ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), ObjectModelUtils.CreateDefaultFeed(), }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName) .Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, }; return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases)); }
/// <summary> /// Applies the payload case to a test descriptor returning a new test descriptor. /// </summary> /// <param name="testDescriptor">The test descriptor to apply the case to.</param> /// <returns>The new test descriptor.</returns> internal PayloadWriterTestDescriptor <TOut> ApplyToTestDescriptor(PayloadWriterTestDescriptor <TIn> testDescriptor) { IEnumerable <TOut> payloadItems = null; if (this.GetPayloadItems != null) { payloadItems = this.GetPayloadItems(); } else { // for the test descriptor to specify payload items TIn and TOut have to be compatible! Type inputType = typeof(TIn); Type outputType = typeof(TOut); if (inputType != outputType && !outputType.IsAssignableFrom(inputType)) { throw new NotSupportedException( "The test descriptor can only specify payload items when they are compatible with the expected output type. " + inputType.FullName + " is not compatible with " + outputType.FullName + "."); } payloadItems = testDescriptor.PayloadItems.Cast <TOut>(); } EdmModel model = (EdmModel)testDescriptor.Model; IEdmElement payloadElementModelContainer = testDescriptor.PayloadEdmElementContainer; IEdmElement payloadElementType = testDescriptor.PayloadEdmElementType; if (model != null && this.ModelBuilder != null) { model = this.ModelBuilder(model); } return(new PayloadWriterTestDescriptor <TOut>( testDescriptor.TestDescriptorSettings, payloadItems, (testConfiguration) => { if (this.ShouldSkip != null && this.ShouldSkip(testConfiguration)) { return null; } WriterTestExpectedResults expectedResults = testDescriptor.ExpectedResultCallback(testConfiguration); AtomWriterTestExpectedResults atomResults = expectedResults as AtomWriterTestExpectedResults; if (atomResults != null) { return new AtomWriterTestExpectedResults(atomResults) { FragmentExtractor = this.AtomFragmentExtractor == null ? atomResults.FragmentExtractor : (result) => atomResults.FragmentExtractor(this.AtomFragmentExtractor(testConfiguration, result)), }; } JsonWriterTestExpectedResults jsonResults = expectedResults as JsonWriterTestExpectedResults; if (jsonResults != null) { return new JsonWriterTestExpectedResults(jsonResults) { FragmentExtractor = this.JsonLightFragmentExtractor == null ? jsonResults.FragmentExtractor : (result) => jsonResults.FragmentExtractor(this.JsonLightFragmentExtractor(testConfiguration, result)), }; } return expectedResults; }) { SkipTestConfiguration = testDescriptor.SkipTestConfiguration, IsGeneratedPayload = !this.NotGenerated, Model = model, PayloadEdmElementContainer = payloadElementModelContainer, PayloadEdmElementType = payloadElementType, }); }
/// <summary> /// Applies payload cases to a test descriptor. /// </summary> /// <param name="testDescriptor">The test descriptor to use.</param> /// <param name="payloadCases">The payload cases to use.</param> /// <returns>Enumeration of test descriptors which are results of applying all the payload cases to the specified test descriptor.</returns> private static IEnumerable <PayloadWriterTestDescriptor <TOut> > ApplyPayloadCases <TIn, TOut>(PayloadWriterTestDescriptor <TIn> testDescriptor, IEnumerable <WriterPayloadCase <TIn, TOut> > payloadCases) { return(payloadCases.Select(payloadCase => payloadCase.ApplyToTestDescriptor(testDescriptor))); }
/// <summary> /// Returns all interesting payloads for a navigation link. /// </summary> /// <param name="testDescriptor">Test descriptor which will end up writing a single navigation link.</param> /// <returns>Enumeration of test descriptors which will include the original navigation link in some interesting scenarios.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > NavigationLinkPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { ODataNestedResourceInfo navigationLink = testDescriptor.PayloadItems[0] as ODataNestedResourceInfo; Debug.Assert(navigationLink != null, "Link payload expected."); var payloadCases = new WriterPayloadCase <ODataItem>[] { new WriterPayloadCase <ODataItem>() // Single link on top-level entry { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry() }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .Where(linkElement => linkElement.Attribute(TestAtomConstants.AtomLinkRelationAttributeName).Value.StartsWith(TestAtomConstants.ODataNavigationPropertiesRelatedLinkRelationPrefix)) .First()); }, }, // TODO: Add other interesting payloads for links - in expanded entry, in expanded feed }; return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases)); }
/// <summary> /// Returns all interesting payloads for a navigation link itself. That is the ODataNestedResourceInfo without any subsequent events. /// </summary> /// <param name="testDescriptor">Test descriptor which will end up writing a single navigation link.</param> /// <returns>Enumeration of test descriptors which will include the original navigation link in some interesting scenarios.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > NavigationLinkOnlyPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { ODataNestedResourceInfo navigationLink = testDescriptor.PayloadItems[0] as ODataNestedResourceInfo; Debug.Assert(navigationLink != null, "Navigation link payload expected."); Debug.Assert(navigationLink.IsCollection.HasValue, "ODataNestedResourceInfo.IsCollection required."); var payloadCases = new WriterPayloadCase <ODataItem>[] { new WriterPayloadCase <ODataItem>() // Just the link as non-expanded { GetPayloadItems = () => new ODataItem[] { navigationLink } }, new WriterPayloadCase <ODataItem>() // The link with expanded entry { GetPayloadItems = () => { if (navigationLink.IsCollection.Value) { return(new ODataItem[] { navigationLink, ObjectModelUtils.CreateDefaultFeed() }); } else { return(new ODataItem[] { navigationLink, ObjectModelUtils.CreateDefaultEntry() }); } } } }; // Apply the cases here and then wrap the link in some entry/feed cases return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases).PayloadCases(NavigationLinkPayloads)); }
public void EntityReferenceLinkValidationTest() { var testCases = new[] { new { InvalidateEntityReferenceLink = new Action <ODataEntityReferenceLink>(entityReferenceLink => entityReferenceLink.Url = null), ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_EntityReferenceLinkUrlMustNotBeNull"), }, }; var testDescriptors = testCases.SelectMany(testCase => { ODataEntityReferenceLink entityReferenceLink = ObjectModelUtils.CreateDefaultEntityReferenceLink(); testCase.InvalidateEntityReferenceLink(entityReferenceLink); ODataEntityReferenceLinks entityReferenceLinks = ObjectModelUtils.CreateDefaultEntityReferenceLinks(); testCase.InvalidateEntityReferenceLink(entityReferenceLinks.Links.First()); return(new PayloadWriterTestDescriptor[] { // Top level entity reference link new PayloadWriterTestDescriptor <ODataEntityReferenceLink>( this.Settings, entityReferenceLink, testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = testCase.ExpectedException }), // Entity reference link in entity reference links new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>( this.Settings, entityReferenceLinks, testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { // Top-level EntityReferenceLinks payload write requests are not allowed. ExpectedException2 = testConfiguration.IsRequest ? ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed") : testCase.ExpectedException }), new PayloadWriterTestDescriptor <ODataItem>( this.Settings, new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultSingletonLink(), entityReferenceLink, null, null }, testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = testConfiguration.IsRequest ? testCase.ExpectedException : ODataExpectedExceptions.ODataException("ODataWriterCore_EntityReferenceLinkInResponse") }), }); }); this.CombinatorialEngineProvider.RunCombinations( testDescriptors, this.WriterTestConfigurationProvider.AtomFormatConfigurations, (testDescriptor, testConfiguration) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); PayloadWriterTestDescriptor <ODataEntityReferenceLink> entityReferenceLinkTestDescriptor = testDescriptor as PayloadWriterTestDescriptor <ODataEntityReferenceLink>; if (entityReferenceLinkTestDescriptor != null) { TestWriterUtils.WriteAndVerifyTopLevelContent( entityReferenceLinkTestDescriptor, testConfiguration, (messageWriter) => messageWriter.WriteEntityReferenceLink(entityReferenceLinkTestDescriptor.PayloadItems.Single()), this.Assert, baselineLogger: this.Logger); return; } PayloadWriterTestDescriptor <ODataEntityReferenceLinks> entityReferenceLinksTestDescriptor = testDescriptor as PayloadWriterTestDescriptor <ODataEntityReferenceLinks>; if (entityReferenceLinksTestDescriptor != null) { TestWriterUtils.WriteAndVerifyTopLevelContent( entityReferenceLinksTestDescriptor, testConfiguration, (messageWriter) => messageWriter.WriteEntityReferenceLinks(entityReferenceLinksTestDescriptor.PayloadItems.Single()), this.Assert, baselineLogger: this.Logger); return; } TestWriterUtils.WriteAndVerifyODataPayload((PayloadWriterTestDescriptor <ODataItem>)testDescriptor, testConfiguration, this.Assert, this.Logger); }); }
public void AbsoluteUriTest() { Uri[] baseUris = new Uri[] { null, // Standard new Uri("http://odata.org/"), new Uri("http://second.odata.org/"), // Reserved Characters new Uri("http://odata.org/MyC%2B%2BService.svc/"), // + new Uri("http://odata.org/My%24Service.svc/"), // $ new Uri("http://odata.org/My%26Service.svc/"), // & new Uri("http://odata.org/My%2FService.svc/"), // / new Uri("http://odata.org/My%3DService.svc/"), // = new Uri("http://odata.org/My%3FService.svc/"), // ? new Uri("http://odata.org/My%2CService.svc/"), // , new Uri("http://odata.org/My%3AService.svc/"), // : new Uri("http://odata.org/My%40Service.svc/"), // @ //Unsafe Characters new Uri("http://odata.org/My%20Service.svc/"), // space new Uri("http://odata.org/My%22Service.svc/"), // " new Uri("http://odata.org/My%23Service.svc/"), // # new Uri("http://odata.org/My%25Service.svc/"), // % new Uri("http://odata.org/My%5CService.svc/"), // \ new Uri("http://odata.org/My%7EService.svc/"), // ~ new Uri("http://odata.org/My%5EService.svc/"), // ^ new Uri("http://odata.org/My%5BService.svc/"), // [ new Uri("http://odata.org/My%5DService.svc/"), // ] new Uri("http://odata.org/My%60Service.svc/"), // ` new Uri("http://odata.org/My%7CService.svc/"), // | new Uri("http://odata.org/My%7BService.svc/"), // { new Uri("http://odata.org/My%7DService.svc/"), // } // Others new Uri("http://odata.org:80/MyService.svc/"), new Uri("http://odata.org/My_Service.svc/"), new Uri("http://odata.org/My-Service.svc/"), new Uri("http://odata.org/My31572Service.svc/"), }; Uri[] testUris = new Uri[] { new Uri("http://odata.org/testuri"), new Uri("http://odata.org/testuri?$filter=3.14E%2B%20ne%20null"), new Uri("http://odata.org/testuri?$filter='foo%20%26%20'%20ne%20null"), new Uri("http://odata.org/testuri?$filter=not%20endswith(Name,'%2B')"), new Uri("http://odata.org/testuri?$filter=geo.distance(Point,%20geometry'SRID=0;Point(6.28E%2B3%20-2.1e%2B4)')%20eq%20null"), }; var testDescriptors = uriTestCases .SelectMany(testCase => testUris .SelectMany(testUri => baseUris .Select(baseUri => { return(new { TestCase = testCase, BaseUri = baseUri, Descriptor = new PayloadWriterTestDescriptor <ODataItem>( this.Settings, testCase.ItemFunc(testUri), CreateUriTestCaseExpectedResultCallback(baseUri, testUri, testCase)) }); }))); // ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight this.CombinatorialEngineProvider.RunCombinations( testDescriptors, this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => false), new bool[] { false, true }, (testDescriptor, testConfiguration, implementUrlResolver) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); if (testConfiguration.Format == ODataFormat.Json && testDescriptor.TestCase.JsonExtractor != null) { PayloadWriterTestDescriptor <ODataItem> payloadTestDescriptor = testDescriptor.Descriptor; if (implementUrlResolver) { payloadTestDescriptor = new PayloadWriterTestDescriptor <ODataItem>(payloadTestDescriptor); payloadTestDescriptor.UrlResolver = new TestUrlResolver(); } TestWriterUtils.WriteAndVerifyODataPayload(payloadTestDescriptor, testConfiguration, this.Assert, this.Logger); } }); }
/// <summary> /// Returns all interesting payloads for a feed. /// </summary> /// <param name="testDescriptor">The test descriptor which will end up writing a single feed.</param> /// <returns>Enumeration of test descriptors which will include the original feed in some interesting scenarios.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > FeedPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { Debug.Assert(testDescriptor.PayloadItems[0] is ODataResourceSet, "The payload does not specify a feed."); var payloadCases = new WriterPayloadCase <ODataItem>[] { // Top-level feed with an entry that has an expanded link containing the feed new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultFeed(), ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName) .Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // Top-level entry with an expanded link containing the feed new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // Top-level entry with an expanded link containing a feed with a single entry; // that entry has another expanded link containing the payload feed new WriterPayloadCase <ODataItem>() { GetPayloadItems = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), ObjectModelUtils.CreateDefaultFeed(), ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultCollectionLink(), }.Concat(testDescriptor.PayloadItems), AtomFragmentExtractor = (testConfiguration, result) => { return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName) .Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName) .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null) .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, }; return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases)); }
/// <summary> /// Returns all interesting payloads for a property. /// </summary> /// <param name="testDescriptor">Test descriptor which will end up writing a single entry with a single property. /// The entry is not going to be used, but the property from it will.</param> /// <returns>Enumeration of test descriptors which will include the original property in some interesting scenarios.</returns> public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > PropertyPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor) { ODataResource tempEntry = testDescriptor.PayloadItems[0] as ODataResource; Debug.Assert(tempEntry != null, "A single entry payload is expected."); ODataProperty property = tempEntry.Properties.First(); // Note - the property can be null - it is a valid test case !!!! var payloadCases = new WriterPayloadCase <ODataItem>[] { new WriterPayloadCase <ODataItem>() // Single property on an entry { GetPayloadItems = () => { ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); entry.Properties = new ODataProperty[] { property }; return(new ODataItem[] { entry }); }, AtomFragmentExtractor = (testConfiguration, result) => { return(TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + property.Name)); }, //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight }, // TODO: Add other interesting payloads for properties - more properties in an entry, inside a complex property, inside a collection of complex and so on }; return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases)); }
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 FeedUserExceptionTests() { IEdmModel edmModel = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel(); ODataFeed cityFeed = ObjectModelUtils.CreateDefaultFeed(); ODataEntry cityEntry = ObjectModelUtils.CreateDefaultEntry("TestModel.CityType"); ODataNavigationLink cityHallCollectionLink = ObjectModelUtils.CreateDefaultCollectionLink("CityHall"); ODataNavigationLink policeStationSingletonLink = ObjectModelUtils.CreateDefaultSingletonLink("PoliceStation"); ODataFeed officeFeed = ObjectModelUtils.CreateDefaultFeed(); ODataEntry officeEntry = ObjectModelUtils.CreateDefaultEntry("TestModel.OfficeType"); var container = edmModel.FindEntityContainer("DefaultContainer"); var citySet = container.FindEntitySet("Cities") as EdmEntitySet; var cityType = edmModel.FindType("TestModel.CityType") as EdmEntityType; ODataItem[] writerPayload = new ODataItem[] { cityFeed, cityEntry, null, cityEntry, cityHallCollectionLink, officeFeed, officeEntry, null, null, null, null, cityEntry, null, cityEntry, policeStationSingletonLink, officeEntry, null, null, null, }; IEnumerable <PayloadWriterTestDescriptor <ODataItem> > testDescriptors = new PayloadWriterTestDescriptor <ODataItem>[] { new PayloadWriterTestDescriptor <ODataItem>( this.Settings, writerPayload, tc => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException = new Exception("User code triggered an exception."), } ) { Model = edmModel, PayloadEdmElementContainer = citySet, PayloadEdmElementType = cityType, } }; this.CombinatorialEngineProvider.RunCombinations( testDescriptors.PayloadCases(WriterPayloads.FeedPayloads), this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent, (testDescriptor, testConfiguration) => { if (testDescriptor.IsGeneratedPayload && (testConfiguration.Format == ODataFormat.Json || testDescriptor.Model != null)) { return; } foreach (int throwUserExceptionAt in Enumerable.Range(0, testDescriptor.PayloadItems.Count + 1)) { var configuredTestDescriptor = new PayloadWriterTestDescriptor <ODataItem>(this.Settings, testDescriptor.PayloadItems, testDescriptor.ExpectedResultCallback) { Model = testDescriptor.Model, PayloadEdmElementContainer = testDescriptor.PayloadEdmElementContainer, PayloadEdmElementType = testDescriptor.PayloadEdmElementType, ThrowUserExceptionAt = throwUserExceptionAt, }; TestWriterUtils.WriteAndVerifyODataEdmPayload(configuredTestDescriptor, testConfiguration, this.Assert, this.Logger); } }); }