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."); } } }
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 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 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 WebDataServiceDanglingNavigationProperty() { // Verifies that navigation properties are appropriately rejected if they have // no AssociationSet for any one EntitySet. const string modelText = "Ns.ET1 = entitytype { ID1 int key; };" + "Ns.ET2 = entitytype { ID2 int key; };" + "AT1 = associationtype { end1 Ns.ET1 1; end2 Ns.ET2 *;};" + "ET1 = entitytype { navigation NP1 AT1 end1 Ns.ET2; };" + "ESa : Ns.ET1; ESb : Ns.ET2; ESc : Ns.ET1;" + // Entity sets "ASab : AT1 { end1 ESa; end2 ESb; };"; // Association set AdHocModel model = AdHocModel.ModelFromText(modelText); Assembly assembly = model.GenerateModelsAndAssembly("DanglingNavpropModel", false /* isReflectionProviderBased */); Type type = TestUtil.LoadDerivedTypeFromAssembly(assembly, typeof(System.Data.Objects.ObjectContext)); using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = type; request.RequestUriString = "/$metadata"; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, true); TestUtil.AssertExceptionStatusCode(exception, 500, "500 expected for dangling property."); } }
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 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 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 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 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 Projections_Batch() { using (TestUtil.MetadataCacheCleaner()) using (ocs.PopulateData.CreateTableAndPopulateData()) using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { TestUtil.RunCombinations( new Type[] { typeof(CustomDataContext), typeof(ocs.CustomObjectContext), typeof(CustomRowBasedContext), typeof(CustomRowBasedOpenTypesContext) }, CustomerSelects.Variations(2), (dataServiceType, selects) => { request.DataServiceType = dataServiceType; BatchWebRequest batchRequest = new BatchWebRequest(); foreach (var select in selects) { InMemoryWebRequest part = new InMemoryWebRequest(); part.Accept = "application/atom+xml,application/xml"; part.RequestUriString = "/Customers?$select=" + select.Select; batchRequest.Parts.Add(part); } batchRequest.SendRequest(request); for (int i = 0; i < selects.Length; i++) { UnitTestsUtil.VerifyXPathExists(UnitTestsUtil.GetResponseAsAtomXLinq(batchRequest.Parts[i]), selects[i].VerificationXPaths); } }); } }
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 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 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 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 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 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(); } }); } }
static TestWebRequest CreateTestWebRequest(string uriString) { TestWebRequest request = TestWebRequest.CreateForInProcess(); request.ForceVerboseErrors = true; request.DataServiceType = ContextType; request.RequestUriString = uriString; return(request); }
private static void Run(Action <TestWebRequest> runTest) { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) using (TestUtil.RestoreStaticValueOnDispose(typeof(BaseTestWebRequest), "HostInterfaceType")) { BaseTestWebRequest.HostInterfaceType = typeof(IDataServiceHost2); request.DataServiceType = typeof(RequestUriCustomizationService); runTest(request); } }
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); } } } }
public void OpenTypeOrderByTest() { string[][] queries = new string[][] { new string[] { "/Values?$orderby=sampleValue1", "abc", "ABC" }, new string[] { "/Values?$orderby=sampleValue1 desc", "ABC", "abc" }, new string[] { "/Values?$orderby=sampleValue1,sampleValue2", "abc", "ABC" }, new string[] { "/Values('101')/sampleValue4()?$orderby=ID", "101", "102" }, }; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(OpenTypeContextWithReflection <OpenElement>); using (StaticCallbackManager <PopulatingValuesEventArgs <OpenElement> > .RegisterStatic((sender, args) => { var o = new OpenElement(); o.ID = "101"; o.Properties.Add("sampleValue1", "abc"); o.Properties.Add("sampleValue2", 12345); o.Properties.Add("sampleValue3", true); args.Values.Add(o); o = new OpenElement(); o.Properties.Add("sampleValue1", "ABC"); o.Properties.Add("sampleValue2", 1); o.Properties.Add("sampleValue3", false); args.Values.Add(o); })) { int i = 0; foreach (string[] queryParts in queries) { string query = queryParts[0]; Trace.WriteLine("Running " + query); request.RequestUriString = query; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, i == queries.Length - 1); if (exception == null) { string response = request.GetResponseStreamAsText(); int firstOffset = response.IndexOf(queryParts[1]); int secondOffset = response.IndexOf(queryParts[2]); if (firstOffset >= secondOffset) { Assert.Fail( "For '" + query + "' the offset for " + queryParts[1] + " (" + firstOffset + ") should be less than " + "the offset for " + queryParts[2] + " (" + secondOffset + ") in '" + response + "'"); } } i++; } } } }
public void RequestQueryParserOperatorsPrimitives() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("Operator", OperatorData.Values), new Dimension("LeftType", TypeData.Values), new Dimension("RightType", TypeData.Values)); TypedCustomDataContext <AllTypes> .ClearValues(); TypedCustomDataContext <AllTypes> .ClearHandlers(); try { TypedCustomDataContext <AllTypes> .ValuesRequested += (x, y) => { ((TypedCustomDataContext <AllTypes>)x).SetValues(new object[] { new AllTypes() }); }; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(TypedCustomDataContext <AllTypes>); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { TypeData left = (TypeData)values["LeftType"]; TypeData right = (TypeData)values["RightType"]; if (!left.IsTypeSupported || !right.IsTypeSupported) { return; } // Big matrix. Let's cut it down by assuming that left and right ordering does not matter. if (Array.IndexOf(TypeData.Values, left) > Array.IndexOf(TypeData.Values, right)) { return; } string leftName = AllTypes.PropertyNameForType(left.ClrType); string rightName = AllTypes.PropertyNameForType(right.ClrType); OperatorData o = (OperatorData)values["Operator"]; string requestText = "/Values?$filter=" + leftName + "%20" + o.Token + "%20" + rightName; request.RequestUriString = requestText; Exception exception = TestUtil.RunCatching(request.SendRequest); TestUtil.AssertExceptionExpected(exception, o.IsEqualityComparison && !left.IsEqualityComparableTo(right), o.IsOrderingComparison && !left.IsOrderComparableTo(right)); }); } } finally { TypedCustomDataContext <AllTypes> .ClearValues(); TypedCustomDataContext <AllTypes> .ClearHandlers(); } }
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"); } }
private static void Run(Action <TestWebRequest> runTest) { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) using (TestUtil.RestoreStaticValueOnDispose(typeof(BaseTestWebRequest), "HostInterfaceType")) using (TestServiceHost.AllowServerToSerializeException.Restore()) { BaseTestWebRequest.HostInterfaceType = typeof(IDataServiceHost2); TestServiceHost.AllowServerToSerializeException.Value = true; request.DataServiceType = typeof(UseDefaultNamespaceForRootElementsService); runTest(request); } }
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(); } }); } }
private static void Run(Action <TestWebRequest> runTest, Type serviceType = null) { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) using (TestUtil.RestoreStaticValueOnDispose(typeof(BaseTestWebRequest), "HostInterfaceType")) using (TestServiceHost.AllowServerToSerializeException.Restore()) { TestServiceHost.AllowServerToSerializeException.Value = true; BaseTestWebRequest.HostInterfaceType = typeof(IDataServiceHost2); request.DataServiceType = serviceType ?? typeof(UriParserIntegrationTestServiceWithNoLimits); runTest(request); } }
public void DeleteWithDowncast() { string requestUriString = "/Entities/" + MostBaseTypeName + "('Derived')/" + EntitySetBaseTypeName + "/" + DerivedTypeName; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(SimpleInheritanceService); request.RequestUriString = requestUriString; request.HttpMethod = "DELETE"; TestUtil.RunCatching(request.SendRequest); Assert.AreEqual(204, 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 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)'])]"); } } }); }
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); } }