public void Ctor_CreateWithHandlerDispose_Success() { using (var handler = new MockHandler(new MockTransportHandler())) { Assert.NotNull(handler.InnerHandler); } }
public void SendAsync_NullRequest_ThrowsArgumentNullException() { var transport = new MockTransportHandler(); var handler = new MockHandler(transport); Assert.Throws<ArgumentNullException>(() => { Task t = handler.TestSendAsync(null, CancellationToken.None); }); }
public void Ctor_CreateDispose_Success() { using (var handler = new MockHandler()) { Assert.Null(handler.InnerHandler); } }
public void SendAsync_WithoutSettingInnerHandlerCallMethod_ThrowsInvalidOperationException() { MockHandler handler = new MockHandler(); Assert.Throws<InvalidOperationException>(() => { Task t = handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None); }); }
public void Ctor_CreateDisposeAssign_ThrowsObjectDisposedException() { MockHandler handler = new MockHandler(); Assert.Null(handler.InnerHandler); handler.Dispose(); Assert.Throws<ObjectDisposedException>(() => handler.InnerHandler = new MockTransportHandler()); }
public async Task SendAsync_Request_HandlerInvoked() { var handler = new MockHandler(); var invoker = new HttpMessageInvoker(handler); HttpResponseMessage response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None); Assert.NotNull(response); Assert.Equal(1, handler.SendAsyncCount); }
public async Task SendAsync_InnerHandlerThrows_ThrowWithoutCallingProcessRequest() { var transport = new MockTransportHandler(true); // Throw if Send/SendAsync() is called. var handler = new MockHandler(transport); await Assert.ThrowsAsync<MockException>(() => handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None)); Assert.Equal(1, handler.ProcessRequestCount); Assert.Equal(0, handler.ProcessResponseCount); }
public async Task SendAsync_InnerHandlerReturnsNullResponse_ThrowInvalidOperationExceptionWithoutCallingProcessRequest() { var transport = new MockTransportHandler(() => { return null; }); var handler = new MockHandler(transport); await Assert.ThrowsAsync<InvalidOperationException>(() => handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None)); Assert.Equal(1, handler.ProcessRequestCount); Assert.Equal(0, handler.ProcessResponseCount); }
public async Task SendAsync_CallMethod_ProcessRequestAndProcessResponseCalled() { var transport = new MockTransportHandler(); var handler = new MockHandler(transport); await handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None); Assert.Equal(1, handler.ProcessRequestCount); Assert.Equal(1, handler.ProcessResponseCount); }
public void Dispose_DontDisposeHandler_HandlerNotDisposed() { var handler = new MockHandler(); var invoker = new HttpMessageInvoker(handler, false); invoker.Dispose(); Assert.Equal(0, handler.DisposeCount); Assert.Throws<ObjectDisposedException>(() => { Task t = invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None); }); Assert.Equal(0, handler.SendAsyncCount); }
public void StumpsHttpRequest_PopulatesCorrectly() { var mockHandler = new MockHandler(); mockHandler.StatusCode = 202; mockHandler.StatusDescription = "Bob"; mockHandler.UpdateBody(TestData.SampleTextResponse); mockHandler.ContentType = "bobs.type"; var startingEventCount = 0; using (var server = HttpHelper.CreateServer(mockHandler)) { server.RequestReceived += (o, i) => { var request = i.Context.Request; startingEventCount++; Assert.Greater(request.Headers.Count, 0); Assert.AreEqual("POST", request.HttpMethod); Assert.AreEqual(server.Port, request.LocalEndPoint.Port); Assert.AreEqual("1.1", request.ProtocolVersion); Assert.AreEqual("/", request.RawUrl); Assert.AreEqual(3, request.BodyLength); CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, request.GetBody()); }; server.StartListening(); var uri = new Uri("http://localhost:" + server.Port.ToString(CultureInfo.InvariantCulture) + "/"); var webRequest = WebRequest.Create(uri) as System.Net.HttpWebRequest; webRequest.ContentType = "Bobs.Content"; webRequest.Referer = "http://stumps-project.com/"; webRequest.UserAgent = "StumpsTestAgent"; webRequest.Method = "POST"; webRequest.ContentLength = 3; var stream = webRequest.GetRequestStream(); stream.Write(new byte[] { 1, 2, 3 }, 0, 3); stream.Close(); using (var response = (HttpWebResponse)webRequest.GetResponse()) { Assert.IsNotNull(response); } } Assert.AreEqual(startingEventCount, 1); }
public void ProcessAsyncRequest_WithValidRequest_RaisesServerEvents() { var mockHandler = new MockHandler(); mockHandler.StatusCode = 202; mockHandler.StatusDescription = "Bob"; mockHandler.UpdateBody(TestData.SampleTextResponse); var startingEventCount = 0; var finishingEventCount = 0; using (var server = HttpHelper.CreateServer(mockHandler)) { server.RequestReceived += (o, i) => { startingEventCount++; Assert.IsNotNull(o); Assert.IsNotNull(i); Assert.IsNotNull(i.Context); Assert.IsNotNull(i.Context.Request); Assert.IsNotNull(i.Context.Response); }; server.RequestFinished += (o, i) => { finishingEventCount++; Assert.IsNotNull(o); Assert.IsNotNull(i); Assert.IsNotNull(i.Context); Assert.IsNotNull(i.Context.Request); Assert.IsNotNull(i.Context.Response); }; server.StartListening(); var uri = new Uri("http://localhost:" + server.Port.ToString(CultureInfo.InvariantCulture) + "/"); var request = WebRequest.Create(uri); using (var response = (HttpWebResponse)request.GetResponse()) { Assert.IsNotNull(response); } } Assert.AreEqual(startingEventCount, 1); Assert.AreEqual(finishingEventCount, 1); }
public async Task SendAsync_SetInnerHandlerTwiceCallMethod_SecondInnerHandlerSendIsCalled() { var handler = new MockHandler(); var transport1 = new MockTransportHandler(); var transport2 = new MockTransportHandler(); handler.InnerHandler = transport1; handler.InnerHandler = transport2; HttpResponseMessage response = await handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None); Assert.NotNull(response); Assert.Equal(1, handler.SendAsyncCount); Assert.Equal(0, transport1.SendAsyncCount); Assert.Equal(1, transport2.SendAsyncCount); }
public async Task SendAsync_SetInnerHandlerCallMethod_InnerHandlerSendIsCalled() { var handler = new MockHandler(); var transport = new MockTransportHandler(); handler.InnerHandler = transport; HttpResponseMessage response = await handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None); Assert.NotNull(response); Assert.Equal(1, handler.SendAsyncCount); Assert.Equal(1, transport.SendAsyncCount); Assert.Throws<InvalidOperationException>(() => handler.InnerHandler = transport); Assert.Equal(transport, handler.InnerHandler); }
public void TestDatagramRecycler() { int port = 1024; ExpiringSessionRecycler recycler = new ExpiringSessionRecycler(1, 1); MockHandler acceptorHandler = new MockHandler(); MockHandler connectorHandler = new MockHandler(); acceptor.Handler = acceptorHandler; acceptor.SessionRecycler = recycler; acceptor.Bind(new IPEndPoint(IPAddress.Loopback, port)); try { connector.Handler = connectorHandler; IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, port)); future.Await(); // Write whatever to trigger the acceptor. future.Session.Write(IoBuffer.Allocate(1)).Await(); // Close the client-side connection. // This doesn't mean that the acceptor-side connection is also closed. // The life cycle of the acceptor-side connection is managed by the recycler. future.Session.Close(true); future.Session.CloseFuture.Await(); Assert.IsTrue(future.Session.CloseFuture.Closed); // Wait until the acceptor-side connection is closed. while (acceptorHandler.session == null) { Thread.Yield(); } acceptorHandler.session.CloseFuture.Await(3000); // Is it closed? Assert.IsTrue(acceptorHandler.session.CloseFuture.Closed); Thread.Sleep(1000); Assert.AreEqual("CROPSECL", connectorHandler.result.ToString()); Assert.AreEqual("CROPRECL", acceptorHandler.result.ToString()); } finally { acceptor.Unbind(); } }
public void ResolveAndRelease() { InstanceHandlerTracker tracker = new InstanceHandlerTracker(); MockHandler handler = new MockHandler(); object instance = tracker.Resolve( handler ); Assert( handler.Resolved ); AssertNotNull( instance ); Assert( tracker.IsOwner( instance ) ); Assert( !tracker.IsOwner( new object() ) ); tracker.Release( new object() ); Assert( !handler.Released ); tracker.Release( instance ); Assert( handler.Released ); }
public void StumpsHttpResponse_PopulatesCorrectly() { var mockHandler = new MockHandler(); mockHandler.StatusCode = 202; mockHandler.StatusDescription = "Bob"; mockHandler.UpdateBody(TestData.SampleTextResponse); mockHandler.AddHeader("X-Stumps", "V1"); var requestFinishedEvent = new AutoResetEvent(false); using (var server = HttpHelper.CreateServer(mockHandler)) { server.RequestFinished += (o, i) => { var response = i.Context.Response; Assert.IsNotNull(response.Headers); Assert.Greater(response.Headers.Count, 0); Assert.AreEqual(response.Headers["X-Stumps"], "V1"); requestFinishedEvent.Set(); }; server.StartListening(); var uri = new Uri("http://localhost:" + server.Port.ToString(CultureInfo.InvariantCulture) + "/"); var request = WebRequest.Create(uri); using (var response = (HttpWebResponse)request.GetResponse()) { Assert.IsNotNull(response); } } var requestFinished = requestFinishedEvent.WaitOne(1000); Assert.IsTrue(requestFinished); }
public void StumpsHttpResponse_PopulatesCorrectly() { var mockHandler = new MockHandler(); mockHandler.StatusCode = 202; mockHandler.StatusDescription = "Bob"; mockHandler.UpdateBody(TestData.SampleTextResponse); mockHandler.AddHeader("X-Stumps", "V1"); var finishingEventCount = 0; using (var server = HttpHelper.CreateServer(mockHandler)) { server.RequestFinished += (o, i) => { var response = i.Context.Response; finishingEventCount++; Assert.IsNotNull(response.Headers); Assert.Greater(response.Headers.Count, 0); Assert.AreEqual(response.Headers["X-Stumps"], "V1"); }; server.StartListening(); var uri = new Uri("http://localhost:" + server.Port.ToString(CultureInfo.InvariantCulture) + "/"); var request = WebRequest.Create(uri); using (var response = (HttpWebResponse)request.GetResponse()) { Assert.IsNotNull(response); } } Assert.AreEqual(finishingEventCount, 1); }
public async Task GetAsyncItems_ThreePagesOfItems_WithAuth_WhenItemsReturned() { // Arrange var page1 = CreatePageOfJsonItems(5, 10, new Uri($"{tableEndpoint}?page=2")); var page2 = CreatePageOfJsonItems(5, 10, new Uri($"{tableEndpoint}?page=3")); MockHandler.AddResponse(HttpStatusCode.OK, new Page <JObject>()); // Act var items = await GetAllItems(authTable, 10); // Assert Assert.Equal(3, MockHandler.Requests.Count); AssertRequest(MockHandler.Requests[0], HttpMethod.Get, tableEndpoint); AssertEx.HasHeader(MockHandler.Requests[0].Headers, "X-ZUMO-AUTH", ValidAuthenticationToken.Token); AssertRequest(MockHandler.Requests[1], HttpMethod.Get, $"{tableEndpoint}?page=2"); AssertEx.HasHeader(MockHandler.Requests[1].Headers, "X-ZUMO-AUTH", ValidAuthenticationToken.Token); AssertRequest(MockHandler.Requests[2], HttpMethod.Get, $"{tableEndpoint}?page=3"); AssertEx.HasHeader(MockHandler.Requests[2].Headers, "X-ZUMO-AUTH", ValidAuthenticationToken.Token); Assert.Equal(10, items.Count); AssertEx.SequenceEqual(page1.Items.ToList(), items.Take(5).ToList()); AssertEx.SequenceEqual(page2.Items.ToList(), items.Skip(5).Take(5).ToList()); }
public async Task DeleteItemAsync_FormulatesCorrectResponse(bool hasPrecondition) { // Arrange MockHandler.AddResponse(HttpStatusCode.NoContent); var item = new IdEntity { Id = sId, Version = hasPrecondition ? "etag" : null }; // Act await table.DeleteItemAsync(item).ConfigureAwait(false); // Assert var request = AssertSingleRequest(HttpMethod.Delete, expectedEndpoint); if (hasPrecondition) { AssertEx.HasHeader(request.Headers, "If-Match", "\"etag\""); } else { Assert.False(request.Headers.Contains("If-Match")); } }
public void be_planned_if_trainner_available_for_session() { // given var trainingId = Guid.NewGuid(); var trainerId = Guid.NewGuid(); var dispatcher = new EventDispatcher(); var mockHandler = new MockHandler <TrainerAssigned, SessionPlanned>(); dispatcher.Register(mockHandler); var eventStore = new FakeEventStore(); eventStore.Save(new TrainerCreated(trainerId, 1, "BOUDOUX", "Aurelien", "*****@*****.**")); var eventBus = new EventBus(dispatcher, eventStore); // when new PlanSession(eventBus).Execute(trainingId, new DateTime(2018, 1, 1), 5, 10, null, trainerId); // then mockHandler.AllEvents.Should() .Contain(new TrainerAssigned(Guid.Empty, 0, new DateTime(2018, 1, 1), 5)).And .Contain(new SessionPlanned(Guid.Empty, 0, trainingId, new DateTime(2018, 1, 1), 5, 10, null, trainerId)); }
public async Task AddOutgoingMessageHeadersToOutgoingHttpRequests() { using (var innerHandler = new MockHandler()) { using (var handler = new MessageHeaderFlowHttpMessageHandler(innerHandler, new OutgoingHeaderProviders(new[] { new Provider() }))) { using (var client = new HttpClient(handler)) { using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri("http://hello.com"))) { using (await client .SendAsync(requestMessage) .ConfigureAwait(false)) { } } Assert.IsTrue( innerHandler.CapturedRequest.Headers.GetValues("Hello").Single() == "World"); } } } }
public void Test_DeleteAccount() { //Arrange MockHandler mock = new MockHandler(); mock.SetTempUsername(null, "Jan"); User user = new User() { Username = "******" }; mock.Users = new List <User>() { user }; HomeController cont = new HomeController(null, mock); //Act bool falseResult = cont.DeleteAccount(); //Assert Assert.False(falseResult); }
public void SQLPrinterReader_Success() { var logger = new MockLogger(); var collector = new MockCollector(logger); var sqlReader = new MockSQLReader(); var reader = new SQLPrinterReader(sqlReader, logger, collector); var handler = new MockHandler(); var config = new EndPointConfiguration() { Id = "2", Password = "******", User = "******", }; config.Properties.Add("ServerName", "localhost"); config.Properties.Add("Database", "MdmPrinter"); config.Properties.Add("SqlCommand", "SELECT * FROM PRINTER"); config.Properties.Add("Top", "100"); reader.Configure("1", config, handler); reader.Run(new Dictionary <string, string>()).Wait(); collector.GetTotalEventCount().Should().Be(1); }
public void TestAcceptorFilterChain() { Int32 port = 1024; IoFilter mockFilter = new MockFilter(); IoHandler mockHandler = new MockHandler(); acceptor.FilterChain.AddLast("mock", mockFilter); acceptor.Handler = mockHandler; acceptor.Bind(new IPEndPoint(IPAddress.Loopback, port)); try { IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, port)); future.Await(); IWriteFuture writeFuture = future.Session.Write(IoBuffer.Allocate(16).PutInt32(0).Flip()); writeFuture.Await(); Assert.IsTrue(writeFuture.Written); future.Session.Close(true); for (int i = 0; i < 30; i++) { if (result.Length == 2) { break; } Thread.Sleep(100); } Assert.AreEqual("FH", result); } finally { acceptor.Unbind(); } }
public async Task PushItemsAsync_SingleTable_HandlesDeleteOperation_Conflict() { await table.ServiceClient.InitializeOfflineStoreAsync(); var item = new ClientMovie { Id = Guid.NewGuid().ToString(), Version = "1" }; var conflictItem = new ClientMovie { Id = item.Id, Version = "2" }; var instance = (JObject)table.ServiceClient.Serializer.Serialize(item); store.Upsert("movies", new[] { instance }); MockHandler.AddResponse(HttpStatusCode.Conflict, conflictItem); await table.DeleteItemAsync(instance); var ex = await Assert.ThrowsAsync <PushFailedException>(() => table.PushItemsAsync()); Assert.Single(MockHandler.Requests); var request = MockHandler.Requests[0]; Assert.Equal(HttpMethod.Delete, request.Method); Assert.Equal($"/tables/movies/{item.Id}", request.RequestUri.PathAndQuery); Assert.Equal(PushStatus.Complete, ex.PushResult.Status); Assert.Single(ex.PushResult.Errors); Assert.Equal("movies", ex.PushResult.Errors.First().TableName); Assert.Equal(item.Id, ex.PushResult.Errors.First().Item.Value <string>("id")); Assert.Single(store.TableMap[SystemTables.OperationsQueue]); var op = TableOperation.Deserialize(store.TableMap[SystemTables.OperationsQueue].Values.First()); Assert.Equal(TableOperationState.Failed, op.State); Assert.Single(store.TableMap[SystemTables.SyncErrors]); }
public ConveyancingMatterTests(WebContainerFixture containerFixture, ITestOutputHelper output) { _containerFixture = containerFixture; _output = output; _handler = A.Fake <MockHandler>(opt => opt.CallsBaseMethods()); A.CallTo(() => _handler.SendAsync(HttpMethod.Get, "/api/rest/actions?id_eq=1&include=actionType,division,division.participant")) .ReturnsLazily(() => Success(EmbeddedResource.Read("ResponseData.get-single-action.json"))); A.CallTo(() => _handler.SendAsync(HttpMethod.Get, "/api/rest/actions?id_in=1,7")) .ReturnsLazily(() => Success(EmbeddedResource.Read("ResponseData.list-multiple-actions.json"))); A.CallTo(() => _handler.SendAsync(HttpMethod.Get, "/api/rest/datacollectionrecordvalues?action=1" + "&dataCollectionRecord[dataCollection][name_in]=property,convdet,keydates" + "&dataCollectionField[name_in]=titleref,lotno,planno,plantype,smtdateonly,smttime,purprice,ConveyType" + "&include=dataCollectionField,dataCollection")) .ReturnsLazily(() => Success(EmbeddedResource.Read("ResponseData.get-data-collection-record-values.json"))); A.CallTo(() => _handler.SendAsync(HttpMethod.Get, "/api/rest/participants")) .ReturnsLazily(() => Success(EmbeddedResource.Read("ResponseData.list-participants.json"))); A.CallTo(() => _handler.SendAsync(HttpMethod.Get, "/api/rest/actionparticipants?action=1&include=participant,participantType")) .ReturnsLazily(() => Success(EmbeddedResource.Read("ResponseData.list-actionparticipants.json"))); A.CallTo(() => _handler.SendAsync(HttpMethod.Post, "/api/rest/v2/workspace")) .ReturnsLazily(() => Success(EmbeddedResource.Read("ResponseData.create-workspace-success.xml"))); }
public void TestSendRequestGetErrorResponseObject() { RequestPostObject rpo = new RequestPostObject(); MockHandler.AddFakeResponse( new RestUrlBuilder(Url, rpo), HttpStatusCode.Unauthorized, "{\"ErrorMessage\":\"ErrorMessageValue\"}" ); try { ResultObject result = SendRequest <ResultObject, RequestPostObject, ErrorResultObject>(rpo); Assert.Fail("Error Response Exception didn't get thrown."); } catch (RestErrorResponseException e) { Assert.IsTrue(e.Error is ErrorResultObject); ErrorResultObject errorObject = (ErrorResultObject)e.Error; Assert.AreEqual <string>("ErrorMessageValue", errorObject.ErrorMessage); } }
public async Task MockDefaultNo524RetryTest() { HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = (HttpStatusCode)524, }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig clientConfig = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; RequestConfig requestConfig = new RequestConfig(); List <IFunction> contentBlock = new List <IFunction> { new ApiSessionCreate() }; RequestHandler requestHandler = new RequestHandler(clientConfig, requestConfig); var ex = await Record.ExceptionAsync(() => requestHandler.ExecuteOnline(contentBlock)); Assert.IsType <HttpRequestException>(ex); Assert.Equal("Response status code does not indicate success: 524 ().", ex.Message); }
public void GetMockHandlerTest() { HttpResponseMessage mockResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse, }; MockHandler mockHandler = new MockHandler(mockResponses); SdkConfig config = new SdkConfig() { SessionId = "faKEsesSiOnId..", EndpointUrl = "https://p1.intacct.com/ia/xml/xmlgw.phtml", MockHandler = mockHandler, }; SessionCredentials sessionCreds = new SessionCredentials(config, senderCreds); Assert.IsInstanceOfType(sessionCreds.MockHandler, typeof(MockHandler)); }
public void be_planned_if_location_available_for_session() { // given var trainingId = Guid.NewGuid(); var locationId = Guid.NewGuid(); var dispatcher = new EventDispatcher(); var mockHandler = new MockHandler <LocationAssigned, SessionPlanned>(); dispatcher.Register(mockHandler); var eventStore = new FakeEventStore(); eventStore.Save(new LocationCreated(locationId, 1, "Paris", "test", 5)); var eventBus = new EventBus(dispatcher, eventStore); // when new PlanSession(eventBus).Execute(trainingId, new DateTime(2018, 1, 1), 5, 10, locationId, null); // then mockHandler.AllEvents.Should() .Contain(new LocationAssigned(Guid.Empty, 0, new DateTime(2018, 1, 1), 5)).And .Contain(new SessionPlanned(Guid.Empty, 0, trainingId, new DateTime(2018, 1, 1), 5, 10, locationId, null)); }
public async Task SendAsync_CallMethod_InnerHandlerSendAsyncIsCalled() { var transport = new MockTransportHandler(); var handler = new MockHandler(transport); await handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None); Assert.Equal(1, handler.SendAsyncCount); Assert.Equal(1, transport.SendAsyncCount); }
public async Task SendAsync_ProcessRequestThrows_ThrowWithoutCallingProcessRequestNorInnerHandler() { var transport = new MockTransportHandler(); // ProcessRequest() throws exception. var handler = new MockHandler(transport, true, () => { throw new MockException(); }); // Note that ProcessRequest() is called by SendAsync(). However, the exception is not thrown // by SendAsync(). Instead, the returned Task is marked as faulted and contains the exception. await Assert.ThrowsAsync<MockException>(() => handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None)); Assert.Equal(0, transport.SendAsyncCount); Assert.Equal(1, handler.ProcessRequestCount); Assert.Equal(0, handler.ProcessResponseCount); }
public async Task FromSessionCredentialsUsingEnvironmentSenderTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getSession</function> <controlid>testControlId</controlid> <data> <api> <sessionid>fAkESesSiOnId..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); Environment.SetEnvironmentVariable("INTACCT_SENDER_ID", "envsender"); Environment.SetEnvironmentVariable("INTACCT_SENDER_PASSWORD", "envpass"); ClientConfig config = new ClientConfig() { SessionId = "fAkESesSiOnId..", EndpointUrl = "https://unittest.intacct.com/ia/xml/xmlgw.phtml", MockHandler = mockHandler, }; ClientConfig sessionCreds = await SessionProvider.Factory(config); Assert.Equal("fAkESesSiOnId..", sessionCreds.SessionId); Assert.Equal("https://unittest.intacct.com/ia/xml/xmlgw.phtml", sessionCreds.EndpointUrl); Assert.Equal("envsender", sessionCreds.SenderId); Assert.Equal("envpass", sessionCreds.SenderPassword); Environment.SetEnvironmentVariable("INTACCT_SENDER_ID", null); Environment.SetEnvironmentVariable("INTACCT_SENDER_PASSWORD", null); }
public void SendAsync_Disposed_Throws() { var transport = new MockTransportHandler(); var handler = new MockHandler(transport); handler.Dispose(); Assert.Throws<ObjectDisposedException>(() => { Task t = handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None); }); Assert.Throws<ObjectDisposedException>(() => handler.InnerHandler = new MockHandler()); Assert.Equal(transport, handler.InnerHandler); }
public void Ctor_SetNullInnerHandler_ThrowsArgumentNullException() { MockHandler handler = new MockHandler(); Assert.Throws<ArgumentNullException>(() => handler.InnerHandler = null); }
public void Dispose_CallDisposeMultipleTimes_OverriddenDisposeMethodCalled() { var innerHandler = new MockTransportHandler(); var handler = new MockHandler(innerHandler); handler.Dispose(); handler.Dispose(); handler.Dispose(); Assert.Equal(3, handler.DisposeCount); Assert.Equal(1, innerHandler.DisposeCount); }
public async Task MockExecuteOfflineWithSessionCredsTest() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <response> <acknowledgement> <status>success</status> </acknowledgement> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>requestUnitTest</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> </response>"; HttpResponseMessage mockResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse, }; MockHandler mockHandler = new MockHandler(mockResponses); var guid = Guid.NewGuid().ToString(); MemoryTarget target = new MemoryTarget { Name = guid, Layout = "${message}" }; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); ClientConfig clientConfig = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, Logger = LogManager.GetLogger(guid), }; RequestConfig requestConfig = new RequestConfig() { ControlId = "requestUnitTest", PolicyId = "policyid123", }; List <IFunction> contentBlock = new List <IFunction> { new ApiSessionCreate() }; RequestHandler requestHandler = new RequestHandler(clientConfig, requestConfig); OfflineResponse response = await requestHandler.ExecuteOffline(contentBlock); Assert.True(true); // TODO fix this test from randomly failing //Assert.Contains("Offline execution sent to Intacct using Session-based credentials.", target.Logs[0]); }
public async Task MockExecuteWithDebugLoggerTest() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse, }; MockHandler mockHandler = new MockHandler(mockResponses); var guid = Guid.NewGuid().ToString(); MemoryTarget target = new MemoryTarget { Name = guid, Layout = "${message}" }; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); ClientConfig clientConfig = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, Logger = LogManager.GetLogger(guid), }; RequestConfig requestConfig = new RequestConfig(); List <IFunction> contentBlock = new List <IFunction> { new ApiSessionCreate() }; RequestHandler requestHandler = new RequestHandler(clientConfig, requestConfig); OnlineResponse response = await requestHandler.ExecuteOnline(contentBlock); // Check for the user agent Assert.True(true); // TODO fix this test from randomly failing //Assert.Contains("intacct-api-net-client/", target.Logs[0]); }
public async Task MockDefaultRetryFailureTest() { HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, }; HttpResponseMessage mockResponse2 = new HttpResponseMessage() { StatusCode = HttpStatusCode.NotImplemented, }; HttpResponseMessage mockResponse3 = new HttpResponseMessage() { StatusCode = HttpStatusCode.BadGateway, }; HttpResponseMessage mockResponse4 = new HttpResponseMessage() { StatusCode = HttpStatusCode.GatewayTimeout, }; HttpResponseMessage mockResponse5 = new HttpResponseMessage() { StatusCode = HttpStatusCode.HttpVersionNotSupported, }; HttpResponseMessage mockResponse6 = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, mockResponse2, mockResponse3, mockResponse4, mockResponse5, mockResponse6, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig clientConfig = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; RequestConfig requestConfig = new RequestConfig(); List <IFunction> contentBlock = new List <IFunction> { new ApiSessionCreate() }; RequestHandler requestHandler = new RequestHandler(clientConfig, requestConfig); var ex = await Record.ExceptionAsync(() => requestHandler.ExecuteOnline(contentBlock)); Assert.IsType <HttpRequestException>(ex); Assert.Equal("Request retry count exceeded max retry count: 5", ex.Message); }
public async Task MockExecuteSynchronousTest() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig clientConfig = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; RequestConfig requestConfig = new RequestConfig() { ControlId = "unittest", }; List <IFunction> contentBlock = new List <IFunction> { new ApiSessionCreate() }; RequestHandler requestHandler = new RequestHandler(clientConfig, requestConfig); OnlineResponse response = await requestHandler.ExecuteOnline(contentBlock); Assert.IsType <OnlineResponse>(response); }
public async Task ExecuteResultExceptionTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>requestUnitTest</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <locationid></locationid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>failure</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <errormessage> <error> <errorno>Get API Session Failed</errorno> <description></description> <description2>Something went wrong</description2> <correction></correction> </error> </errormessage> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig clientConfig = new ClientConfig { SenderId = "testsender", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; OnlineClient client = new OnlineClient(clientConfig); var ex = await Record.ExceptionAsync(() => client.Execute(new ApiSessionCreate("func1UnitTest"))); Assert.IsType <ResultException>(ex); Assert.Equal("Result status: failure for Control ID: func1UnitTest - Get API Session Failed Something went wrong", ex.Message); }
public async Task SendAsync_SetInnerHandlerAfterCallMethod_ThrowsInvalidOperationException() { var transport = new MockTransportHandler(); var handler = new MockHandler(transport); await handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None); Assert.Equal(1, handler.SendAsyncCount); Assert.Equal(1, transport.SendAsyncCount); Assert.Throws<InvalidOperationException>(() => handler.InnerHandler = transport); }
public void Ctor_CreateDispose_Success() { MockHandler handler = new MockHandler(); Assert.Null(handler.InnerHandler); handler.Dispose(); }
public async Task SendAsync_ProcessResponseThrowsOperationCanceledExceptionUsingOtherCts_TaskSetToIsFaulted() { var cts = new CancellationTokenSource(); var otherCts = new CancellationTokenSource(); var transport = new MockTransportHandler(); // ProcessResponse will throw a random OperationCanceledException() not related to cts. We also cancel // the cts to make sure the code behaves correctly even if cts is canceled & an OperationCanceledException // was thrown. var handler = new MockHandler(transport, false, () => { cts.Cancel(); throw new OperationCanceledException("custom", otherCts.Token); }); await Assert.ThrowsAsync<OperationCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token)); Assert.Equal(1, handler.ProcessResponseCount); }
public LoginCredentials(SdkConfig config, SenderCredentials senderCreds) { string envProfileName = Environment.GetEnvironmentVariable(CompanyProfileEnvName); if (String.IsNullOrWhiteSpace(envProfileName)) { envProfileName = DefaultCompanyProfile; } if (String.IsNullOrWhiteSpace(config.ProfileName)) { config.ProfileName = envProfileName; } if (String.IsNullOrWhiteSpace(config.CompanyId)) { config.CompanyId = Environment.GetEnvironmentVariable(CompanyIdEnvName); } if (String.IsNullOrWhiteSpace(config.UserId)) { config.UserId = Environment.GetEnvironmentVariable(UserIdEnvName); } if (String.IsNullOrWhiteSpace(config.UserPassword)) { config.UserPassword = Environment.GetEnvironmentVariable(UserPasswordEnvName); } if ( String.IsNullOrWhiteSpace(config.CompanyId) && String.IsNullOrWhiteSpace(config.UserId) && String.IsNullOrWhiteSpace(config.UserPassword) && !String.IsNullOrWhiteSpace(config.ProfileName) ) { ProfileCredentialProvider profileProvider = new ProfileCredentialProvider(); SdkConfig profileCreds = profileProvider.GetLoginCredentials(config); config.CompanyId = !String.IsNullOrWhiteSpace(profileCreds.CompanyId) ? profileCreds.CompanyId : config.CompanyId; config.UserId = !String.IsNullOrWhiteSpace(profileCreds.UserId) ? profileCreds.UserId : config.UserId; config.UserPassword = !String.IsNullOrWhiteSpace(profileCreds.UserPassword) ? profileCreds.UserPassword : config.UserPassword; } if (String.IsNullOrWhiteSpace(config.CompanyId)) { throw new ArgumentException("Required CompanyId not supplied in params or env variable \"" + CompanyIdEnvName + "\""); } if (String.IsNullOrWhiteSpace(config.UserId)) { throw new ArgumentException("Required UserId not supplied in params or env variable \"" + UserIdEnvName + "\""); } if (String.IsNullOrWhiteSpace(config.UserPassword)) { throw new ArgumentException("Required UserPassword not supplied in params or env variable \"" + UserPasswordEnvName + "\""); } CompanyId = config.CompanyId; UserId = config.UserId; Password = config.UserPassword; SenderCreds = senderCreds; MockHandler = config.MockHandler; Logger = config.Logger; LogMessageFormat = config.LogFormatter; LogLevel = config.LogLevel; }
public async Task SendAsync_OperationCanceledWhileProcessResponseIsExecuted_TaskSetToIsCanceled() { var cts = new CancellationTokenSource(); var transport = new MockTransportHandler(); // ProcessResponse will cancel. var handler = new MockHandler(transport, false, () => { cts.Cancel(); cts.Token.ThrowIfCancellationRequested(); }); await Assert.ThrowsAsync<TaskCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token)); }
public void ProcessAsyncRequest_WithValidRequest_ReturnsResponseFromHandler() { var mockHandler = new MockHandler(); mockHandler.StatusCode = 202; mockHandler.StatusDescription = "Bob"; mockHandler.UpdateBody(TestData.SampleTextResponse); using (var server = HttpHelper.CreateServer(mockHandler)) { server.StartListening(); var uri = new Uri("http://localhost:" + server.Port.ToString(CultureInfo.InvariantCulture) + "/"); var request = WebRequest.Create(uri); using (var response = (HttpWebResponse)request.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, response.StatusCode); Assert.AreEqual(mockHandler.StatusDescription, response.StatusDescription); string body; using (var sr = new StreamReader(response.GetResponseStream())) { body = sr.ReadToEnd(); } Assert.AreEqual(TestData.SampleTextResponse, body); } } }
public async Task LoggerTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>requestUnitTest</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>readByQuery</function> <controlid>func1UnitTest</controlid> <data listtype=""customer"" count=""1"" totalcount=""1"" numremaining=""0"" resultId=""""> <customer> <CUSTOMERID>C0001</CUSTOMERID> <NAME>Intacct Corporation</NAME> </customer> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); MemoryTarget target = new MemoryTarget(); target.Layout = "${message}"; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); SdkConfig config = new SdkConfig { MockHandler = mockHandler, Logger = LogManager.GetCurrentClassLogger(), }; Content content = new Content(); content.Add(new ApiSessionCreate("func1UnitTest")); SynchronousResponse response = await client.Execute(content, false, "requestUnitTest", false, config); Assert.IsTrue(target.Logs[0].Contains("<password>REDACTED</password>")); }
public async Task MockRetryTest() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadGateway, }; HttpResponseMessage mockResponse2 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, mockResponse2, }; MockHandler mockHandler = new MockHandler(mockResponses); SdkConfig config = new SdkConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; Content content = new Content(); RequestHandler requestHandler = new RequestHandler(config); SynchronousResponse response = await requestHandler.ExecuteSynchronous(config, content); Assert.AreEqual("testsenderid", response.Control.SenderId); }
public async Task MockExecuteWithDebugLoggerTest() { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse, }; MockHandler mockHandler = new MockHandler(mockResponses); MemoryTarget target = new MemoryTarget(); target.Layout = "${message}"; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); SdkConfig config = new SdkConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, Logger = LogManager.GetCurrentClassLogger(), }; Content content = new Content() { new ApiSessionCreate(), }; RequestHandler requestHandler = new RequestHandler(config); SynchronousResponse response = await requestHandler.ExecuteSynchronous(config, content); Assert.IsTrue(target.Logs[0].Contains("intacct-api-net-client/")); // Check for the user agent }
public void Ctor_SetNullInnerHandler_ThrowsArgumentNullException() { MockHandler handler = new MockHandler(); Assert.Throws <ArgumentNullException>(() => handler.InnerHandler = null); }
public async Task FromLoginCredentialsTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getSession</function> <controlid>testControlId</controlid> <data> <api> <sessionid>fAkESesSiOnId..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); SdkConfig config = new SdkConfig() { CompanyId = "testcompany", UserId = "testuser", UserPassword = "******", MockHandler = mockHandler, }; LoginCredentials loginCreds = new LoginCredentials(config, senderCreds); SessionCredentials sessionCreds = await provider.FromLoginCredentials(loginCreds); Assert.AreEqual("fAkESesSiOnId..", sessionCreds.SessionId); StringAssert.Equals("https://unittest.intacct.com/ia/xml/xmlgw.phtml", sessionCreds.Endpoint); Assert.IsInstanceOfType(sessionCreds.SenderCreds, typeof(SenderCredentials)); }
public async Task SendAsync_OperationCanceledWhileProcessRequestIsExecuted_TaskSetToIsCanceled() { var cts = new CancellationTokenSource(); var transport = new MockTransportHandler(); // ProcessRequest will cancel. var handler = new MockHandler(transport, true, () => { cts.Cancel(); cts.Token.ThrowIfCancellationRequested(); }); // Note that even ProcessMessage() is called on the same thread, we don't expect SendAsync() to throw. // SendAsync() must complete successfully, but the Task will be canceled. await Assert.ThrowsAsync<TaskCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token)); Assert.Equal(0, handler.ProcessResponseCount); }
public async Task ExecuteTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>requestUnitTest</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <locationid></locationid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getAPISession</function> <controlid>func1UnitTest</controlid> <data> <api> <sessionid>unittest..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> <locationid></locationid> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig clientConfig = new ClientConfig { SenderId = "testsender", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, }; OnlineClient client = new OnlineClient(clientConfig); OnlineResponse response = await client.Execute(new ApiSessionCreate("func1UnitTest")); Assert.Equal("requestUnitTest", response.Control.ControlId); }
public void Reset() { MockHandler.Reset(); }
public async Task SendAsync_OperationCanceledWhileInnerHandlerIsWorking_TaskSetToIsCanceled() { var cts = new CancellationTokenSource(); // We simulate a cancellation happening while the inner handler was processing the request, by letting // the inner mock handler call Cancel() and behave like if another thread called cancel while it was // processing. var transport = new MockTransportHandler(cts); // inner handler will cancel. var handler = new MockHandler(transport); await Assert.ThrowsAsync<TaskCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token)); Assert.Equal(0, handler.ProcessResponseCount); }
public async Task LoggerTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>requestUnitTest</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <locationid></locationid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>readByQuery</function> <controlid>func1UnitTest</controlid> <data listtype=""customer"" count=""1"" totalcount=""1"" numremaining=""0"" resultId=""""> <customer> <CUSTOMERID>C0001</CUSTOMERID> <NAME>Intacct Corporation</NAME> </customer> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); var guid = Guid.NewGuid().ToString(); MemoryTarget target = new MemoryTarget { Name = guid, Layout = "${message}" }; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); ClientConfig config = new ClientConfig { SenderId = "testsender", SenderPassword = "******", SessionId = "testsession..", MockHandler = mockHandler, Logger = LogManager.GetLogger(guid), }; OnlineClient client = new OnlineClient(config); OnlineResponse response = await client.Execute(new ReadByQuery("func1UnitTest")); Assert.True(true); // TODO fix this test from randomly failing //Assert.Contains("<password>REDACTED</password>", target.Logs[0]); }
public async Task FromPrivateEntitySessionCredentialsWithDifferentEntityOverrideTest() { string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <response> <control> <status>success</status> <senderid>testsenderid</senderid> <controlid>sessionProvider</controlid> <uniqueid>false</uniqueid> <dtdversion>3.0</dtdversion> </control> <operation> <authentication> <status>success</status> <userid>testuser</userid> <companyid>testcompany</companyid> <locationid>entityA</locationid> <sessiontimestamp>2015-12-06T15:57:08-08:00</sessiontimestamp> </authentication> <result> <status>success</status> <function>getSession</function> <controlid>testControlId</controlid> <data> <api> <sessionid>EntityBSession..</sessionid> <endpoint>https://unittest.intacct.com/ia/xml/xmlgw.phtml</endpoint> <locationid>entityB</locationid> </api> </data> </result> </operation> </response>"; HttpResponseMessage mockResponse1 = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(xml) }; List <HttpResponseMessage> mockResponses = new List <HttpResponseMessage> { mockResponse1, }; MockHandler mockHandler = new MockHandler(mockResponses); ClientConfig config = new ClientConfig() { SenderId = "testsenderid", SenderPassword = "******", SessionId = "EntityAsession..", EndpointUrl = "https://unittest.intacct.com/ia/xml/xmlgw.phtml", MockHandler = mockHandler, EntityId = "entityB", }; ClientConfig sessionCreds = await SessionProvider.Factory(config); Assert.Equal("EntityBSession..", sessionCreds.SessionId); Assert.Equal("https://unittest.intacct.com/ia/xml/xmlgw.phtml", sessionCreds.EndpointUrl); Assert.Equal("entityB", sessionCreds.EntityId); }