[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 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 QueryWithBothMinimalAndFullMetadataShouldNotCauseDuplicateIdentities() { // Repro for: EntityDescriptor identity/links key order changes for json DataServiceContext using (TestUtil.MetadataCacheCleaner()) using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { // using the row-based context because it intentionally puts OrderDetail's key properties in non-alphabetical order in the OM. request.DataServiceType = typeof(CustomRowBasedContext); request.StartService(); DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); JsonLightTestUtil.ConfigureContextForJsonLight(ctx); ConfigureContextForSendingRequest2Verification(ctx); var firstOrderDetail = ctx.CreateQuery <OrderDetail>("OrderDetails").First(); var firstOrderDetailProjected = ctx.CreateQuery <OrderDetail>("OrderDetails").Select(od => new OrderDetail { Quantity = od.Quantity }).First(); Assert.IsNotNull(firstOrderDetail); Assert.IsNotNull(firstOrderDetailProjected); Assert.AreEqual(1, ctx.Entities.Count); } }
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 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 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 Dev10Type_ClientQueryTupleWithALinq() { using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf()) { web.DataServiceType = typeof(Dev10TypeDef.Dev10TypeEntitySet <Dev10TypeDef.EntityWithTupleProperty>); web.StartService(); string baseUri = web.BaseUri; DataServiceContext context = new DataServiceContext(new Uri(baseUri)); var query = from t in context.CreateQuery <Dev10TypeDef.EntityWithTupleProperty>("Entities") where t.ComplexTuple.Item1 == "value 1" select t; try { string queryUri = query.ToString(); Assert.Fail("Client ALINQ with Tuple failed to throw"); } catch (Exception ex) { Exception innerEx = ex; while (innerEx.InnerException != null) { innerEx = innerEx.InnerException; } Assert.AreEqual("The type 'System.Tuple`2[System.String,System.String]' is not supported by the client library.", innerEx.Message); } } }
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 static void RunEndToEndSmokeTestWithClient(Action <DataServiceContext> customize = null) { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(KeyAsSegmentService); request.StartService(); DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4) { UrlConventions = DataServiceUrlConventions.KeyAsSegment }; if (customize != null) { customize(ctx); } var customer = ctx.CreateQuery <Customer>("Customers").Where(c => c.ID == 0).Single(); var descriptor = ctx.GetEntityDescriptor(customer); var baseUri = request.ServiceRoot.AbsoluteUri; Assert.AreEqual(baseUri + "/Customers/0", descriptor.Identity.OriginalString); Assert.AreEqual(baseUri + "/Customers/0", descriptor.EditLink.OriginalString); Assert.AreEqual(baseUri + "/Customers/0/BestFriend/$ref", descriptor.LinkInfos[0].AssociationLink.OriginalString); Assert.AreEqual(baseUri + "/Customers/0/BestFriend", descriptor.LinkInfos[0].NavigationLink.OriginalString); Assert.AreEqual(baseUri + "/Customers/0/Orders/$ref", descriptor.LinkInfos[1].AssociationLink.OriginalString); Assert.AreEqual(baseUri + "/Customers/0/Orders", descriptor.LinkInfos[1].NavigationLink.OriginalString); } }
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); }); } }
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 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 Dev10Type_ClientDynamicExpand() { using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf()) { web.DataServiceType = typeof(Dev10TypeDef.Dev10TypeEntitySet_Expand); web.StartService(); string baseUri = web.BaseUri; DataServiceContext context = new DataServiceContext(new Uri(baseUri)); var query = context.CreateQuery <Dev10TypeDef.EntityWithDynamicNavigation>("Parents").Expand("Children"); try { var results = query.ToList(); Assert.Fail("Exception failed to be thrown."); } catch (Exception ex) { Exception innerEx = ex; while (innerEx.InnerException != null) { innerEx = innerEx.InnerException; } Assert.IsTrue(innerEx.Message.Contains("Internal Server Error. The type 'AstoriaUnitTests.Tests.UnitTestModule+Dev10TypeTests+EntityWithDynamicInterface' is not supported."), ex.InnerException.Message); } } }
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 static void ClassInitialize(TestContext context) { changeScope = EFFK.CustomObjectContextPOCOProxy.CreateChangeScope(); web = TestWebRequest.CreateForInProcessWcf(); web.DataServiceType = typeof(EFFK.CustomObjectContextPOCOProxy); OpenWebDataServiceHelper.ForceVerboseErrors = true; web.StartService(); }
public static void ClassInitialize(TestContext context) { TestUtil.ClearConfiguration(); request = (HttpBasedWebRequest)TestWebRequest.CreateForInProcessWcf(); request.ServiceType = typeof(OpenWebDataService <CustomDataContext>); request.StartService(); serviceRoot = request.ServiceRoot; }
public void HttpContextServiceHostQueryStringTest() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/Customers?$orderby="; request.SendRequest(); } }
private TestWebRequest SetupRequest() { var request = TestWebRequest.CreateForInProcessWcf(); request.DataServiceType = typeof(ModifyErrorMessageInHandleExceptionService); request.RequestUriString = "/ThisDoesNotExist"; request.RequestMaxVersion = "4.0"; return(request); }
[Ignore] // Remove Atom // [TestMethod] public void ResponseHeadersAndStreamExceptionTest() { // Execute a query using a variety of methods (including sync, async, batch) and verify the response headers and payloads using (PlaybackService.OverridingPlayback.Restore()) using (PlaybackService.ProcessRequestOverride.Restore()) using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.ServiceType = typeof(PlaybackService); request.StartService(); TestUtil.RunCombinations(((IEnumerable <QueryMode>)Enum.GetValues(typeof(QueryMode))), (queryMode) => { bool isBatchQuery = queryMode == QueryMode.BatchAsyncExecute || queryMode == QueryMode.BatchAsyncExecuteWithCallback || queryMode == QueryMode.BatchExecute; PlaybackService.ProcessRequestOverride.Value = (r) => { throw new InvalidOperationException("ResponseHeadersAndStreamExceptionTest -- Bad Request."); }; DataServiceContext context = new DataServiceContext(new Uri(request.BaseUri)); HttpTestHookConsumer testHookConsumer = new HttpTestHookConsumer(context, false); DataServiceQuery <Customer> query = context.CreateQuery <Customer>("Customers"); Exception ex = null; try { foreach (var o in DataServiceContextTestUtil.ExecuteQuery(context, query, queryMode)) { } } catch (Exception e) { ex = e; } // Verify response headers Assert.AreEqual(1, testHookConsumer.ResponseHeaders.Count, "Wrong number of response headers being tracked by the test hook."); Dictionary <string, string> actualResponseHeaders = testHookConsumer.ResponseHeaders[0]; Assert.AreEqual("InternalServerError", actualResponseHeaders["__HttpStatusCode"]); // Verify response stream Assert.AreEqual(1, testHookConsumer.ResponseWrappingStreams.Count, "Unexpected number of response streams tracked by the test hook."); string actualResponsePayload = testHookConsumer.ResponseWrappingStreams[0].GetLoggingStreamAsString(); if (queryMode == QueryMode.BatchExecute) { Assert.AreEqual("", actualResponsePayload, "In batch the client calls the hook to get the stream but never reads from it."); } else { TestUtil.AssertContains(actualResponsePayload, "System.InvalidOperationException: ResponseHeadersAndStreamExceptionTest -- Bad Request."); } // Sanity check on the count of request streams, but not verifying them here. That functionality is tested more fully in another test method. int expectedRequestStreamsCount = isBatchQuery ? 1 : 0; Assert.AreEqual(expectedRequestStreamsCount, testHookConsumer.RequestWrappingStreams.Count, "Unexpected number of request streams."); }); } }
/// <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); } }
public void CanOverloadUpdateRequestWithHeader() { foreach (var serviceType in Services) { using (CustomDataContext.CreateChangeScope()) { using (TestWebRequest webRequest = TestWebRequest.CreateForInProcessWcf()) { // get an existing customer before sending PUT requests webRequest.HttpMethod = "GET"; webRequest.ServiceType = serviceType; webRequest.RequestUriString = "/Customers(1)"; webRequest.Accept = UnitTestsUtil.JsonLightMimeType; TestUtil.RunCatching(webRequest.SendRequest); Assert.IsTrue(webRequest.ResponseContentType.ToLower().Contains(UnitTestsUtil.JsonLightMimeType.ToLower())); // all the subsequent requests are PUT requests with specified Accept and Content-Type headers webRequest.HttpMethod = "PUT"; webRequest.Accept = UnitTestsUtil.JsonLightMimeType; webRequest.RequestContentType = "application/json"; // update the customer and send the correct ETag in query string header - should succeed webRequest.RequestUriString = "/Customers(1)/Name?Override-If-Match=" + webRequest.ResponseETag; webRequest.IfMatch = "SomeBadValue"; webRequest.SetRequestStreamAsText("{\"value\": \"Name1\"}"); TestUtil.RunCatching(webRequest.SendRequest); Assert.AreEqual(204, webRequest.ResponseStatusCode); string eTag = webRequest.ResponseETag; // update the customer and send ETag with reversed guid in query string header - should fail // Length of a GUID is 36 string correctGuid = webRequest.ResponseETag.Substring(webRequest.ResponseETag.IndexOf('"') + 1, 36); string reversedGuid = string.Concat(correctGuid.ToArray().Reverse()); webRequest.RequestUriString = "/Customers(1)/Name?Override-If-Match=" + webRequest.ResponseETag.Replace(correctGuid, reversedGuid); webRequest.IfMatch = eTag; webRequest.SetRequestStreamAsText("{\"value\": \"Name2\"}"); TestUtil.RunCatching(webRequest.SendRequest); Assert.AreEqual(412, webRequest.ResponseStatusCode); // update the customer and send prefer header return=representation in query string - expect 200 webRequest.RequestUriString = "/Customers(1)/Name?Override-Prefer=return=representation"; webRequest.IfMatch = eTag; webRequest.SetRequestStreamAsText("{\"value\": \"Name3\"}"); TestUtil.RunCatching(webRequest.SendRequest); Assert.AreEqual(200, webRequest.ResponseStatusCode); Assert.IsTrue(webRequest.GetResponseStreamAsText().Contains("TheTest/$metadata#Customers(1)/Name\",\"value\":\"Name3\"")); } } } }
private static void RunNegativeActionTestWithAtom(TestCase testCase) { // These tests are specific to Atom and don't apply to JSON Light. // Any JSON Light negative cases are covered by ODL reader tests. See ODL tests OperationReaderJsonLightTests and ODataJsonLightDeserializerTests. using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) using (PlaybackService.ProcessRequestOverride.Restore()) { request.ServiceType = typeof(AstoriaUnitTests.Stubs.PlaybackService); request.StartService(); PlaybackService.ProcessRequestOverride.Value = (req) => { // These tests intentionally don't set the base URI of the context, so we need to also remove the xml:base attribute that is automatically // generated by the PayloadGenerator. Otherwise another parsing error will occur before we hit the actual errors we are trying to validate. string payload = PayloadGenerator.Generate(testCase.ResponsePayloadBuilder, ODataFormat.Atom); string xmlBaseAttribute = @"xml:base=""/"""; payload = payload.Remove(payload.IndexOf(xmlBaseAttribute), xmlBaseAttribute.Length); req.SetResponseStreamAsText(payload); req.ResponseHeaders.Add("Content-Type", "application/atom+xml"); req.SetResponseStatusCode(200); return(req); }; Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString); DataServiceContext ctx = new DataServiceContext(null, ODataProtocolVersion.V4); ctx.EnableAtom = true; QueryOperationResponse <CustomerEntity> qor = (QueryOperationResponse <CustomerEntity>)ctx.Execute <CustomerEntity>(uri); Assert.IsNotNull(qor); Assert.IsNull(qor.Error); IEnumerator <CustomerEntity> entities = qor.GetEnumerator(); Exception exception = AstoriaTest.TestUtil.RunCatching(delegate() { while (entities.MoveNext()) { CustomerEntity c = entities.Current; EntityDescriptor ed = ctx.GetEntityDescriptor(c); IEnumerable <OperationDescriptor> actualDescriptors = ed.OperationDescriptors; } }); Assert.IsNotNull(exception); Assert.AreEqual(testCase.ExpectedErrorMessage, exception.Message); } }
public void ErrorResponseContentTypeHasCharset() { // regression tests for these bugs : // [GQL Failure, ODataLib integration] Server does not write charset in content-type header on error responses // [GQL Failure, Astoria-ODataLib Integration] ContentType provided to DataService.HandleException does not match final header value in $batch 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 }), new Dimension("Accept", new string[] { "application/atom", UnitTestsUtil.JsonLightMimeType }), new Dimension("Charset", new string[] { null, Encoding.UTF8.WebName, "iso-8859-1" })); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { bool verbose = (bool)values["verbose"]; using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { int customerCount = (0xA0 / "Customer 1".Length) + 1; string accept = values["Accept"].ToString(); object charset = values["Charset"]; values[CustomDataContext.CustomerCountArgument] = customerCount; if (charset == null) { charset = Encoding.UTF8.WebName; } else { request.AcceptCharset = charset.ToString(); } request.Accept = accept; request.TestArguments = values; request.ForceVerboseErrors = verbose; request.DataServiceType = typeof(CustomDataContext); request.RequestUriString = "/NonExistantSet"; Exception exception = TestUtil.RunCatching(request.SendRequest); string responseType = string.Equals(accept, "application/atom") ? "application/xml" : UnitTestsUtil.JsonLightMimeType + ";odata.streaming=true;IEEE754Compatible=false"; string expectedContentType = string.Format("{0};charset={1}", responseType, charset.ToString()); Assert.IsNotNull(exception, "Expecting an exception, but no exception was thrown"); Assert.AreEqual(expectedContentType, request.ResponseContentType, true /*ignoreCase*/); } }); }
private void RunQueryTest(List <DollarFormatTestCase> testCases, string RequestMaxVersion = "4.0;") { using (TestWebRequest webRequest = TestWebRequest.CreateForInProcessWcf()) { webRequest.HttpMethod = "GET"; webRequest.DataServiceType = typeof(DollarFormatTestService); foreach (var testCase in testCases) { webRequest.RequestUriString = testCase.UriString; webRequest.RequestMaxVersion = RequestMaxVersion; TestUtil.RunCatching(webRequest.SendRequest); Assert.AreEqual(testCase.ExpectedStatusCode, webRequest.ResponseStatusCode); Assert.AreEqual(testCase.ExpectedContentType, webRequest.ResponseHeaders["Content-Type"]); } } }
public void SendMoreThan100RequestsInBatch() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); BatchWebRequest batchRequest = new BatchWebRequest(); for (int i = 0; i < 101; i++) { InMemoryWebRequest getRequest = new InMemoryWebRequest(); getRequest.RequestUriString = "Customers(1)"; batchRequest.Parts.Add(getRequest); } batchRequest.SendRequest(request); Assert.IsFalse(batchRequest.Parts.Any(p => p.ResponseStatusCode != 200), "All the requests should succeed"); } }
/// <summary> /// Runs a non-batch test over the the Services defined. /// </summary> /// <param name="configureRequest">Action to configure the request.</param> /// <param name="validateResponse">Action to validate the test results.</param> public static void RunTest(Action <TestWebRequest> configureRequest, Action <TestWebRequest> validateResponse) { foreach (var serviceType in Services) { using (TestWebRequest webRequest = TestWebRequest.CreateForInProcessWcf()) { // Default settings webRequest.HttpMethod = "GET"; webRequest.DataServiceType = serviceType; // Apply test's settings configureRequest(webRequest); TestUtil.RunCatching(webRequest.SendRequest); validateResponse(webRequest); } } }
public void VerifyODataLibIsUsedForWritingTopLevelErrors() { // Only ODL knows about json lite serialization, so we know ODL is being used if the json lite error was serialized correctly. const string expectedJsonLitePayload = @"{""error"":{""code"":"""",""message"":""Resource not found for the segment 'Customers'.""}}"; using (TestWebRequest r = TestWebRequest.CreateForInProcessWcf()) { r.DataServiceType = typeof(CustomDataContext); r.RequestUriString = "/Customers(-2345354)"; r.HttpMethod = "GET"; r.Accept = "application/json;odata.metadata=minimal"; TestUtil.RunCatching(() => r.SendRequest()); string responsePayload = r.GetResponseStreamAsText(); Assert.AreEqual(404, r.ResponseStatusCode); Assert.AreEqual(expectedJsonLitePayload, responsePayload); } }
public void CallbackOptionValueTest() { using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf()) { request.DataServiceType = typeof(CustomDataContext); Dictionary <string, string> testCases = new Dictionary <string, string>() { // empty callback option { "?$format=json&$callback=", string.Empty }, // example callback option values from JQuery and DataJS { "?$callback=parent.handleJSONP_0&$format=json", "parent.handleJSONP_0" }, { "?$callback=jQuery18209805240577502099_1348783118115&$format=json&_=1348783118119", "jQuery18209805240577502099_1348783118115" }, // callback option values in special character/format { "?$format=json&$callback=null", "null" }, { "?$callback=" + Uri.EscapeDataString("A string with characters :%*+,/.") + "&$format=json", "A string with characters :%*+,/." }, { "?$callback=" + "<script>$.getJSON(\"http://something.com\",function (data) {alert(data.value);});</script>" + "&$format=json", "<script>$.getJSON(\"http://something.com\",function (data) {alert(data.value);});</script>" }, }; foreach (var testCase in testCases) { request.RequestUriString = "/Customers(1)" + testCase.Key; request.SendRequest(); var actualText = request.GetResponseStreamAsText(); if (testCase.Value.Length == 0) { // We don't do JSONP for empty callback value Assert.IsTrue(actualText.StartsWith(testCase.Value + "{")); Assert.IsTrue(actualText.EndsWith("}")); Assert.IsTrue(request.ResponseHeaders["content-type"].StartsWith("application/json;odata.metadata=minimal;")); } else { Assert.IsTrue(actualText.StartsWith(testCase.Value + "({")); Assert.IsTrue(actualText.EndsWith("})")); Assert.IsTrue(request.ResponseHeaders["content-type"].StartsWith("text/javascript;odata.metadata=minimal;")); } Assert.AreEqual(200, request.ResponseStatusCode); } } }
private void QueryDev10TypeService <T>(bool expectException, string exceptionMessage) where T : new() { using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf()) { web.DataServiceType = typeof(Dev10TypeDef.Dev10TypeEntitySet <T>); web.StartService(); string baseUri = web.BaseUri; DataServiceContext context = new DataServiceContext(new Uri(baseUri)); try { var query = context.CreateQuery <T>("Entities"); var result = query.Execute(); Assert.IsFalse(expectException); Assert.AreEqual(result.Count(), 3); } catch (Exception ex) { // is exception expected? Assert.IsTrue(expectException, "exception was not expected"); if (!String.IsNullOrEmpty(exceptionMessage)) { Exception innerEx = ex; while (innerEx.InnerException != null) { innerEx = innerEx.InnerException; } if (exceptionMessage.StartsWith("Contains:")) { exceptionMessage = exceptionMessage.Substring(9); Assert.IsTrue(innerEx.Message.Contains(exceptionMessage), innerEx.Message); } else { Assert.AreEqual(ex.Message, exceptionMessage); } } } } }
public void SetDollarFormatInBuildingRequest() { 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", It will be enabled by finishing // "json", enable the json case by involving proper EDM model in DataServiceContext. "xml", }; string option = string.Empty; ctx.BuildingRequest += (sender, arg) => arg.RequestUri = new Uri(arg.RequestUri.AbsoluteUri + "?$format=" + option); foreach (string s in options) { try { option = s; ctx.Execute <Customer>(new Uri(web.ServiceRoot + "/Customers")); ctx.CreateQuery <Customer>("Customers"); // Assert.IsTrue(option == "json"); } catch (DataServiceQueryException e) { if (option == "xml") { TestUtil.AssertContains(e.InnerException.Message, "A supported MIME type could not be found that matches the acceptable MIME types for the request."); Assert.AreEqual(415, e.Response.StatusCode); } else { // Assert.AreEqual("atom", option); // Assert.AreEqual(DataServicesClientResourceUtil.GetString("DataServiceClientFormat_ValidServiceModelRequiredForAtom"), e.InnerException.Message); } } } } }