public void RequestUriSpecialNumbersTest() { TypedCustomDataContext <AllTypes> .ClearHandlers(); TypedCustomDataContext <AllTypes> .ClearValues(); using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(TypedCustomDataContext <AllTypes>); string[] uris = new string[] { "/Values(1)", "/Values(-1)", }; foreach (string uri in uris) { Trace.WriteLine("Requesting URI " + uri); request.RequestUriString = uri; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, true); TestUtil.AssertExceptionStatusCode( exception, 404, "Correctly parsed (but missing) entites should return 404."); } } }
public void RequestUriProcessorDollarValueMustComeAfterMleError() { string[] requestValues = new string[] { // $value after a non-MLE entity should fail. "/Customers(1)/$value", }; foreach (string responseFormat in UnitTestsUtil.ResponseFormats) { using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess)) { request.Accept = responseFormat; request.DataServiceType = typeof(CustomDataContext); foreach (string requestValue in requestValues) { request.RequestUriString = requestValue; Exception e = TestUtil.RunCatching(request.SendRequest); Assert.IsNotNull(e); Assert.AreEqual(400, request.ResponseStatusCode); Assert.AreEqual(typeof(DataServiceException), e.InnerException.GetType()); Assert.AreEqual("The URI 'http://host/Customers(1)/$value' is not valid. The segment before '$value' must be a Media Link Entry or a primitive property.", e.InnerException.Message); } } } }
public void RequestUriCaseInsensitive() { // Repro: Path to the .svc file shoud not be case sensitive. WebServerLocation[] locations = new WebServerLocation[] { WebServerLocation.InProcessWcf, WebServerLocation.Local }; CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("location", locations)); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { WebServerLocation location = (WebServerLocation)values["location"]; using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; request.FullRequestUriString = request.FullRequestUriString .Replace(".svc", ".SvC") .Replace("Test", "test"); request.SendRequest(); string response = request.GetResponseStreamAsText(); Trace.WriteLine(response); } }); }
public void RequestUriProcessorNullNavigationTest() { string[] uris = new string[] { "/Customer(100)/BestFriend/Name", "/Customer(100)/Orders", "/Customer(100)/Orders(1)", "/Customer(100)/Orders(1)/DollarAmount", // "/Customer(100)/BestFriend/BestFriend/Name", }; using (CustomDataContext.CreateChangeScope()) using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(CustomDataContext); var c = new CustomDataContext(); c.InternalCustomersList.Add(new Customer() { ID = 100, BestFriend = null, Orders = null }); c.SaveChanges(); CombinatorialEngine engine = CombinatorialEngine.FromDimensions(new Dimension("URI", uris)); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { string uri = (string)values["URI"]; request.RequestUriString = "/Customer(100)/BestFriend/Name"; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionStatusCode(exception, 404, "404 expected for " + uri); }); } }
public void RequestUriProcessorNotFoundErrorTest() { string[] requestValues = new string[] { // Traversing a property. "/Customers(1)/Name/More", // Non-existent property "/Customers(1)/SomeName", // Traversing a $value. "/Customers(1)/Name/$value/More", "/Customers%n0", }; foreach (string responseFormat in UnitTestsUtil.ResponseFormats) { using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess)) { request.Accept = responseFormat; request.DataServiceType = typeof(CustomDataContext); foreach (string requestValue in requestValues) { request.RequestUriString = requestValue; VerifyResourceNotFoundError(request); } } } }
public ResourceVerification(TestWebRequest request, DSPResourceSerializerFormat payloadFormat, int id, GeographyPropertyValues propertyValues) { this.Request = request; this.Id = id; this.PropertyValues = propertyValues; this.PayloadFormat = payloadFormat; }
public void RequestUriProcessorEmptySegments() { // This test reproes: extra / are not ignored, http://host/service//$metadata string[] uris = new string[] { "/", "/$metadata", "//$metadata", "//", "///", "//Values//", }; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(TypedCustomDataContext <TypedEntity <int, string> >); foreach (string uri in uris) { Trace.WriteLine("Requesting " + uri); request.RequestUriString = uri; request.Accept = "application/atom+xml,application/xml"; request.SendRequest(); var doc = request.GetResponseStreamAsXmlDocument(); if (uri == "/$metadata") { TestUtil.AssertSelectNodes(doc, "/edmx:Edmx/edmx:DataServices[0 = count(@adsm:DataServiceVersion)]"); } } } }
[Ignore] // Remove Atom // [TestMethod, TestCategory("Partition1")] public void CanOverrideAcceptHeaderToBatchRequestWithQueryItem() { StringBuilder batchQueryOperation = new StringBuilder(); batchQueryOperation.AppendLine("GET Customers(1)/Address?Override-Accept=" + UnitTestsUtil.JsonLightMimeType + " HTTP/1.1"); batchQueryOperation.AppendLine("Host: host"); batchQueryOperation.AppendLine("Accept: " + UnitTestsUtil.MimeApplicationXml); var test = new SimpleBatchTestCase { RequestPayload = new BatchInfo(new BatchQuery(new Operation(batchQueryOperation.ToString()))), ResponseStatusCode = 202, ResponseETag = default(string), ResponseVersion = V4, RequestDataServiceVersion = V4, RequestMaxDataServiceVersion = V4, }; foreach (var serviceType in Services) { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.HttpMethod = "POST"; request.RequestUriString = "/$batch?Override-Batch-Accept=" + UnitTestsUtil.JsonLightMimeType; request.DataServiceType = serviceType; request.Accept = UnitTestsUtil.MimeMultipartMixed; request.RequestVersion = test.RequestDataServiceVersion.ToString(); request.RequestMaxVersion = test.RequestMaxDataServiceVersion.ToString(); request.ForceVerboseErrors = true; if (test.RequestPayload == null) { request.RequestContentLength = 0; } else { const string boundary = "batch-set"; request.RequestContentType = String.Format("{0}; boundary={1}", UnitTestsUtil.MimeMultipartMixed, boundary); request.SetRequestStreamAsText(BatchRequestWritingUtils.GetBatchText(test.RequestPayload, boundary)); } TestUtil.RunCatching(request.SendRequest); // expect 202 as $batch request does not honor query string Accept header Assert.AreEqual(test.ResponseStatusCode, request.ResponseStatusCode); // The following response header is written in ProcessingRequest/OnStartProcessingRequest Assert.AreEqual(UnitTestsUtil.JsonLightMimeType, request.ResponseHeaders["Override-Batch-Accept"]); string response = request.GetResponseStreamAsText(); if (serviceType == typeof(ModifyHeaderOnStartProcessingRequestTestService)) { Assert.IsTrue(response.Contains("Content-Type: application/json;odata.metadata=minimal;")); } else { // ProcessingRequest which sets the Aceept header is not called for inner requests Assert.IsTrue(response.Contains("Content-Type: application/xml;charset=utf-8")); } } } }
public void ParseResponseFromRequest(TestWebRequest request, bool matchToExisting) { using (var contentStream = request.GetResponseStream()) { this.ParseBatchContent(contentStream, request.ResponseContentType, true, matchToExisting); } }
[Ignore] // Remove Atom // [TestMethod] public void FilterNavigationWithAnyAll_TypeCasts() { using (OpenWebDataServiceHelper.AcceptAnyAllRequests.Restore()) { OpenWebDataServiceHelper.AcceptAnyAllRequests.Value = true; using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); request.StartService(); string[] filters = new string[] { "Orders/all(o: o/Customer/AstoriaUnitTests.Stubs.CustomerWithBirthday/Birthday gt 1911-04-22T15:20:45.907Z)", "Orders/all(o: isof(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday') and cast(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday')/Birthday gt 1911-04-22T15:20:45.907Z)", "Orders/all(o: isof(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday') and cast(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday')/Orders/any())", "isof(Orders/any(),'Edm.Boolean') and ID eq 1", "isof(Orders/any(o: $it/ID eq 2),'Edm.Boolean') and isof(Orders/all(o: $it/ID eq 2),'Edm.Boolean') and ID eq 1", }; foreach (var filter in filters) { request.RequestUriString = "/Customers?$format=atom&$filter=" + filter; Exception e = TestUtil.RunCatching(request.SendRequest); Assert.IsNull(e, "Not expecting exception."); var xdoc = request.GetResponseStreamAsXDocument(); XElement customerWithBirthday = xdoc.Root.Elements(XName.Get("{http://www.w3.org/2005/Atom}entry")).Single(); XElement typeName = customerWithBirthday.Elements(XName.Get("{http://www.w3.org/2005/Atom}category")).Single(); Assert.IsTrue(typeName.Attribute("term").Value.EndsWith("CustomerWithBirthday"), "typeName.Attribute(\"term\").Value.EndsWith(\"CustomerWithBirthday\")"); } } } }
private void GetResponse(string uri, string responseFormat, Type contextType, string[] xPathsToVerify, KeyValuePair <string, string>[] headerValues, string httpMethodName, string requestPayload) { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = contextType; request.RequestUriString = uri; request.Accept = responseFormat; request.HttpMethod = httpMethodName; UnitTestsUtil.SetHeaderValues(request, headerValues); if (requestPayload != null) { request.RequestContentType = responseFormat; request.RequestStream = new MemoryStream(); StreamWriter writer = new StreamWriter(request.RequestStream); writer.Write(requestPayload); writer.Flush(); } request.SendRequest(); Stream responseStream = request.GetResponseStream(); if (xPathsToVerify != null) { UnitTestsUtil.VerifyXPaths(responseStream, responseFormat, xPathsToVerify); } } }
public void HttpContextServiceHostTunnelingTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("Method", new string[] { "GET", "POST", "PUT", "DELETE" }), new Dimension("XMethod", new string[] { "GET", "POST", "PATCH", "DELETE", "DELETE,DELETE" })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { using (TestWebRequest request = TestWebRequest.CreateForLocal()) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Orders(100)"; string method = (string)values["Method"]; string xmethod = (string)values["XMethod"]; request.HttpMethod = method; if (xmethod == "PATCH") { request.RequestContentType = UnitTestsUtil.JsonLightMimeType; request.SetRequestStreamAsText( "{ @odata.type:\"#AstoriaUnitTests.Stubs.Order\"" + " , DollarAmount: 10 }"); } request.RequestHeaders["X-HTTP-Method"] = xmethod; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, method != "POST", xmethod != "PATCH"); } }); }
public void CallbackSuccessQueryKeywordTest() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CallbackQueryOptionTestService); request.StartService(); request.RequestUriString = "/ReturnNullServiceOperation?$callback=foo"; request.SendRequest(); Assert.AreEqual(204, request.ResponseStatusCode); request.RequestUriString = "/Customers(1)/ID/$value?$callback=foo"; request.SendRequest(); Assert.AreEqual(200, request.ResponseStatusCode); Assert.AreEqual("foo(1)", request.GetResponseStreamAsText()); Assert.AreEqual("text/javascript;charset=utf-8", request.ResponseHeaders["content-type"]); request.RequestUriString = "/Customers/$count?$callback=foo"; request.SendRequest(); Assert.AreEqual(200, request.ResponseStatusCode); var actualText = request.GetResponseStreamAsText(); Assert.IsTrue(actualText.StartsWith("foo(")); Assert.IsTrue(actualText.EndsWith(")")); Assert.AreEqual("text/javascript;charset=utf-8", request.ResponseHeaders["content-type"]); } }
public void OpenTypeIncorrectPropertyNameTest() { string[] invalidNames = new string[] { null, "", " ", "1", "@for", //"a.", "a;", "a`", "a,", //"a-", "a+", "a\'", "a[", "a]", "a ", " a", }; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { foreach (string name in invalidNames) { using (StaticCallbackManager <PopulatingValuesEventArgs <OpenElement> > .RegisterStatic((sender, args) => { var o = new OpenElement(); o.Properties[name] = 1; args.Values.Add(o); })) { request.DataServiceType = typeof(OpenTypeContextWithReflection <OpenElement>); request.Accept = "application/atom+xml,application/xml"; request.RequestUriString = "/Values"; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, true); } } } }
public void OpenTypeMetadataTest() { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(CustomRowBasedOpenTypesContext); request.RequestUriString = "/$metadata"; request.SendRequest(); using (Stream responseStream = request.GetResponseStream()) { var document = new System.Xml.XPath.XPathDocument(responseStream); // Ensure the OpenType attribute is there. var expression = System.Xml.XPath.XPathExpression.Compile("//csdl:EntityType[@OpenType]", TestUtil.TestNamespaceManager); var nodeIterator = document.CreateNavigator().Select(expression); int count = 0; while (nodeIterator.MoveNext()) { Assert.AreEqual("true", nodeIterator.Current.SelectSingleNode("@OpenType").Value); count++; } // The OpenType attribute is present at all levels of the type hierarchy; expect it on all types. Assert.AreEqual(3, count); } } }
public void HttpProcessUtilityJsonEncodingTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("Test", TestUtil.CreateDictionary <string, Encoding>( new string[] { UnitTestsUtil.JsonLightMimeType, UnitTestsUtil.JsonLightMimeType + ";charset=utf-16", UnitTestsUtil.JsonLightMimeType + ";charset=GB18030" }, new Encoding[] { Encoding.UTF8, Encoding.Unicode, Encoding.GetEncoding("GB18030") }))); using (CustomDataContext.CreateChangeScope()) using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(CustomDataContext); request.Accept = UnitTestsUtil.JsonLightMimeType; request.HttpMethod = "POST"; int index = 100; TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { KeyValuePair <string, Encoding> test = (KeyValuePair <string, Encoding>)values["Test"]; Encoding encoding = test.Value; request.RequestContentType = test.Key; request.RequestStream = new MemoryStream(); byte[] bytes = encoding.GetBytes("{ @odata.type: 'AstoriaUnitTests.Stubs.Customer', ID : " + index++.ToString() + ", Name : \"P\\\\B \\/K\\\"n\\u00e4c\\f\\tke\\r\\n\\br\\u00f6d AB\" }"); request.RequestStream.Write(bytes, 0, bytes.Length); request.RequestStream.Position = 0; request.RequestUriString = "/Customers"; request.SendRequest(); string responseText = request.GetResponseStreamAsText(); Assert.IsTrue(responseText.Contains(@"P\\B /K\" + "\"" + @"n\u00e4c\f\tke\r\n\br\u00f6d AB"), "Response [" + responseText + "] contains the expected escape sequences."); }); } }
public void OpenTypeBasicTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("TypeData", TypeData.Values)); using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(OpenTypeContextWithReflection <OpenElement>); request.RequestUriString = "/Values"; TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { TypeData data = (TypeData)values["TypeData"]; foreach (object sampleValue in data.SampleValues) { using (StaticCallbackManager <PopulatingValuesEventArgs <OpenElement> > .RegisterStatic((sender, args) => { var o = new OpenElement(); o.Properties.Add("sampleValue", sampleValue); args.Values.Add(o); })) { Exception exception = TestUtil.RunCatching(request.SendRequest); // If we choose to throw when an open property is, say, IntPtr, use this: // Also check for null, since when the value is null, there is no way to know the datatype of the property TestUtil.AssertExceptionExpected(exception, !data.IsTypeSupported && sampleValue != null); } } }); } }
public void HttpContextServiceHostRequestNameTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("WebServerLocation", new WebServerLocation[] { WebServerLocation.InProcessWcf }), new Dimension("LocalHostName", new string[] { "127.0.0.1" })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { WebServerLocation location = (WebServerLocation)values["WebServerLocation"]; string hostName = (string)values["LocalHostName"]; using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers(1)?$format=atom"; request.StartService(); UriBuilder builder = new UriBuilder(request.FullRequestUriString); builder.Host = hostName; WebClient client = new WebClient(); string response = client.DownloadString(builder.Uri); response = response.Substring(response.IndexOf('<')); XmlDocument document = new XmlDocument(TestUtil.TestNameTable); document.LoadXml(response); string baseUri = UnitTestsUtil.GetBaseUri(document.DocumentElement); TestUtil.AssertContains(baseUri, hostName); } }); }
public void NonNullableComplexPropertyTest() { test.TestUtil.RunCombinations( new DSPUnitTestServiceDefinition[] { service }, new string[] { UnitTestsUtil.AtomFormat }, ServiceVersion.ValidVersions, // requestDSV ServiceVersion.ValidVersions, // requestMDSV ServiceVersion.ValidVersions, // maxProtocolVersion (localService, format, requestDSV, requestMDSV, maxProtocolVersion) => { if (maxProtocolVersion == null) { return; } localService.DataServiceBehavior.MaxProtocolVersion = maxProtocolVersion.ToProtocolVersion(); using (TestWebRequest request = localService.CreateForInProcess()) { if (requestDSV != null && maxProtocolVersion.ToProtocolVersion() < requestDSV.ToProtocolVersion()) { return; } request.StartService(); request.HttpMethod = "POST"; request.RequestUriString = "/People"; request.Accept = format; if (requestDSV != null) { request.RequestVersion = requestDSV.ToString(); } if (requestMDSV != null) { request.RequestMaxVersion = requestMDSV.ToString(); } request.RequestContentType = format; request.SetRequestStreamAsText(@"<entry xml:base='http://host/' xmlns:d='http://docs.oasis-open.org/odata/ns/data' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' xmlns='http://www.w3.org/2005/Atom'> <category term='#AstoriaUnitTests.Tests.PeopleType' scheme='http://docs.oasis-open.org/odata/ns/scheme' /> <content type='application/xml'> <m:properties> <d:ID m:type='Edm.Int32'>1</d:ID> <d:Name>bar</d:Name> <d:Body></d:Body> <d:Age>6</d:Age> <d:Office m:type='#AstoriaUnitTests.Tests.OfficeType' m:null='true'/> </m:properties> </content> </entry>"); request.HttpMethod = "POST"; var exception = test.TestUtil.RunCatching(request.SendRequest); Assert.IsNotNull(exception, "Exception is always expected."); Assert.IsNotNull(exception.InnerException, "InnerException is always expected."); // For v1 and v2, provider should throw. Assert.AreEqual("EntityFramework", exception.InnerException.Source, "Source expected: EntityFramework, actual: " + exception.InnerException.Source); Assert.AreEqual(500, request.ResponseStatusCode, "Status code expected: 500" + ", actual: " + request.ResponseStatusCode); } }); }
public void HttpContextServiceHost() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); string[] invalidUris = new string[] { "/Customers?$top=1&$top=2", "/Customers?$top=1&$top=", // "/Customers?$top=1&$top", - System.UriTemplateHelpers.ParseQueryString drops the empty argument "/Customers?$top", "/Customers?$foo", "/Customers?$top=1&%20$top=1", "/Customers?$top=1&$top%20=1", }; CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("uri", invalidUris)); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { request.RequestUriString = (string)values["uri"]; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, true); TestUtil.AssertExceptionStatusCode(exception, 400, "400 error expected for invalid query options " + request.RequestUriString); }); } }
private static void ResponsesShouldBeTheSame(string baselineUri, string testUri, int statusCode, Func <string, string> prepareExpected, Type serviceType) { using (TestServiceHost.AllowServerToSerializeException.Restore()) using (TestWebRequest baselineRequest = TestWebRequest.CreateForInProcess()) using (TestWebRequest testRequest = TestWebRequest.CreateForInProcess()) { TestServiceHost.AllowServerToSerializeException.Value = true; baselineRequest.DataServiceType = serviceType; testRequest.DataServiceType = serviceType; baselineRequest.RequestUriString = baselineUri; testRequest.RequestUriString = testUri; TestUtil.RunCatching(baselineRequest.SendRequest); TestUtil.RunCatching(testRequest.SendRequest); Assert.AreEqual(statusCode, testRequest.ResponseStatusCode); Assert.AreEqual(testRequest.ResponseStatusCode, baselineRequest.ResponseStatusCode); var baselinePayload = prepareExpected(testRequest.GetResponseStreamAsText()); string actualPayload = baselineRequest.GetResponseStreamAsText(); Assert.AreEqual(baselinePayload, actualPayload); } }
public void VerboseExceptionTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension(CustomDataContext.ExceptionTypeArgument, new object[] { typeof(FormatException) }), new Dimension(CustomDataContext.ExceptionAtEndArgument, new object[] { true }), new Dimension("verbose", new bool[] { true, false })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { bool verbose = (bool)values["verbose"]; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { int customerCount = (0xA0 / "Customer 1".Length) + 1; values[CustomDataContext.CustomerCountArgument] = customerCount; request.TestArguments = values; request.ForceVerboseErrors = verbose; request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; Exception exception = TestUtil.RunCatching(request.SendRequest); Assert.IsNotNull(exception, "Expecting an exception, but no exception was thrown"); if (verbose) { Assert.AreEqual(typeof(FormatException), exception.InnerException.GetType(), "Expecting formatexception, when verboseErrors is turned on"); } else { Assert.AreEqual(typeof(WebException), exception.GetType(), "Expecting WebException thrown by TestServiceHost.ProcessException method"); Assert.AreEqual("WebException from TestServiceHost.ProcessException", exception.Message); } } }); }
public void SetDollarFormatInAddQueryOption() { using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf()) { web.DataServiceType = typeof(DollarFormatTestService); web.StartService(); DataServiceContext ctx = new DataServiceContext(web.ServiceRoot, ODataProtocolVersion.V4); List <string> options = new List <string>() { "atom", "json", "jsonlight", "xml", }; foreach (string option in options) { try { ctx.CreateQuery <Customer>("Customers").AddQueryOption("$format", option).Execute(); } catch (NotSupportedException e) { Assert.AreEqual(DataServicesClientResourceUtil.GetString("ALinq_FormatQueryOptionNotSupported"), e.Message); } } } }
public void GeographyCollection_Serialize() { Dictionary <Type, object> data = new Dictionary <Type, object>(); foreach (var sample in testData) { data.Add(SpatialTestUtil.GeographyTypeFor(sample.Key), sample.Value.Select(wkt => wktFormatter.Read <Geography>(new StringReader(wkt))).ToList()); } using (TestWebRequest request = CreateCollectionReadService(data).CreateForInProcess()) { System.Data.Test.Astoria.TestUtil.RunCombinations(UnitTestsUtil.ResponseFormats, (format) => { var response = UnitTestsUtil.GetResponseAsAtomXLinq(request, "/Entities", format); // feed/entry/content/properties/CollectionGeographyPoint[@type = \"Collection(Edm.Point)\"]" UnitTestsUtil.VerifyXPaths(response, testData.Keys.Select(type => String.Format("atom:feed/atom:entry/atom:content/adsm:properties/ads:Collection{0}[@adsm:type = \"#Collection({1})\"]", SpatialTestUtil.GeographyTypeFor(type).Name, SpatialTestUtil.GeographyEdmNameFor(type))).ToArray()); UnitTestsUtil.VerifyXPaths(response, testData.Select(d => String.Format("count(atom:feed/atom:entry/atom:content/adsm:properties/ads:Collection{0}/adsm:element) = {1}", SpatialTestUtil.GeographyTypeFor(d.Key).Name, d.Value.Length)).ToArray()); }); } }
public static string GetResponse(string payload, Type contextType, WebServerLocation location, string requestVersion) { string[] segments = payload.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); string boundary = segments[0].Substring(2); using (TestWebRequest request = TestWebRequest.CreateForLocation(location)) { request.RequestVersion = requestVersion; request.DataServiceType = contextType; request.RequestUriString = "/$batch"; request.Accept = UnitTestsUtil.MimeMultipartMixed; request.HttpMethod = "POST"; request.RequestContentType = String.Format("{0}; boundary={1}", UnitTestsUtil.MimeMultipartMixed, boundary); if (request.BaseUri != null) { payload = Regex.Replace(payload, "\\$\\(BaseUri\\)", request.BaseUri.EndsWith("/") ? request.BaseUri : request.BaseUri + "/"); } request.RequestStream = IOUtil.CreateStream(payload); request.SendRequest(); Stream responseStream = request.GetResponseStream(); using (StreamReader reader = new StreamReader(responseStream)) { return(PrepareResponseForFileCompare(reader, request.BaseUri, "$(BaseUri)")); } } }
public void CreateODataWriterDataServerExceptionSurfacingTest() { // ATOM the value is written to the Feed prior to Start,JSON the value is written after start // but before end using (OpenWebDataServiceHelper.CreateODataWriterDelegate.Restore()) using (MyODataWriter.WriteEntryStart.Restore()) using (var request = TestWebRequest.CreateForInProcess()) { request.HttpMethod = "GET"; request.DataServiceType = typeof(CustomDataContext); OpenWebDataServiceHelper.CreateODataWriterDelegate.Value = (odataWriter) => new MyODataWriter(odataWriter); MyODataWriter.WriteEntryStart.Value = (args) => { throw new DataServiceException(509, "Should see this message in error"); }; request.RequestUriString = "/Orders"; try { request.SendRequest(); } catch (WebException) { Assert.AreEqual(509, request.ResponseStatusCode); Assert.IsTrue(request.GetResponseStreamAsText().Contains("Should see this message in error")); } } }
public void CreateODataWriterExceptionTestOnLink() { // ATOM the value is written to the Feed prior to Start,JSON the value is written after start // but before end using (OpenWebDataServiceHelper.CreateODataWriterDelegate.Restore()) using (MyODataWriter.WriteLinkStart.Restore()) using (var request = TestWebRequest.CreateForInProcess()) { request.HttpMethod = "GET"; request.DataServiceType = typeof(CustomDataContext); OpenWebDataServiceHelper.CreateODataWriterDelegate.Value = (odataWriter) => new MyODataWriter(odataWriter); MyODataWriter.WriteLinkStart.Value = (args) => { throw new ODataException("Cast exception"); }; request.RequestUriString = "/Customers?$expand=Orders"; try { request.SendRequest(); } catch (WebException) { Assert.AreEqual(500, request.ResponseStatusCode); Assert.IsTrue(request.GetResponseStreamAsText().Contains("Cast exception")); } } }
public void CallbackFailOnAtomXml() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); List <string> requestUriStrings = new List <string>() { "/Customers(1)?$callback=foo", "/Customers(1)/Address?$callback=foo", }; foreach (string requestUriString in requestUriStrings) { try { request.RequestUriString = requestUriString; request.Accept = "application/atom+xml,application/xml"; request.SendRequest(); Assert.Fail("Request should have failed because our server defaults to ATOM/XML, which does not support $callback."); } catch (WebException) { var actualText = request.GetResponseStreamAsText(); Assert.IsFalse(actualText.StartsWith("foo(")); Assert.IsTrue(actualText.Contains("is not compatible with the $callback query option.")); Assert.IsTrue(request.ResponseHeaders["content-type"].StartsWith("application/xml")); Assert.AreEqual(400, request.ResponseStatusCode); } } } }
public void CallbackFailOnCUDRequest() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers(1)?$format=json&$callback=foo"; List <string> methods = new List <string>() { "POST", "PUT", "DELETE" }; request.RequestStream = new MemoryStream(new byte[] { 1, 2, 3, }); foreach (string method in methods) { try { request.HttpMethod = method; request.SendRequest(); Assert.Fail("Request should have failed because it was not a GET request."); } catch (WebException) { var actualText = request.GetResponseStreamAsText(); Assert.IsFalse(actualText.StartsWith("foo(")); Assert.IsTrue(actualText.Contains("$callback can only be specified on GET requests.")); Assert.IsTrue(request.ResponseHeaders["content-type"].StartsWith("application/json")); Assert.AreEqual(400, request.ResponseStatusCode); } } } }
public void AdvertiseLargeNumberOfActionsTests() { // Test advertising large number of actions. var testCases = new[] { new { RequestUri = "/Customers(1)", }, }; using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); t.TestUtil.RunCombinations(testCases, (testCase) => { DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); //ctx.EnableAtom = true; //ctx.Format.UseAtom(); ctx.ResolveType = name => typeof(Customer); Uri uri = new Uri(request.ServiceRoot + testCase.RequestUri); QueryOperationResponse <object> qor = (QueryOperationResponse <object>)ctx.Execute <object>(uri); Assert.IsNotNull(qor); IEnumerator <object> entities = qor.GetEnumerator(); entities.MoveNext(); Assert.IsNotNull(entities.Current); EntityDescriptor ed = ctx.GetEntityDescriptor(entities.Current); Assert.IsNotNull(ed); Assert.IsNotNull(ed.OperationDescriptors); Assert.AreEqual(ed.OperationDescriptors.Count(), TotalNumberOfActions, "Invalid count of total number of advertised actions."); }); } }
public void ClassCleanup() { if (request != null) { request.Dispose(); request = null; } }
protected override void InitializeService(TestWebRequest request) { base.InitializeService(request); // We reset all the static variables to nulls since we use the service definition if it's available // This allows users to modify the settings on the servide definition while the service already runs and those changes to have effect OpenWebDataServiceDefinition.ApplySetting(request, PlaybackService.OverridingPlayback, null); OpenWebDataServiceDefinition.ApplySetting(request, PlaybackService.InspectRequestPayload, null); OpenWebDataServiceDefinition.ApplySetting(request, PlaybackService.ProcessRequestOverride, null); }
/// <summary>Creates the in-memory response from another TestWebRequest, copying its reponse.</summary> /// <param name="sourceResponse">The request to read the response from.</param> /// <returns>The newly create request object with the response proeprties filled with the data from the request response.</returns> public static InMemoryWebRequest FromResponse(TestWebRequest sourceResponse) { InMemoryWebRequest response = new InMemoryWebRequest(); response.SetResponseStatusCode(sourceResponse.ResponseStatusCode); foreach (var header in GetAllResponseHeaders(sourceResponse)) { response.ResponseHeaders[header.Key] = header.Value; } using (Stream responseStream = sourceResponse.GetResponseStream()) { response.SetResponseStream(responseStream); } return response; }
private void VerifyEntryIDsAndXPaths(string requestUri, TestWebRequest request, int[] expectedIDs, params string[] xpaths) { var response = UnitTestsUtil.GetResponseAsAtomXLinq(request, requestUri); List<string> ids = response.Root.Elements(UnitTestsUtil.AtomNamespace + "entry").Elements(UnitTestsUtil.AtomNamespace + "id") .Select(e => (string)e).ToList(); Assert.AreEqual(expectedIDs.Length, ids.Count, "The number of returned entries doesn't match."); for (int i = 0; i < expectedIDs.Length; i++) { if (!ids[i].Contains("(" + expectedIDs[i].ToString() + ")")) { Assert.Fail("Entries not reported correctly, \r\nexpected: " + expectedIDs.Select(n => n.ToString()).Concatenate(", ") + "\r\nactual: " + ids.Concatenate(", ") + "\r\n" + response.ToString()); } } UnitTestsUtil.VerifyXPathExists(response, xpaths); }
internal static void VerifyRequestSyntaxError(TestWebRequest request) { try { request.SendRequest(); Assert.Fail("Syntax error expected for " + request.RequestUriString + ", but none thrown."); } catch (WebException exception) { DataServiceException serviceException = (DataServiceException)exception.InnerException; Assert.AreEqual(400, serviceException.StatusCode, "Syntax errors give 400 - Bad Status results (for [" + request.RequestUriString + "])"); } }
public PassThroughInterceptor(string playbackServiceUriInput, TestWebRequest underlyingServiceInput) { this.PlaybackServiceBaseUri = playbackServiceUriInput; this.UnderlyingService = underlyingServiceInput; }
internal static void VerifyRequestSyntaxError(TestWebRequest request, string requestUriString) { request.RequestUriString = requestUriString; VerifyRequestSyntaxError(request); }
private static ResourceVerification GetResourceVerification(string responseFormat, int id, GeographyPropertyValues defaultValues, TestWebRequest request) { Assert.IsTrue(responseFormat == UnitTestsUtil.AtomFormat || responseFormat == UnitTestsUtil.JsonLightMimeType, "Response format {0} not recognized in GetResourceVerification.", responseFormat); DSPResourceSerializerFormat payloadFormat = responseFormat == UnitTestsUtil.AtomFormat ? DSPResourceSerializerFormat.Atom : DSPResourceSerializerFormat.Json; return new ResourceVerification(request, payloadFormat, id, defaultValues); }
private void PreferHeader_VerifyResponse(TestWebRequest request, string serviceRoot, bool considerResponsePreference, Action<XDocument> responsePayloadValidation) { bool? effectiveResponsePreference; bool expectedPayload = PreferHeader_ShouldContainResponseBody(request, considerResponsePreference, out effectiveResponsePreference); ServiceVersion responseVersion = ServiceVersion.FromHeaderValue(request.ResponseVersion); string preferApplied; request.ResponseHeaders.TryGetValue("Preference-Applied", out preferApplied); string odataEntityId; request.ResponseHeaders.TryGetValue("OData-EntityId", out odataEntityId); if (request.HttpMethod == "POST") { // Substring(1) to remove the first slash // For POST we need to add the (1) to identify the entity posted string itemLocation = serviceRoot + request.RequestUriString.Substring(1) + "(1)"; if (effectiveResponsePreference == false) { Assert.AreEqual(204, request.ResponseStatusCode, "POST without response payload should respond with status 204."); Assert.AreEqual(itemLocation, odataEntityId, "Response to POST without payload must include the OData-EntityId header with the value being the URL of the item posted."); } else { Assert.AreEqual(201, request.ResponseStatusCode, "POST with response payload should respond with status 201."); Assert.IsNull(odataEntityId, "Response to POST with payload must NOT include the OData-EntityId header."); } Assert.AreEqual(itemLocation, request.ResponseLocation, "The response to POST should include the Location header and it must have the URL to the item posted."); } else { Assert.AreEqual(expectedPayload ? 200 : 204, request.ResponseStatusCode, "Unexpected response status for PUT/PATCH."); Assert.IsNull(odataEntityId, "Response to anything other than POST must NOT include the OData-EntityId header."); } if (effectiveResponsePreference.HasValue) { Assert.IsTrue(responseVersion.Version >= 40, "Response which was influenced by the Prefer header must have DSV >= 4.0"); Assert.AreEqual(effectiveResponsePreference == false ? "return=minimal" : "return=representation", preferApplied, "The preference was applied and thus Preference-Applied header should have been included with the right value."); } else { Assert.IsNull(preferApplied, "No Prefer was sent or it was ignored thus Preference-Applied must not be sent in the response."); } if (expectedPayload) { XDocument response = UnitTestsUtil.GetResponseAsAtomXLinq(request); if (responsePayloadValidation != null) { responsePayloadValidation(response); } } else { string response = request.GetResponseStreamAsText(); Assert.IsTrue(string.IsNullOrEmpty(response), "No response should have been sent."); } }
/// <summary>Called to initialize the service on a given request.</summary> /// <param name="request">The request which was not yet used for the service to initialize on.</param> protected override void InitializeService(TestWebRequest request) { // Create the table and populate it with data. Register for cleanup as well. request.RegisterForDispose(ocs.PopulateData.CreateTableAndPopulateData()); }
/// <summary>Applies all the headers in the RequestHeaders collection to the explicit properties.</summary> public static void ApplyHeadersToProperties(TestWebRequest request) { string contentLength = GetAndRemoveRequestHeader(request, "Content-Length"); if (contentLength != null) { request.RequestContentLength = Int32.Parse(contentLength); } request.RequestContentType = GetAndRemoveRequestHeader(request, "Content-Type"); request.Accept = GetAndRemoveRequestHeader(request, "Accept"); request.AcceptCharset = GetAndRemoveRequestHeader(request, "Accept-Charset"); request.IfMatch = GetAndRemoveRequestHeader(request, "If-Match"); request.IfNoneMatch = GetAndRemoveRequestHeader(request, "If-None-Match"); request.RequestMaxVersion = GetAndRemoveRequestHeader(request, "OData-MaxVersion"); request.RequestVersion = GetAndRemoveRequestHeader(request, "OData-Version"); }
/// <summary>Returns a single request header value, or null if no such value exists. Then it removes that header from the collection.</summary> /// <param name="header">The name of the request header to get</param> /// <returns>The value of the header or null if no such header was in the request.</returns> private static string GetAndRemoveRequestHeader(TestWebRequest request, string header) { string value; if (request.RequestHeaders.TryGetValue(header, out value)) { request.RequestHeaders.Remove(header); return value; } return null; }
/// <summary>Creates a dictionary of request headers as specified by the request object.</summary> /// <returns>The request headers specified by this object.</returns> /// <remarks>This collects all the request headers from the various properties the request object has.</remarks> public static Dictionary<string, string> GetAllRequestHeaders(TestWebRequest request) { Dictionary<string, string> headers = new Dictionary<string, string>(); if (request.RequestContentLength != -1) { headers.Add("Content-Length", request.RequestContentLength.ToString()); } if (request.RequestContentType != null) { headers.Add("Content-Type", request.RequestContentType); } if (request.Accept != null) { headers.Add("Accept", request.Accept); } if (request.AcceptCharset != null) { headers.Add("Accept-Charset", request.AcceptCharset); } if (!String.IsNullOrEmpty(request.IfMatch)) { headers.Add("If-Match", request.IfMatch); } if (!String.IsNullOrEmpty(request.IfNoneMatch)) { headers.Add("If-None-Match", request.IfNoneMatch); } if (request.RequestMaxVersion != null) { headers.Add("OData-MaxVersion", request.RequestMaxVersion); } if (request.RequestVersion != null) { headers.Add("OData-Version", request.RequestVersion); } foreach (var h in request.RequestHeaders) { headers[h.Key] = h.Value; } return headers; }
/// <summary>Creates a dictionary of response headers as specified by the request object.</summary> /// <returns>The response headers specified by this object.</returns> /// <remarks>This collects all the response headers from the various properties the request object has.</remarks> public static Dictionary<string, string> GetAllResponseHeaders(TestWebRequest request) { Dictionary<string, string> headers = new Dictionary<string, string>(); if (request.ResponseCacheControl != null) { headers.Add("Cache-Control", request.ResponseCacheControl); } if (request.ResponseContentType != null) { headers.Add("Content-Type", request.ResponseContentType); } if (request.ResponseETag != null) { headers.Add("ETag", request.ResponseETag); } if (request.ResponseLocation != null) { headers.Add("Location", request.ResponseLocation); } if (request.ResponseVersion != null) { headers.Add("OData-Version", request.ResponseVersion); } foreach (var h in request.ResponseHeaders) { headers[h.Key] = h.Value; } return headers; }
/// <summary>Writes the request into another request instance (copies the data over).</summary> /// <param name="request">The request to write to.</param> public void WriteRequest(TestWebRequest request) { request.HttpMethod = this.HttpMethod; request.RequestUriString = this.RequestUriString; foreach (var header in GetAllRequestHeaders(this)) { request.RequestHeaders[header.Key] = header.Value; } ApplyHeadersToProperties(request); request.RequestStream = this.RequestStream; }
public static void ClassInitialize(TestContext context) { changeScope = EFFK.CustomObjectContextPOCOProxy.CreateChangeScope(); web = TestWebRequest.CreateForInProcessWcf(); web.DataServiceType = typeof(EFFK.CustomObjectContextPOCOProxy); OpenWebDataServiceHelper.ForceVerboseErrors = true; web.StartService(); }
public void SetupOverflowRequest(TestWebRequest request, bool useCollections) { TestUtil.CheckArgumentNotNull(request, "request"); StringBuilder builder; int entryId = 100; request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; switch (this.feature) { case StackConsumingFeature.AtomDeserializer: // ATOM deserializer shares limits with JSON deserialized. int atomDeserializerDepth = 105; request.HttpMethod = "POST"; request.RequestContentType = SerializationFormatData.Atom.MimeTypes[0]; builder = new StringBuilder(); string entryTail = "xml:base=\"/\" " + TestUtil.CommonPayloadNamespaces + ">" + AtomUpdatePayloadBuilder.GetCategoryXml(typeof(Customer).FullName); // "<category term=\"" + typeof(Customer).FullName + "\" scheme=\"http://docs.oasis-open.org/odata/ns/scheme\" />"; for (int i = 0; i < atomDeserializerDepth; i++) { if (i != 0) { builder.Append("<adsm:inline>"); } if (i == 1) { entryTail = "> " + AtomUpdatePayloadBuilder.GetCategoryXml(typeof(Customer).FullName); } builder.Append("<entry " + entryTail); builder.Append("<content type=\"application/xml\"><adsm:properties>"); builder.Append("<ads:ID>" + (entryId++).ToString() + "</ads:ID></adsm:properties></content>"); builder.Append("<link rel='http://docs.oasis-open.org/odata/ns/related/BestFriend' title='BestFriend'>"); } for (int i = 0; i < atomDeserializerDepth; i++) { if (i != 0) { builder.Append("</adsm:inline>"); } builder.Append("</link></entry>"); } request.SetRequestStreamAsText(builder.ToString()); break; case StackConsumingFeature.JsonDeserializer: // JSON deserializer survives 1000 nested objects but not 2000 on Vista Ultimate x86 chk under debugger. We hard-code to 100. int jsonDeserializerDepth = 200; request.HttpMethod = "POST"; request.RequestContentType = UnitTestsUtil.JsonLightMimeType; builder = new StringBuilder(); for (int i = 0; i < jsonDeserializerDepth; i++) { builder.Append("{ @odata.type: \"" + typeof(Customer).FullName + "\" , ID: " + (entryId++).ToString() + ", BestFriend : "); } // builder.Append("null"); // null not supported builder.Append(" { ID : 110000 } "); builder.Append('}', jsonDeserializerDepth); request.SetRequestStreamAsText(builder.ToString()); break; case StackConsumingFeature.JsonReader: // JSON reader is not recursive in ODL, so we pick a large depth here to verify that it doesn't break. int jsonReaderDepth = 3000; request.HttpMethod = "POST"; request.RequestContentType = UnitTestsUtil.JsonLightMimeType; request.SetRequestStreamAsText(new string('[', jsonReaderDepth) + " abc "); break; case StackConsumingFeature.RequestQueryParser: // Query parser survives 1000 nested expressions but not 5000 on Vista Ultimate x86 chk under the debugger. We hard-code to 100 nested expressions. int queryParserDepth = 115; request.RequestUriString += "?$filter=" + new string('(', queryParserDepth) + "true" + new string(')', queryParserDepth); break; case StackConsumingFeature.RequestUriProcessor: // The Uri constructor already restricts to 65520 characters. // Request processor is hard-coded to reject more than 100 segments of querying. int processorDepth = 101; builder = new StringBuilder(request.RequestUriString + "(1)"); for (int i = 0; i < processorDepth; i++) { builder.Append("/a"); } request.RequestUriString = builder.ToString(); break; case StackConsumingFeature.JsonSerializer: request.DataServiceType = useCollections ? typeof(StackOverflowCollectionCustomDataContext) : typeof(StackOverflowCustomDataContext); request.Accept = AstoriaUnitTests.Data.SerializationFormatData.JsonLight.MimeTypes[0]; break; case StackConsumingFeature.AtomSerializer: request.DataServiceType = useCollections ? typeof(StackOverflowCollectionCustomDataContext) : typeof(StackOverflowCustomDataContext); request.Accept = AstoriaUnitTests.Data.SerializationFormatData.Atom.MimeTypes[0]; break; case StackConsumingFeature.XmlSerializer: request.DataServiceType = useCollections ? typeof(StackOverflowCollectionCustomDataContext) : typeof(StackOverflowCustomDataContext); request.RequestUriString = "/Customers(1)/Address"; break; default: Debug.Fail("Unknown feature."); break; } }
private void PreferHeader_SetupRequest(TestWebRequest request, string httpMethod, string format, XDocument existingItemAtom, DSPResource existingItem, Action<XDocument> modifyInputAtom) { string realHttpMethod = httpMethod; if (realHttpMethod == "POSTMR") { realHttpMethod = "POST"; } request.HttpMethod = realHttpMethod; request.RequestContentType = httpMethod == "POSTMR" ? UnitTestsUtil.MimeTextPlain : format; request.Accept = format; XDocument inputAtom = new XDocument(existingItemAtom); // Remove all nav property links as those are not supported on some operations inputAtom.Root.Elements(UnitTestsUtil.AtomNamespace + "link").Where(e => e.Attribute("rel").Value.Contains("http://docs.oasis-open.org/odata/ns/related/") || e.Attribute("rel").Value.Contains("http://docs.oasis-open.org/odata/ns/relatedlinks/")).Remove(); request.RequestHeaders["Slug"] = null; if (httpMethod == "POST") { inputAtom.Root.Element(UnitTestsUtil.AtomNamespace + "content").Element(UnitTestsUtil.MetadataNamespace + "properties") .Element(UnitTestsUtil.DataNamespace + "ID").Value = "1"; request.IfMatch = null; request.RequestUriString = "/Items"; } else if (httpMethod == "POSTMR") { request.RequestHeaders["Slug"] = "1"; request.IfMatch = null; request.RequestUriString = "/Streams"; } else { request.IfMatch = existingItem.GetETag(); request.RequestUriString = "/Items(0)"; } if (httpMethod == "POSTMR") { request.SetRequestStreamAsText("some text content"); } else { if (modifyInputAtom != null) { modifyInputAtom(inputAtom); } request.SetRequestStreamAsText(inputAtom.ToString()); } }
public void TestInitialize() { DSPServiceDefinition service = NamedStreamService.SetUpNamedStreamService(); request = service.CreateForInProcessWcf(); request.StartService(); }
private bool PreferHeader_ShouldContainResponseBody(TestWebRequest request, bool considerResponsePreference, out bool? effectiveResponsePreference) { effectiveResponsePreference = null; string preferHeader; request.RequestHeaders.TryGetValue("Prefer", out preferHeader); if (preferHeader != null && considerResponsePreference) { if (string.Equals(preferHeader, "return=minimal", StringComparison.OrdinalIgnoreCase)) { effectiveResponsePreference = false; } if (string.Equals(preferHeader, "return=representation", StringComparison.OrdinalIgnoreCase)) { effectiveResponsePreference = true; } } bool expectedPayload = false; if (request.HttpMethod == "POST") { // For POST the payload is included unless the Prefer header says to not include it and version makes the Prefer header valid expectedPayload = effectiveResponsePreference != false; } else { // For PUT/PATCH the payload is not included unless the Prefer header says to include it and version makes the Prefer header valid expectedPayload = effectiveResponsePreference == true; } return expectedPayload; }
private static bool IsValidScenario(TestWebRequest request, ODataProtocolVersion protocolVersion, ServiceVersions versions, ServiceVersion requestDSV, ServiceVersion requestMDSV, Exception exception) { // figure out the default values of the version if they are null if (requestDSV == null && requestMDSV != null) { requestDSV = requestMDSV.Version > 20 ? requestMDSV : new ServiceVersion(40); } if (exception != null) { Assert.AreEqual(400, request.ResponseStatusCode, "Expecting bad request"); List<string> expectedErrorMessages = new List<string>(); if (requestDSV != null && requestDSV.Version < versions.MinRequestDSV.Version) { expectedErrorMessages.Add(DataServicesResourceUtil.GetString("DataService_DSVTooLow", requestDSV.ToString(), versions.MinRequestDSV.Version / 10, versions.MinRequestDSV.Version % 10)); } if (requestMDSV != null && requestMDSV.Version < versions.MinRequestMDSV.Version) { expectedErrorMessages.Add(DataServicesResourceUtil.GetString("DataService_MaxDSVTooLow", requestMDSV.ToString(), versions.MinRequestMDSV.Version / 10, versions.MinRequestMDSV.Version % 10)); } // Since enableRelationshipLinks is true, the response will be 3.0 if the MPV is set to 3.0. For V1/V2 servers, this setting is ignored if (protocolVersion == ODataProtocolVersion.V4 && requestMDSV != null && requestMDSV.ToProtocolVersion() < protocolVersion) { expectedErrorMessages.Add(DataServicesResourceUtil.GetString("DataService_MaxDSVTooLow", requestMDSV.ToString(), 4, 0)); } if (expectedErrorMessages.Count != 0) { Assert.IsTrue(expectedErrorMessages.Contains(exception.InnerException.Message), "Didn't find the expected error message"); } else { Assert.Fail("Exception not expected, but exception was thrown"); } return false; } Assert.IsTrue(requestDSV == null || requestDSV.Version >= versions.MinRequestDSV.Version, "Request DSV should be equal or greater than the min required DSV"); Assert.IsTrue(requestMDSV == null || requestMDSV.Version >= versions.MinRequestMDSV.Version, "Request MDSV should be equal or greater than the min required MDSV"); return true; }
internal static void SetHeaderValues(TestWebRequest request, IEnumerable<KeyValuePair<string, string>> headerValues) { UnitTestsUtil.SetHeaderValues(request, headerValues); }
public static bool ValidateCustomResponseHeaders(TestWebRequest request) { if (request.ResponseHeaders.ContainsKey("CustomResponseHeader1") && request.ResponseHeaders["CustomResponseHeader1"] == "CustomResponseHeaderValue1" && request.ResponseHeaders.ContainsKey("CustomResponseHeader2") && request.ResponseHeaders["CustomResponseHeader2"] == "CustomResponseHeaderValue2") { return true; } return false; }
/// <summary>Called to initialize the service on a given request.</summary> /// <param name="request">The request which was not yet used for the service to initialize on.</param> virtual protected void InitializeService(TestWebRequest request) { request.RegisterForDispose(System.Data.Test.Astoria.TestUtil.RestoreStaticValueOnDispose(typeof(System.Data.Test.Astoria.BaseTestWebRequest), "HostInterfaceType")); System.Data.Test.Astoria.BaseTestWebRequest.HostInterfaceType = this.HostInterfaceType; }
/// <summary> /// Make final changes to the testcase before sending the request. /// </summary> private static void MakeFinalChangesToTestCase(TestCase testCase, ODataFormat format, MyDSPActionProvider actionProvider, TestWebRequest request) { foreach (var action in testCase.Operations) { actionProvider.AddAction((ServiceAction)action); } testCase.AddBaseUriStringToExpectedDescriptors(request.ServiceRoot.OriginalString, format); if (testCase.SubstituteAdvertiseServiceAction != null) { actionProvider.SubstituteAdvertiseServiceAction = testCase.SubstituteAdvertiseServiceAction; } }
private static void ExecuteUpdate(DSPResource resource, int id, TestWebRequest baseRequest, string httpMethod, string preferHeader, bool useBatch, DSPResourceSerializerFormat payloadFormat) { string payload = DSPResourceSerializer.WriteEntity(resource, payloadFormat); bool isPost = httpMethod == "POST"; bool expectedReturnContent = preferHeader == "return=representation" || isPost && preferHeader == null; string uriSuffix = isPost ? String.Empty : String.Format("({0})", id); TestWebRequest request = useBatch ? new InMemoryWebRequest() : baseRequest; request.RequestUriString = String.Format("/{0}s{1}", resource.ResourceType.Name, uriSuffix); request.HttpMethod = httpMethod; request.RequestVersion = "4.0;"; request.RequestMaxVersion = "4.0;"; request.RequestHeaders["Prefer"] = preferHeader; request.Accept = payloadFormat == DSPResourceSerializerFormat.Atom ? "application/atom+xml,application/xml" : UnitTestsUtil.JsonLightMimeType; request.RequestContentType = "application/atom+xml"; request.SetRequestStreamAsText(payload); if (useBatch) { var batchRequest = new BatchWebRequest(); var changeset = new BatchWebRequest.Changeset(); changeset.Parts.Add((InMemoryWebRequest)request); batchRequest.Changesets.Add(changeset); batchRequest.SendRequest(baseRequest); Assert.IsTrue(UnitTestsUtil.IsSuccessStatusCode(baseRequest.ResponseStatusCode), "Unexpected error occurred on batch."); } else { request.SendRequest(); } Assert.IsTrue(UnitTestsUtil.IsSuccessStatusCode(request.ResponseStatusCode), "Unexpected error occurred when sending the request."); if (expectedReturnContent) { // If the request is expected to return content, verify there were no instream errors Exception e = request.ParseResponseInStreamError(); string errorMessage = e != null ? e.Message : string.Empty; Assert.IsNull(e, "Expected no exception, but got the following error", errorMessage); } }
internal static void VerifyResourceNotFoundError(TestWebRequest request) { try { request.SendRequest(); Assert.Fail("Resource Not Found error expected for " + request.RequestUriString + ", but none thrown."); } catch (WebException exception) { DataServiceException serviceException = exception.InnerException as DataServiceException; if (serviceException == null) { throw; } Assert.AreEqual(404, serviceException.StatusCode, "General URI errors give 404 - Resource Not Found results (for [" + request.RequestUriString + "])"); } }
private static XElement GetAtomEntryProperties(TestWebRequest request, string resourceSetName, int id) { request.HttpMethod = "GET"; XDocument response = UnitTestsUtil.GetResponseAsAtomXLinq(request, string.Format("/{0}({1})", resourceSetName, id), "application/atom+xml,application/xml"); XElement entry = response.Root.Element(UnitTestsUtil.AtomNamespace + "content"); Assert.IsNotNull(entry, "Expected the request to produce an ATOM entry."); return entry.Element(UnitTestsUtil.MetadataNamespace + "properties"); }
static void SendRequestAndAssertExistence(TestWebRequest request, string requestUri, params string[] xpaths) { request.RequestUriString = requestUri; request.SendRequest(); XmlDocument responseXml = request.GetResponseStreamAsXmlDocument(); foreach (string xpath in xpaths) { TestUtil.AssertSelectSingleElement(responseXml, xpath); } }