public void CheckRelationshipLinkForDeleteOperationForEntityCollection() { // CreateChangeScope will make sure that changes are preserved after every SendRequest. // By default the data source is created for every request using (UnitTestsUtil.CreateChangeScope(typeof(CustomDataContext))) { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.ServiceType = typeof(RelationshipLinksService); request.RequestUriString = "/Customers(1)/Orders/$ref"; request.HttpMethod = "GET"; request.SendRequest(); var response1 = request.GetResponseStreamAsText(); request.RequestUriString = "/Customers(1)/Orders/$ref?$id=Orders(1)"; request.HttpMethod = "DELETE"; request.SendRequest(); var response = request.GetResponseStreamAsText(); Assert.IsTrue(response != null); Assert.IsTrue(request.ResponseStatusCode == 204); request.RequestUriString = "/Customers(1)/Orders/$ref"; request.HttpMethod = "GET"; request.SendRequest(); var response2 = request.GetResponseStreamAsText(); Assert.IsTrue(response1 != response2); } } }
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 WebDataServiceMetadataCache() { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { bool called = false; using (AstoriaUnitTests.Tests.UnitTestModule.AuthorizationTest.InitializationCallbackManager.RegisterStatic( delegate(object sender, AstoriaUnitTests.Tests.UnitTestModule.AuthorizationTest.InitializationCallbackEventArgs args) { args.Configuration.SetEntitySetAccessRule("*", EntitySetRights.All); called = true; })) { TestUtil.ClearConfiguration(); request.ServiceType = typeof(AstoriaUnitTests.Tests.UnitTestModule.AuthorizationTest.WebDataServiceA); request.RequestUriString = "/Customers"; request.SendRequest(); Assert.IsTrue(called, "Initialization callback called."); called = false; request.SendRequest(); Assert.IsFalse(called, "Initialization callback not called - presumably configuration was cached."); } } }
public void CallBackInBatchRequestTest() { StringBuilder batchQueryOperation = new StringBuilder(); batchQueryOperation.AppendLine("GET Customers(1)/Address?$callback=foo HTTP/1.1"); batchQueryOperation.AppendLine("Host: host"); batchQueryOperation.AppendLine("Accept: " + UnitTestsUtil.JsonMimeType); batchQueryOperation.AppendLine("Override-Accept: " + UnitTestsUtil.JsonLightMimeType); var testCase = new SimpleBatchTestCase { RequestPayload = new BatchInfo(new BatchQuery(new Operation(batchQueryOperation.ToString()))), ExpectedResponsePayloadContains = new[] { "Content-Type: text/javascript;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8", "foo({\"@odata.context\":", "\"StreetAddress\":\"Line1\",\"City\":\"Redmond\",\"State\":\"WA\",\"PostalCode\":\"98052\"})", }, ResponseStatusCode = 202, ResponseETag = default(string), }; using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.HttpMethod = "POST"; request.RequestUriString = "/$batch"; request.DataServiceType = typeof(CustomDataContext); request.Accept = UnitTestsUtil.MimeMultipartMixed; request.ForceVerboseErrors = true; const string boundary = "batch-set"; request.RequestContentType = String.Format("{0}; boundary={1}", UnitTestsUtil.MimeMultipartMixed, boundary); request.SetRequestStreamAsText(BatchRequestWritingUtils.GetBatchText(testCase.RequestPayload, boundary)); // callback in inner GET request should succeed request.SendRequest(); string response = request.GetResponseStreamAsText(); Assert.AreEqual(testCase.ResponseStatusCode, request.ResponseStatusCode); Assert.IsTrue(request.ResponseContentType.StartsWith("multipart/mixed; boundary=batchresponse_")); foreach (string str in testCase.ExpectedResponsePayloadContains) { Assert.IsTrue(response.Contains(str), String.Format("The response:\r\n{0}\r\nDoes not contain the string:\r\n{1}.", response, str)); } // callback with $batch should fail try { request.RequestUriString = "/$batch?$callback=bar"; request.SendRequest(); Assert.Fail("Request should have failed because it was not a GET request."); } catch (WebException) { Assert.IsTrue(request.GetResponseStreamAsText().Contains("$callback can only be specified on GET requests.")); Assert.IsTrue(request.ResponseHeaders["content-type"].StartsWith("application/xml")); Assert.AreEqual(400, request.ResponseStatusCode); } } }
public void BasicUpdateTests() { ICollection <Tuple <string, string, string, string> > payloadsAndVerifications = new List <Tuple <string, string, string, string> > { new Tuple <string, string, string, string>( "/Elevators", "/Elevators(4)", "{ @odata.type: \"AstoriaUnitTests.Tests.Elevator\", ID: 4, SerialNumber: \"98765\", Location: \"W\" }", "/atom:entry/atom:content/adsm:properties[ads:ID=4 and ads:Location='W'] | /atom:entry/atom:link[@href='98765']"), new Tuple <string, string, string, string>( "/FloorCalls", "/FloorCalls(3)", "{ @odata.type: \"AstoriaUnitTests.Tests.FloorCall\", ID: 3, Floor: 2, Up: \"true\", Down: \"true\" }", "/atom:entry/atom:content/adsm:properties[ads:ID=3 and ads:Up='true' and ads:Down='true'] | /atom:entry/atom:category[@term='2']"), }; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = ContextType; request.Accept = "application/atom+xml,application/xml"; request.ForceVerboseErrors = true; request.RequestContentType = SerializationFormatData.JsonLight.MimeTypes[0] + ";charset=iso-8859-1"; TestUtil.RunCombinations <Tuple <string, string, string, string> >(payloadsAndVerifications, (testcase) => { string collectionUri = testcase.Item1; string singleUri = testcase.Item2; string payload = testcase.Item3; string verifyXPath = testcase.Item4; request.HttpMethod = "POST"; request.RequestStream = IOUtil.CreateStream(payload); SendRequestAndAssertExistence(request, collectionUri, verifyXPath); request.HttpMethod = "PATCH"; request.RequestUriString = singleUri; request.RequestStream = IOUtil.CreateStream(payload); request.SendRequest(); request.HttpMethod = "PUT"; request.RequestUriString = singleUri; request.RequestStream = IOUtil.CreateStream(payload); request.SendRequest(); request.HttpMethod = "DELETE"; request.RequestUriString = singleUri; request.SendRequest(); }); } }
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)]"); } } } }
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 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 JsonLightPayloadMetadataIntegrationTest() { Stream resultStream = UnitTestsUtil.GetResponseStream(WebServerLocation.InProcess, "application/json;odata.metadata=none", "/Customers?$select=Name", typeof(CustomDataContext)); Stream stream = TestUtil.EnsureStreamWithSeek(resultStream); string actualText = new StreamReader(stream).ReadToEnd(); const string expectedSuccessText = @"{""value"":[{""Name"":""Customer 0""},{""Name"":""Customer 1""},{""Name"":""Customer 2""}]}"; Assert.AreEqual(expectedSuccessText, actualText); // now test that it is fails for the query option // $controlinfo was briefly used for controlling how much metadata a client wanted // in JSON-Light payloads. It was removed and replaced with a parameter in the media type. using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcessWcf)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers?$controlinfo=all"; request.Accept = "application/json;odata.metadata=minimal"; TestUtil.RunCatching(() => request.SendRequest()); Assert.AreEqual(400, request.ResponseStatusCode); } // now test that it is fails for 'odata-light' which was also eventually replaced. using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcessWcf)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; request.Accept = "application/json;odata.metadata=light"; TestUtil.RunCatching(() => request.SendRequest()); Assert.AreEqual(415, request.ResponseStatusCode); } // now test that it is fails with 'metadata' parameter which was later combined into the 'odata' parameter. using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcessWcf)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; request.Accept = "application/json;odata.metadata=minimal;metadata=all"; TestUtil.RunCatching(() => request.SendRequest()); Assert.AreEqual(415, request.ResponseStatusCode); } // Now test that it fails for an invalid type/subtype. using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcessWcf)) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers"; request.Accept = "fake/things;odata.metadata=minimal"; TestUtil.RunCatching(() => request.SendRequest()); Assert.AreEqual(415, request.ResponseStatusCode); } }
public void DbEntityValidationFailureProducesUsableMessage() { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = ContextType; request.ForceVerboseErrors = true; request.RequestContentType = UnitTestsUtil.AtomFormat; string uri = "/Elevators(2)"; XName elementName = XName.Get("SerialNumber", ODataNamespace); const string changedValue = "123456"; request.HttpMethod = "GET"; request.Accept = "application/atom+xml,application/xml"; request.RequestStream = null; request.RequestUriString = uri; request.SendRequest(); XDocument entry = request.GetResponseStreamAsXDocument(); XElement element = entry.Descendants(elementName).Single(); element.Value = changedValue; request.HttpMethod = "PATCH"; request.Accept = "application/atom+xml,application/xml"; request.RequestStream = IOUtil.CreateStream(entry.ToString(SaveOptions.DisableFormatting)); System.Net.WebException exception = TestUtil.RunCatching <System.Net.WebException>(() => request.SendRequest()); Assert.IsNotNull(exception, "Expected an exception, but none occurred."); Assert.IsNotNull(exception.InnerException, "Expected an inner exception, but found none"); Assert.AreEqual("The field SerialNumber must be a string with a minimum length of 5 and a maximum length of 5.", exception.InnerException.Message, "Didn't get the expected error message"); } }
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 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 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 CallbackSuccessQueryTest() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); List <string> requestUris = new List <string>() { "/Customers(1)/ID?$format=json&$callback=foo", "/Customers(1)/Orders/$ref?$format=json&$callback=foo", "/Customers/?$expand=Orders&$select=ID,Name,Orders&$top=3&$skip=1&$orderby=ID&$filter=Orders/any(p:p/ID%20ne%200)&$format=json&$callback=foo", "/Customers/?$format=json&$callback=foo&$filter=Orders/all(p:p/ID%20ge%200)&inlinecount=allpages", }; foreach (var requestUri in requestUris) { request.RequestUriString = requestUri; request.SendRequest(); var actualText = request.GetResponseStreamAsText(); Assert.IsTrue(actualText.StartsWith("foo(")); Assert.IsTrue(actualText.EndsWith(")")); Assert.IsTrue(request.ResponseHeaders["content-type"].StartsWith("text/javascript;odata.metadata=minimal;")); Assert.AreEqual(200, 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 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 GeometryAsOpenProperty_AtomWithTypeDeserialize() { // tests atom deserialization with m:type information var testCases = testData.Select(kvp => new { Type = SpatialTestUtil.GeometryTypeFor(kvp.Key), EdmName = SpatialTestUtil.GeometryEdmNameFor(kvp.Key), WktData = kvp.Value }); TestUtil.RunCombinations(testCases, (tcase) => { using (TestWebRequest request = CreateSpatialPropertyService(new Geometry[tcase.WktData.Length], tcase.Type, true, true).CreateForInProcessWcf()) { request.RequestUriString = "/Entities"; request.HttpMethod = "POST"; request.Accept = "application/atom+xml,application/xml"; request.RequestContentType = UnitTestsUtil.AtomFormat; request.SetRequestStreamAsText(AggregateAtomPayloadFromWkt(tcase.Type.Name, tcase.WktData, tcase.EdmName)); request.SendRequest(); var response = request.GetResponseStreamAsXDocument(); string rootXpath = "atom:entry/atom:content/adsm:properties/ads:" + tcase.Type.Name; UnitTestsUtil.VerifyXPaths(response, tcase.WktData.Select((v, i) => rootXpath + i + "[@adsm:type = '" + tcase.EdmName + "' and namespace-uri(*) = 'http://www.opengis.net/gml']").ToArray()); } }); }
public void RequestUriProcessorKeySpecialRealTest() { double[] doubleValues = new double[] { double.PositiveInfinity, double.NegativeInfinity, double.NaN }; string[] findText = new string[] { "INF", "-INF", "NaN" }; int textIndex = 0; // Index corresponds to the findText array CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("doubleValue", doubleValues)); using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(TypedCustomDataContext <TypedEntity <double, string> >); TypedCustomDataContext <TypedEntity <double, string> > .ClearHandlers(); TypedCustomDataContext <TypedEntity <double, string> > .ClearValues(); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { double doubleValue = (double)values["doubleValue"]; TypedCustomDataContext <TypedEntity <double, string> > .ValuesRequested += (sender, args) => { TypedCustomDataContext <TypedEntity <double, string> > s = (TypedCustomDataContext <TypedEntity <double, string> >)sender; TypedEntity <double, string> entity = new TypedEntity <double, string>(); entity.ID = doubleValue; s.SetValues(new object[] { entity }); }; try { Assert.IsTrue(textIndex < 3, "Out of bounds for test data array. Please check the doubleValues variable."); string searchValue = findText[textIndex]; // Increment textIndex for next test case ++textIndex; request.RequestUriString = "/Values"; request.Accept = "application/json"; request.SendRequest(); string responseText = request.GetResponseStreamAsText(); Assert.IsTrue(responseText.IndexOf(searchValue) > 0, String.Format("ID \"{0}\" expected in response.", searchValue)); Trace.WriteLine(String.Format("Found ID: {0}", searchValue)); // Finish the test suite after we've ran through all the strings. If we continue, the test suite continues and fails. // Researching into that is a expensive at this time. if (textIndex == 3) { return; } } finally { TypedCustomDataContext <TypedEntity <double, string> > .ClearHandlers(); TypedCustomDataContext <TypedEntity <double, string> > .ClearValues(); } }); } }
public void HttpContextServiceHostQueryStringTest() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers?$orderby="; request.SendRequest(); } }
public void RequestUriResourceKeyTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("TypeData", TypeData.Values), new Dimension("UseSmallCasing", new bool[] { true, false }), new Dimension("UseDoublePostfix", new bool[] { true, false })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { TypeData typeData = (TypeData)values["TypeData"]; if (!typeData.IsTypeSupportedAsKey) { return; } // TODO: when System.Uri handles '/' correctly, re-enable. if (typeData.ClrType == typeof(System.Xml.Linq.XElement)) { return; } Type entityType = typeof(TypedEntity <,>).MakeGenericType(typeData.ClrType, typeof(int)); CustomDataContextSetup setup = new CustomDataContextSetup(entityType); object idValue = typeData.NonNullValue; if (idValue is byte[]) { // idValue = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; return; } bool useSmallCasing = (bool)values["UseSmallCasing"]; bool useDoublePostFix = (bool)values["UseDoublePostfix"]; if (!(idValue is double) && useDoublePostFix) { return; } string valueAsString = TypeData.FormatForKey(idValue, useSmallCasing, useDoublePostFix); using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess)) { Trace.WriteLine("Running with value: [" + valueAsString + "] for [" + typeData.ToString() + "]"); setup.Id = idValue; setup.MemberValue = 1; request.DataServiceType = setup.DataServiceType; request.Accept = "application/json"; request.RequestUriString = "/Values(" + valueAsString + ")"; Trace.WriteLine("RequestUriString: " + request.RequestUriString); request.SendRequest(); request.GetResponseStreamAsText(); } setup.Cleanup(); }); }
public void OpenTypeUrlTest() { string[] queries = new string[] { "/Values", "/Values('100')/sampleValue2", "/Values('100')/sampleValue4", // no () after sample value 4, it's an array, gets rejected "/Values('100')/notfound", // This should be bad query since we expect to return 404 for open-properties not found }; string[] badQueries = new string[] { "/Values/sampleValue1", // no () after Values "/Values('100')/sampleValue4()", "/Values('100')/sampleValue4('101')", "/Values('100')/sampleValue4('101')/ID", "/Values('100')/sampleValue4(101)", // Since we don't detect types during runtime, this queries will fail "/Values('100')/sampleValue3/Identity/Name", "/Values('100')/sampleValue3/Identity", }; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(OpenTypeContextWithReflection <OpenElement>); int i = 0; using (StaticCallbackManager <PopulatingValuesEventArgs <OpenElement> > .RegisterStatic((sender, args) => { var o = new OpenElement(); o.ID = "100"; o.Properties.Add("sampleValue1", "abc"); o.Properties.Add("sampleValue2", 12345); args.Values.Add(o); })) { foreach (string query in queries) { i++; Trace.WriteLine(query); request.RequestUriString = query; request.SendRequest(); Trace.WriteLine(request.GetResponseStreamAsText()); } foreach (string query in badQueries) { i++; Trace.WriteLine(query); request.RequestUriString = query; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, true); } } } }
/// <summary> /// Create a TestWebRequest using <paramref name="dataServiceType"/> and <paramref name="uri"/>. /// Execute the request and extract the IQueryable generated from the service /// </summary> /// <param name="dataServiceType">The context type for the service</param> /// <param name="uri">The uri for this request</param> /// <returns>An IQueryable object representing the Queryable for this request</returns> public static IQueryable CreateRequestAndGetQueryable(Type dataServiceType, string uri) { TestUtil.ClearMetadataCache(); using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.ServiceType = typeof(ExpressionDataService <>).MakeGenericType(dataServiceType); request.RequestUriString = uri; request.SendRequest(); return(lastQueryable); } }
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); } }
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 void WebDataServiceReflectionNoLinqToSql() { // Verifies that no Linq to SQL-specific types appear in metadata. // Incorrect namespace always being defined as System.Data.Linq when you generated a ClientClassGeneration for a LinqToWorkspace uri using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(TypedCustomDataContext <AllTypes>); request.RequestUriString = "/$metadata"; request.SendRequest(); string text = request.GetResponseStreamAsText(); TestUtil.AssertContainsFalse(text, "System.Data"); } }
static void InitializeServiceAndDatabase(SqlConnection connection) { // Set up the service and issue a request - Code First will create a database based on the model using (TestWebRequest request = CreateTestWebRequest("/")) { request.Accept = "application/atom+xml,application/xml"; request.SendRequest(); XmlDocument response = request.GetResponseStreamAsXmlDocument(); TestUtil.AssertSelectNodes(response, "//app:collection[@href='Elevators']"); TestUtil.AssertSelectNodes(response, "//app:collection[@href='FloorCalls']"); TestUtil.AssertSelectNodes(response, "//app:collection[@href='ElevatorControlSystems']"); } }
public void RequestUriProcessorKeySpecialRealTest() { double[] doubleValues = new double[] { double.PositiveInfinity, double.NegativeInfinity, double.NaN }; CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("doubleValue", doubleValues)); using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(TypedCustomDataContext <TypedEntity <double, string> >); TypedCustomDataContext <TypedEntity <double, string> > .ClearHandlers(); TypedCustomDataContext <TypedEntity <double, string> > .ClearValues(); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { double doubleValue = (double)values["doubleValue"]; TypedCustomDataContext <TypedEntity <double, string> > .ValuesRequested += (sender, args) => { TypedCustomDataContext <TypedEntity <double, string> > s = (TypedCustomDataContext <TypedEntity <double, string> >)sender; TypedEntity <double, string> entity = new TypedEntity <double, string>(); entity.ID = doubleValue; s.SetValues(new object[] { entity }); }; try { request.RequestUriString = "/Values"; request.Accept = "application/atom+xml,application/xml"; request.SendRequest(); XmlDocument document = request.GetResponseStreamAsXmlDocument(); XmlElement element = TestUtil.AssertSelectSingleElement(document, "/atom:feed/atom:entry/atom:id"); Trace.WriteLine("Found ID: " + element.InnerText); request.FullRequestUriString = element.InnerText; Exception exception = TestUtil.RunCatching(request.SendRequest); // One NaN value won't match another except throug the use of the .IsNaN // method. It's probably OK to not support this. TestUtil.AssertExceptionExpected(exception, double.IsNaN(doubleValue)); string responseText = request.GetResponseStreamAsText(); Trace.WriteLine(responseText); } finally { TypedCustomDataContext <TypedEntity <double, string> > .ClearHandlers(); TypedCustomDataContext <TypedEntity <double, string> > .ClearValues(); } }); } }
public void SecurityCallbacksFilterTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("option", "$filter,$orderby".Split(','))); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { string option = (string)values["option"]; int callCount = 0; using (AstoriaUnitTests.Tests.UnitTestModule.AuthorizationTest.InitializationCallbackManager.RegisterStatic((s, e) => { e.Configuration.SetEntitySetAccessRule("*", EntitySetRights.All); })) using (StaticCallbackManager <AstoriaUnitTests.Tests.UnitTestModule.AuthorizationTest.ComposeQueryEventArgs> .RegisterStatic((s, e) => { System.Linq.Expressions.Expression <Func <Customer, bool> > notZero = c => c.ID != 0; e.Filter = notZero; callCount++; })) using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.ServiceType = typeof(AstoriaUnitTests.Tests.UnitTestModule.AuthorizationTest.WebDataServiceA); request.RequestUriString = "/Customers?" + ((option == "$filter") ? "$filter=BestFriend/ID%20gt%200" : "$orderby=BestFriend/ID%20desc"); request.Accept = "application/atom+xml,application/xml"; request.SendRequest(); var document = request.GetResponseStreamAsXmlDocument(); Assert.AreEqual(2, callCount, "Callback is called twice (once for URI, once for best friend."); // Customer with ID #2 has best friend with ID #1 and thus it's returned. TestUtil.AssertSelectSingleElement(document, "/atom:feed/atom:entry/atom:id[text()='http://host/Customers(2)']"); if (option == "$filter") { // Customer #0 is not returned because of the filter (on the segment), and // customer #1 is not returned because of the filter (on the navigation property). TestUtil.AssertSelectSingleElement(document, "/atom:feed[0 = count(//atom:id[text()='http://host/Customers(0)'])]"); TestUtil.AssertSelectSingleElement(document, "/atom:feed[0 = count(//atom:id[text()='http://host/Customers(1)'])]"); } else { // Customer #0 is not returned because of the filter (on the segment). TestUtil.AssertSelectSingleElement(document, "/atom:feed[0 = count(//atom:id[text()='http://host/Customers(0)'])]"); TestUtil.AssertSelectSingleElement(document, "/atom:feed[1 = count(//atom:id[text()='http://host/Customers(1)'])]"); } } }); }
private static void CompareIds(string uri, string uri1) { string xpath = "/atom:feed/atom:id"; using (CustomDataContext.CreateChangeScope()) using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = uri; request.Accept = "application/atom+xml,application/xml"; request.SendRequest(); XmlDocument document = request.GetResponseStreamAsXmlDocument(); string id = document.SelectSingleNode(xpath, TestUtil.TestNamespaceManager).InnerText; request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = uri1; request.SendRequest(); document = request.GetResponseStreamAsXmlDocument(); string id1 = document.SelectSingleNode(xpath, TestUtil.TestNamespaceManager).InnerText; Assert.AreEqual(id, id1); Assert.IsFalse(id.Contains("()")); } }
public void MultipleAssociationsToTheSameEntitySetResultInDistinctAssociationSetNames() { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.ServiceType = typeof(DistinctAssociationSetService); request.FullRequestUriString = "http://host/$metadata"; request.HttpMethod = "GET"; request.SendRequest(); string response = new StreamReader(request.GetResponseStream()).ReadToEnd(); //count the number of occurrances of ReferenceProductMetatdatas and VariableProductMetadatas, they should be equal. Regex referenceCountRegex = new Regex("ReferenceProduct_Metadatas"); Regex variableCountRegex = new Regex("VariableProduct_Metadatas"); referenceCountRegex.Matches(response).Count.Should().Be(variableCountRegex.Matches(response).Count); } }
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 + "])"); } }
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); } }
/// <summary>Using the specified TestWebRequest sends the batch as a request and parses the response back into the batch.</summary> /// <param name="request">The request to use for sending the batch.</param> public void SendRequest(TestWebRequest request) { this.WriteRequest(request); request.SendRequest(); this.ParseResponseFromRequest(request, true); }
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 + "])"); } }