public void CleanupTest() { try { foreach (string server in new string[] { HomeServer, PartnerServer }) { PowerShell.InvokeBatchScript( string.Format("Get-AzureSqlDatabase -ServerName {0} " + "| where {{ $_.Name -ne 'master' }} " + "| Remove-AzureSqlDatabase -ServerName {0} -Force", server)); } } catch (Exception ex) { Console.WriteLine("Error cleaning up servers: {0}", ex.Message); } MockHttpServer.Dispose(); ExceptionManager.Dispose(); PowerShell.Dispose(); // Save the mock session results MockServerHelper.SaveDefaultSessionCollection(); }
public void TestTxSigner() { List <String> mnemonic = new List <String>(singleVector.Split(" ", StringSplitOptions.RemoveEmptyEntries)); // Create the network info NetworkInfo networkInfo = new NetworkInfo(bech32Hrp: localbech32Hrp, lcdUrl: localTestUrl); // Build a transaction MsgSend msg = new MsgSend( fromAddress: "cosmos1hafptm4zxy5nw8rd2pxyg83c5ls2v62tstzuv2", toAddress: "cosmos12lla7fg3hjd2zj6uvf4pqj7atx273klc487c5k", amount: new List <StdCoin> { new StdCoin(denom: "uatom", amount: "100") } ); // Fee StdFee fee = new StdFee( gas: "200000", amount: new List <StdCoin> { new StdCoin(denom: "uatom", amount: "250") } ); StdTx tx = TxBuilder.buildStdTx(stdMsgs: new List <StdMsg> { msg }, fee: fee); // Create a wallet Wallet wallet = Wallet.derive(mnemonic, networkInfo); // Verify Wallet Assert.AreEqual(wallet.networkInfo.bech32Hrp, networkInfo.bech32Hrp); Assert.AreEqual(wallet.networkInfo.lcdUrl, networkInfo.lcdUrl); // Build the mockup server var _server = new MockHttpServer(); // I need this in order to get the correct data out of the mock server Dictionary <String, Object> accResponse = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.AccountDataResponse); Dictionary <String, Object> NodeResponse = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.NodeInfoResponse); // Initialize Server Response _server .WithService(localTestUrl) .Api("auth/accounts/{wallettAddress}", accResponse) .Api("node_info", NodeResponse); // Link the client to the retrieval classes HttpClient client = new HttpClient(_server); AccountDataRetrieval.client = client; NodeInfoRetrieval.client = client; // Call without await to avoid marking test class as async StdTx signedTx = TxSigner.signStdTx(wallet: wallet, stdTx: tx).Result; Assert.AreEqual(signedTx.signatures.Count, 1); StdSignature signature = (signedTx.signatures.ToArray())[0]; Assert.AreEqual(signature.publicKey.type, "tendermint/PubKeySecp256k1"); Assert.AreEqual(signature.publicKey.value, "ArMO2T5FNKkeF2aAZY012p/cpa9+PqKqw2GcQRPhAn3w"); Assert.AreEqual(signature.value, "m2op4CCBa39fRZD91WiqtBLKbUQI+1OWsc1tJkpDg+8FYB4y51KahGn26MskVMpTJl5gToIC1pX26hLbW1Kxrg=="); }
async Task TestApiFunction(ApiTestSetup setup, bool withContent = true) { var expectedContent = new { message = "hello" }; const string handlerName = "handler_name"; const HttpStatusCode expectedStatusCode = HttpStatusCode.OK; const string expectedId = "23421"; var server = new MockHttpServer(); WithServiceClause withServiceClause = server.WithService("http://www.base.com/sub"); setup(withServiceClause, "user?id={id}", new [] { "PUT" }, expectedContent, expectedStatusCode, handlerName); HttpClient client = CreateClient(server); HttpResponseMessage response = await client.PutAsJsonAsync($"http://www.base.com/sub/user?id={expectedId}", new object()); Assert.Equal(expectedStatusCode, response.StatusCode); if (withContent) { string actualMessage = JsonConvert.DeserializeAnonymousType( await response.Content.ReadAsStringAsync(), expectedContent).message; Assert.Equal(expectedContent.message, actualMessage); } server[handlerName].VerifyHasBeenCalled(); server[handlerName].VerifyHasBeenCalled(1); server[handlerName].VerifyBindedParameter("id", expectedId); }
public void SqlDatabaseManagementErrorTest() { string serverRequestId = Guid.NewGuid().ToString(); string errorMessage = @"<Error xmlns=""http://schemas.microsoft.com/sqlazure/2010/12/""> <Code>40647</Code> <Message>Subscription '00000000-1111-2222-3333-444444444444' does not have the server 'server0001'.</Message> <Severity>16</Severity> <State>1</State> </Error>"; WebException exception = MockHttpServer.CreateWebException( HttpStatusCode.BadRequest, errorMessage, (context) => { context.Response.Headers.Add(Constants.RequestIdHeaderName, serverRequestId); }); string requestId; ErrorRecord errorRecord = SqlDatabaseExceptionHandler.RetrieveExceptionDetails( exception, out requestId); Assert.AreEqual(serverRequestId, requestId); Assert.AreEqual( @"Subscription '00000000-1111-2222-3333-444444444444' does not have the server 'server0001'. Error Code: 40647", errorRecord.Exception.Message); }
public async Task should_not_confuse_between_different_systems() { var server = new MockHttpServer(); server .WithService("http://service1.com") .Api("user", new { message = "from service 1" }) .Done() .WithService("http://service2.com") .Api("user", new { message = "from service 2" }) .Done(); HttpClient client = CreateClient(server); HttpResponseMessage responseSvc1 = await client.GetAsync("http://service1.com/user"); HttpResponseMessage responseSvc2 = await client.GetAsync("http://service2.com/user"); HttpResponseMessage responseSvc3 = await client.GetAsync("http://service-not-exist.com/user"); var template = new { message = default(string) }; Assert.Equal("from service 1", (await responseSvc1.ReadAs(template)).message); Assert.Equal("from service 2", (await responseSvc2.ReadAs(template)).message); Assert.Equal(HttpStatusCode.NotFound, responseSvc3.StatusCode); }
public async Task should_get_optional_query_parameters_of_uri() { var server = new MockHttpServer(); server .WithService("http://www.base.com") .Api( "user/{userId}/session/{sessionId}?p1={value1}&p2={value2}", "GET", _ => new { Parameter = _ }.AsResponse()); HttpClient client = CreateClient(server); HttpResponseMessage response = await client.GetAsync( "http://www.base.com/user/12/session/28000?p2=v2"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); string jsonString = await response.Content.ReadAsStringAsync(); var content = JsonConvert.DeserializeAnonymousType( jsonString, new { Parameter = default(Dictionary <string, object>) }); Assert.Equal(string.Empty, content.Parameter["value1"]); Assert.Equal("v2", content.Parameter["value2"]); }
public void ProcessBatchAsync_CallsRegisterForDispose() { // Arrange List<IDisposable> expectedResourcesForDisposal = new List<IDisposable>(); MockHttpServer server = new MockHttpServer(request => { var tmpContent = new StringContent(String.Empty); request.RegisterForDispose(tmpContent); expectedResourcesForDisposal.Add(tmpContent); return new HttpResponseMessage { Content = new StringContent(request.RequestUri.AbsoluteUri) }; }); UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server); HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new MultipartContent("mixed") // ChangeSet { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/")) } } }; batchRequest.SetConfiguration(new HttpConfiguration()); // Act var response = batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result; var resourcesForDisposal = batchRequest.GetResourcesForDisposal(); // Assert foreach (var expectedResource in expectedResourcesForDisposal) { Assert.Contains(expectedResource, resourcesForDisposal); } }
public void SqlDatabaseManagementErrorTest() { string serverRequestId = Guid.NewGuid().ToString(); string errorMessage = @"<Error xmlns=""http://schemas.microsoft.com/sqlazure/2010/12/""> <Code>40647</Code> <Message>Subscription '00000000-1111-2222-3333-444444444444' does not have the server 'server0001'.</Message> <Severity>16</Severity> <State>1</State> </Error>"; WebException exception = MockHttpServer.CreateWebException( HttpStatusCode.BadRequest, errorMessage, (context) => { context.Response.Headers.Add(Constants.RequestIdHeaderName, serverRequestId); }); string requestId; ErrorRecord errorRecord = SqlDatabaseExceptionHandler.RetrieveExceptionDetails( exception, out requestId); string expectedErrorDetails = string.Format( CultureInfo.InvariantCulture, Microsoft.WindowsAzure.Commands.SqlDatabase.Properties.Resources.DatabaseManagementErrorFormat, 40647, "Subscription '00000000-1111-2222-3333-444444444444' does not have the server 'server0001'."); Assert.AreEqual(serverRequestId, requestId); Assert.AreEqual(expectedErrorDetails, errorRecord.Exception.Message); }
public void NetworkQueryReturnsCorrectData() { const String localTestUrl = "http://example.com"; // Build the mockup server var _server = new MockHttpServer(); // I need this in order to get the correct data out of the mock server Dictionary <String, Object> nodeResponse = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.SentDocumentResponseJson); // Initialize Server Response _server .WithService(localTestUrl) .Api("", "GET", nodeResponse); // Link the client to the retrieval class Network HttpClient client = new HttpClient(_server); Network.client = client; // Test response JArray resultList = Network.queryChain(localTestUrl).Result as JArray; List <NetworkTestData> testDataList = resultList.Select(json => new NetworkTestData((JObject)json)).ToList(); Assert.IsTrue(testDataList.Count == 4); Assert.IsTrue("did:com:1zfhgwfgex8rc9t00pk6jm6xj6vx5cjr4ngy32v" == testDataList[0].sender); Assert.IsTrue("6a881ef0-04da-4524-b7ca-6e5e3b7e61dc" == testDataList[1].uuid); }
public async void should_get_request_conent_from_calling_history_even_if_original_request_has_been_disposed() { var server = new MockHttpServer(); server.WithService("http://www.base.com") .Api("login", "POST", HttpStatusCode.OK, "login"); var client = new HttpClient(server); var request = new HttpRequestMessage(HttpMethod.Post, "http://www.base.com/login") { Content = new StringContent( JsonConvert.SerializeObject(new { username = "******", password = "******" }), Encoding.UTF8, "application/json") }; HttpResponseMessage response = await client.SendAsync(request); response.Dispose(); request.Dispose(); var actualRequestContent = await server["login"].SingleOrDefaultRequestContentAsync( new { username = string.Empty, password = string.Empty }); Assert.Equal("n", actualRequestContent.username); Assert.Equal("p", actualRequestContent.password); }
static void MockTokenGenerator(ContainerBuilder builder, MockHttpServer mockHttpServer) { var mockdef = new Mock <ITokenGenerator>(); mockdef.Setup(m => m.GenerateToken()).Returns(() => SessionToken); builder.Register(_ => mockdef.Object).SingleInstance(); }
public void GetString() { using (MockHttpServer.ReturnJson(request => Task.FromResult <JToken>(new JValue("foo")))) { var client = HttpApiClient <EmitBasedClientTests.IGetString> .Create("http://localhost:8844/path", httpHandler : new WebRequestHttpHandler()); client.GetString().Wait(); } }
public async Task GetString() { using (MockHttpServer.ReturnJson(request => Task.FromResult <JToken>(new JValue("foo")))) { var client = HttpApiClient <IGetString> .Create("http://localhost:8844/path"); await client.GetString(); } }
public void ReflectValueNotAsync() { using (MockHttpServer.Json(x => x)) { var client = HttpApiClient <IReflectValue> .Create("http://localhost:8844/pathnotasync", httpHandler : new WebRequestHttpHandler()); var result = client.ReflectValueNotAsync("foo"); Assert.AreEqual("foo", result); } }
public async Task should_return_404_if_there_is_no_handler() { var server = new MockHttpServer(); HttpClient client = CreateClient(server); HttpResponseMessage response = await client.GetAsync("http://uri.does.not.exist"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.True(response.Content is StringContent); }
public async Task PostStringMultipart() { using (MockHttpServer.PostMultipartReturnJson(x => Task.FromResult <JToken>(((StringHttpBody)x.Data["value"].Body).Text))) { var client = HttpApiClient <IPostStringMultipart> .Create("http://localhost:8844/path"); var result = await client.PostString("foo"); Assert.AreEqual("foo", result); } }
public async Task ReflectValue() { using (MockHttpServer.Json(x => x)) { var client = HttpApiClient <IReflectValue> .Create("http://localhost:8844/path"); var result = await client.ReflectValue("foo"); Assert.AreEqual("foo", result); } }
public async Task RawResponseBody() { using (MockHttpServer.Json(x => x)) { var client = HttpApiClient <IRawResponseBody> .Create("http://localhost:8844/path"); var result = await client.GetString("foo"); Assert.AreEqual("foo", (string)((JsonHttpBody)result).Json); } }
public void Test1() { var server = new MockHttpServer(); var client = server.CreateClient(); var res = client.GetStringAsync("api/values").Result; string[] output = JsonConvert.DeserializeObject <string[]>(res); output.Should().ContainInOrder(new string[] { "value1", "value2" }); }
public async Task Override() { using (MockHttpServer.Json(x => x)) { var client = HttpApiClient <OverrideApi> .Create("http://localhost:8844"); var result = await client.ReflectString("foo"); Assert.AreEqual("foobargoat", result); } }
public async Task SingleArgumentAsObject() { using (MockHttpServer.Json(x => x["value"])) { var client = HttpApiClient <ISingleArgumentAsObject> .Create("http://localhost:8844/path"); var result = await client.GetString("foo"); Assert.AreEqual("foo", result); } }
public async Task FormNameOverride() { using (MockHttpServer.PostFormReturnJson(x => x.Values["val1"] + x.Values["val2"])) { var client = HttpApiClient <IFormNameOverride> .Create("http://localhost:8844/path"); var result = await client.GetString("foo", "bar"); Assert.AreEqual("foobar", result); } }
public async Task JsonNameOverride() { using (MockHttpServer.Json(x => (string)x["val1"] + x["val2"])) { var client = HttpApiClient <INameOverride> .Create("http://localhost:8844/path"); var result = await client.GetString("foo", "bar"); Assert.AreEqual("foobar", result); } }
public async Task RawRequestBody() { using (MockHttpServer.Json(x => x)) { var client = HttpApiClient <IRawRequestBody> .Create("http://localhost:8844/path"); var result = await client.GetString(new JsonHttpBody("foo")); Assert.AreEqual("foo", result); } }
public void SetupTest() { powershell = PowerShell.Create(); MockHttpServer.SetupCertificates(); UnitTestHelper.SetupUnitTestSubscription(powershell); serverName = SqlDatabaseTestSettings.Instance.ServerName; powershell.Runspace.SessionStateProxy.SetVariable("serverName", serverName); }
public async Task GetStringAbstract() { using (MockHttpServer.ReturnJson(request => Task.FromResult <JToken>(new JValue("foo")))) { var client = HttpApiClient <GetStringApi> .Create("http://localhost:8844/path"); var result = await client.GetString(); Assert.AreEqual("foo", result); } }
public async Task CustomizeInvocation() { using (MockHttpServer.ReturnJson(request => Task.FromResult <JToken>(new JValue("foo")))) { var client = HttpApiClient <CustomizeInvocationApi> .Create("http://localhost:8844/path"); var result = await client.PostString("foo"); Assert.AreEqual("foofoo", result); } }
public static void InitializeClass(TestContext context) { powershell = System.Management.Automation.PowerShell.Create(); MockHttpServer.SetupCertificates(); UnitTestHelper.SetupUnitTestSubscription(powershell); serverName = SqlDatabaseTestSettings.Instance.ServerName; powershell.Runspace.SessionStateProxy.SetVariable("serverName", serverName); }
public async Task InstrumentedResponse() { using (MockHttpServer.ReturnJson(request => request.Headers.Get("Test"))) { var client = HttpApiClient <InstrumentResponseClass> .Create("http://localhost:8844"); var result = await client.InstrumentedResponse(); Assert.AreEqual("foo", result); } }
public async Task ThrowsConnectionExceptionWhenServerIsNotUp() { using (var server = new MockHttpServer(8000, context => { })) { } using (var client = new DocmsApiClient("docms-client-1", "http://localhost:8000")) { var docClient = client.CreateDocumentClient(); await Assert.ThrowsExceptionAsync <ConnectionException>(() => docClient.GetEntriesAsync()); } }
public async Task PostForm() { using (MockHttpServer.PostFormReturnJson(x => Task.FromResult <JToken>(x.Values["value1"] + "|" + x.Values["value2"]))) { var client = HttpApiClient <IPostForm> .Create("http://localhost:8844/path"); var result = await client.PostForm("value&1", 5); Assert.AreEqual("value&1|5", result); } }
public void ExecuteRequestMessagesAsync_DisposesResponseInCaseOfException() { List<MockHttpResponseMessage> responses = new List<MockHttpResponseMessage>(); MockHttpServer server = new MockHttpServer(request => { if (request.Method == HttpMethod.Put) { throw new InvalidOperationException(); } var response = new MockHttpResponseMessage(); responses.Add(response); return response; }); DefaultODataBatchHandler batchHandler = new DefaultODataBatchHandler(server); ODataBatchRequestItem[] requests = new ODataBatchRequestItem[] { new OperationRequestItem(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new OperationRequestItem(new HttpRequestMessage(HttpMethod.Post, "http://example.com/")), new OperationRequestItem(new HttpRequestMessage(HttpMethod.Put, "http://example.com/")), }; Assert.Throws<InvalidOperationException>( () => batchHandler.ExecuteRequestMessagesAsync(requests, CancellationToken.None).Result); Assert.Equal(2, responses.Count); foreach (var response in responses) { Assert.True(response.IsDisposed); } }
public void ProcessBatchAsync_CallsInvokerForEachRequest() { // Arrange MockHttpServer server = new MockHttpServer(request => { string responseContent = request.RequestUri.AbsoluteUri; if (request.Content != null) { string content = request.Content.ReadAsStringAsync().Result; if (!String.IsNullOrEmpty(content)) { responseContent += "," + content; } } return new HttpResponseMessage { Content = new StringContent(responseContent) }; }); UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server); HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new MultipartContent("mixed") // ChangeSet { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values") { Content = new StringContent("foo") }) } } }; batchRequest.SetConfiguration(new HttpConfiguration()); // Act var response = batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result; // Assert var batchContent = Assert.IsType<ODataBatchContent>(response.Content); var batchResponses = batchContent.Responses.ToArray(); Assert.Equal(2, batchResponses.Length); Assert.Equal("http://example.com/", ((OperationResponseItem)batchResponses[0]).Response.Content.ReadAsStringAsync().Result); Assert.Equal("http://example.com/values,foo", ((ChangeSetResponseItem)batchResponses[1]).Responses.First().Content.ReadAsStringAsync().Result); }
public void ExecuteOperationAsync_CopiesPropertiesFromRequest_WithoutExcludedProperties() { MockHttpServer server = new MockHttpServer(request => { return new HttpResponseMessage { RequestMessage = request }; }); UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server); HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), } }; batchRequest.Properties.Add("foo", "bar"); batchRequest.SetRouteData(new HttpRouteData(new HttpRoute())); batchRequest.RegisterForDispose(new StringContent(String.Empty)); ODataMessageReader reader = batchRequest.Content .GetODataMessageReaderAsync(new ODataMessageReaderSettings { BaseUri = new Uri("http://example.com") }, CancellationToken.None) .Result; ODataBatchReader batchReader = reader.CreateODataBatchReader(); List<ODataBatchResponseItem> responses = new List<ODataBatchResponseItem>(); Guid batchId = Guid.NewGuid(); batchReader.Read(); var response = batchHandler.ExecuteOperationAsync(batchReader, Guid.NewGuid(), batchRequest, CancellationToken.None).Result; var operationResponse = ((OperationResponseItem)response).Response; var operationRequest = operationResponse.RequestMessage; Assert.Equal("bar", operationRequest.Properties["foo"]); Assert.Null(operationRequest.GetRouteData()); Assert.Same(operationRequest, operationRequest.GetUrlHelper().Request); Assert.Empty(operationRequest.GetResourcesForDisposal()); }
public void ExecuteChangeSetAsync_ReturnsSingleErrorResponse() { MockHttpServer server = new MockHttpServer(request => { if (request.Method == HttpMethod.Post) { return Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)); } return Task.FromResult(new HttpResponseMessage()); }); UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server); HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { new MultipartContent("mixed") // ChangeSet { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Put, "http://example.com/values")), ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")), ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Delete, "http://example.com/values")), } } }; ODataMessageReader reader = batchRequest.Content .GetODataMessageReaderAsync(new ODataMessageReaderSettings { BaseUri = new Uri("http://example.com") }, CancellationToken.None) .Result; ODataBatchReader batchReader = reader.CreateODataBatchReader(); var response = batchHandler.ExecuteChangeSetAsync(batchReader, Guid.NewGuid(), batchRequest, CancellationToken.None).Result; var changesetResponse = Assert.IsType<ChangeSetResponseItem>(response); Assert.Equal(1, changesetResponse.Responses.Count()); Assert.Equal(HttpStatusCode.BadRequest, changesetResponse.Responses.First().StatusCode); }
public void ProcessBatchAsync_ContinueOnError(bool enableContinueOnError) { // Arrange MockHttpServer server = new MockHttpServer(request => { string responseContent = request.RequestUri.AbsoluteUri; string content = ""; if (request.Content != null) { content = request.Content.ReadAsStringAsync().Result; if (!String.IsNullOrEmpty(content)) { responseContent += "," + content; } } HttpResponseMessage responseMessage = new HttpResponseMessage { Content = new StringContent(responseContent) }; if (content.Equals("foo")) { responseMessage.StatusCode = HttpStatusCode.BadRequest; } return responseMessage; }); UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server); HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new MultipartContent("mixed") // ChangeSet { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values") { Content = new StringContent("foo") }) }, ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values") { Content = new StringContent("bar") }), } }; var enableContinueOnErrorconfig = new HttpConfiguration(); enableContinueOnErrorconfig.EnableContinueOnErrorHeader(); batchRequest.SetConfiguration(enableContinueOnErrorconfig); HttpRequestMessage batchRequestWithPrefContinueOnError = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new MultipartContent("mixed") // ChangeSet { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values") { Content = new StringContent("foo") }) }, ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values") { Content = new StringContent("bar") }), } }; if (enableContinueOnError) { batchRequestWithPrefContinueOnError.SetConfiguration(enableContinueOnErrorconfig); batchRequestWithPrefContinueOnError.Headers.Add("prefer", "odata.continue-on-error"); } else { batchRequestWithPrefContinueOnError.SetConfiguration(new HttpConfiguration()); } // Act var response = batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result; var batchContent = Assert.IsType<ODataBatchContent>(response.Content); var batchResponses = batchContent.Responses.ToArray(); var responseWithPrefContinueOnError = batchHandler.ProcessBatchAsync(batchRequestWithPrefContinueOnError, CancellationToken.None).Result; var batchContentWithPrefContinueOnError = Assert.IsType<ODataBatchContent>(responseWithPrefContinueOnError.Content); var batchResponsesWithPrefContinueOnError = batchContentWithPrefContinueOnError.Responses.ToArray(); // Assert Assert.Equal(2, batchResponses.Length); Assert.Equal(3, batchResponsesWithPrefContinueOnError.Length); }
public void ProcessBatchAsync_DisposesResponseInCaseOfException() { // Arrange List<MockHttpResponseMessage> responses = new List<MockHttpResponseMessage>(); MockHttpServer server = new MockHttpServer(request => { if (request.Method == HttpMethod.Put) { throw new InvalidOperationException(); } var response = new MockHttpResponseMessage(); responses.Add(response); return response; }); UnbufferedODataBatchHandler batchHandler = new UnbufferedODataBatchHandler(server); HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://example.com/$batch") { Content = new MultipartContent("mixed") { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new MultipartContent("mixed") // ChangeSet { ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Post, "http://example.com/values")), ODataBatchRequestHelper.CreateODataRequestContent(new HttpRequestMessage(HttpMethod.Put, "http://example.com/values")) } } }; batchRequest.SetConfiguration(new HttpConfiguration()); // Act & Assert Assert.Throws<InvalidOperationException>( () => batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None).Result); Assert.Equal(2, responses.Count); foreach (var response in responses) { Assert.True(response.IsDisposed); } }
public void ExecuteRequestMessagesAsync_CallsInvokerForEachRequest() { MockHttpServer server = new MockHttpServer(request => { string responseContent = request.RequestUri.AbsoluteUri; if (request.Content != null) { string content = request.Content.ReadAsStringAsync().Result; if (!String.IsNullOrEmpty(content)) { responseContent += "," + content; } } return new HttpResponseMessage { Content = new StringContent(responseContent) }; }); DefaultODataBatchHandler batchHandler = new DefaultODataBatchHandler(server); ODataBatchRequestItem[] requests = new ODataBatchRequestItem[] { new OperationRequestItem(new HttpRequestMessage(HttpMethod.Get, "http://example.com/")), new ChangeSetRequestItem(new HttpRequestMessage[] { new HttpRequestMessage(HttpMethod.Post, "http://example.com/values") { Content = new StringContent("foo") } }) }; var responses = batchHandler.ExecuteRequestMessagesAsync(requests, CancellationToken.None).Result; Assert.Equal(2, responses.Count); Assert.Equal("http://example.com/", ((OperationResponseItem)responses[0]).Response.Content.ReadAsStringAsync().Result); Assert.Equal("http://example.com/values,foo", ((ChangeSetResponseItem)responses[1]).Responses.First().Content.ReadAsStringAsync().Result); }