private void setupServerUnavailableHttpResponse() { mockMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.ServiceUnavailable, }); }
public void ProcesarArchivo_Method_Should_Call_LlamarMetodoConsoleMethods_Method_When_Exception_By_DataReader_Ocurrs() { //Arrange _fileDataReaderMock.Setup(m => m.GetFileDataRows(It.IsAny <string>(), It.IsAny <string>())).Throws(new Exception("AlgoOcurrio")); //Act _procesadorMock.Object.ProcesarArchivo(); //Assert _procesadorMock.Protected().Verify <bool>("LlamarMetodoConsoleMethods", Times.Once(), ItExpr.IsAny <string>()); }
public void ProcesarArchivo_Method_Should_Call_LlamarMetodoConsoleMethods_Method_When_ObtenerParametrosPedido_Method_Throws_Error_By_Number_Columns(string lineaPedido) { //Arrange _filasPedidos[0] = lineaPedido; //Act _procesadorMock.Object.ProcesarArchivo(); //Assert _procesadorMock.Protected().Verify <bool>("LlamarMetodoConsoleMethods", Times.Once(), ItExpr.IsAny <string>()); }
public async Task Execute_CheckIfCallsCorrectUri_CheckSucceeds() { var fixture = new Fixture(); var clientName = fixture.Create <string>(); var apiKey = fixture.Create <string>(); var query = fixture.Create <string>(); var requestUri = ""; var baseUri = "http://test.com/"; var expectedRequestUri = $"{baseUri}json/{apiKey}/{query.TrimStart('/')}"; _handler.ConfigUriCheck((request, cancellationToken) => { requestUri = request.RequestUri.AbsoluteUri; }); var httpClient = new HttpClient(_handler.Object); httpClient.BaseAddress = new Uri(baseUri); _httpClientFactory.Setup(z => z.CreateClient(clientName)).Returns(httpClient); await _subjectUnderTest.Execute(clientName, apiKey, query); _httpClientFactory.Verify(z => z.CreateClient(clientName), Times.Once); _handler.Protected().Verify("SendAsync", Times.Once(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); requestUri.Should().BeEquivalentTo(expectedRequestUri); }
public void ProcesarArchivo_Method_Should_Call_LlamarImprimirMensajesPedidoProcesadorPedido_Method_When_All_Data_Is_Correct(string lineaPedido) { //Arrange _filasPedidos[0] = lineaPedido; //Act _procesadorMock.Object.ProcesarArchivo(); //Assert _procesadorMock.Protected().Verify <bool>("LlamarImprimirMensajesPedidoProcesadorPedido", Times.Once(), ItExpr.IsAny <IProcesadorPedidos>()); }
public async Task LongPollingTransportStopsWhenPollReceives204() { var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); return(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); await longPollingTransport.Running.OrTimeout(); Assert.True(longPollingTransport.Input.TryRead(out var result)); Assert.True(result.IsCompleted); longPollingTransport.Input.AdvanceTo(result.Buffer.End); } finally { await longPollingTransport.StopAsync(); } } }
public async Task Sms_WhenSmsArriveAndGet_AllMustBeSuccess() { //arrange var userId = Guid.NewGuid(); var callsController = _serviceProvider.GetScopedController <CallsController>(userId); Guid caseFolderId = Guid.Empty; _operatorClientMock.Setup(x => x.Clients.All.SendCoreAsync( "smsAccepted", It.IsAny <object[]>(), It.IsAny <CancellationToken>())).Returns <string, object[], CancellationToken>(async(x, datas, z) => { var result = JsonConvert.SerializeObject(datas[0]); var jObject = JObject.Parse(result); caseFolderId = Guid.Parse(jObject["caseFolder"]["id"].ToString()); } ); var smsText = "У меня коронавирус, помогите!"; var extension = "4124"; //action var result = await _serviceProvider.MakeSms(smsText, extension); var acceptCallDto = CreateAcceptDto(result.ItemId); _inboxDistributionClientMock.Setup(x => x.AcceptItem(It.IsAny <AcceptItemClientDto>())).ReturnsAsync(Result.Success(new UserItemClientDto() { ItemType = ClientInboxItemType.Sms, ItemId = result.ItemId, CaseTypeId = new Guid("6a9f90c4-2b7e-4ec3-a38f-000000000112") }) ); var operatorId = userId; SetCurrentUserId(operatorId); var smsInRepo = await IsSmsInRepo(result.ItemId); _httpMessageHandler.Protected().Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.Is <HttpRequestMessage>(x => x.RequestUri.AbsoluteUri.EndsWith($"users/{userId}")), ItExpr.IsAny <CancellationToken>()).ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new JsonContent(new UserDto { Id = userId }) }); var acceptResult = await callsController.Accept(acceptCallDto); await Task.Delay(1000); var caseFolder = await GetCaseFolder(caseFolderId); //assert caseFolder.ShouldNotBeNull(); var descriptionFieldValue = caseFolder.GetFieldValue(Domain.Entities.Case.DescriptionFieldId); var phoneFieldValue = caseFolder.GetFieldValue(Domain.Entities.Case.NumberFieldId); descriptionFieldValue.ShouldBe(smsText); phoneFieldValue.ShouldBe(extension); acceptResult.ShouldBeOfType <demoResult>("Accept Call from Applicant error"); smsInRepo.ShouldBeTrue(); }
public async Task LongPollingTransportStopsWhenPollRequestFails() { var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); return(ResponseUtils.CreateResponse(HttpStatusCode.InternalServerError)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); var exception = await Assert.ThrowsAsync <HttpRequestException>(async() => { async Task ReadAsync() { await longPollingTransport.Input.ReadAsync(); } await ReadAsync().OrTimeout(); }); Assert.Contains(" 500 ", exception.Message); } finally { await longPollingTransport.StopAsync(); } } }
public async Task LongPollingTransportStopsWhenSendRequestFails() { var stopped = false; var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); switch (request.Method.Method) { case "DELETE": stopped = true; return(ResponseUtils.CreateResponse(HttpStatusCode.Accepted)); case "GET" when stopped: return(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)); case "GET": return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); case "POST": return(ResponseUtils.CreateResponse(HttpStatusCode.InternalServerError)); default: throw new InvalidOperationException("Unexpected request"); } }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); await longPollingTransport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello World")); await longPollingTransport.Running.OrTimeout(); var exception = await Assert.ThrowsAsync <HttpRequestException>(async() => await longPollingTransport.Input.ReadAllAsync().OrTimeout()); Assert.Contains(" 500 ", exception.Message); Assert.True(stopped); } finally { await longPollingTransport.StopAsync(); } } }
public void FiltersOnPathAndTemplate() { // Mock the database var db = Mock.Of <Database>(); // Mock the parent item var parentId = ID.NewID; var parentDef = new ItemDefinition(parentId, "parent", Templates.Product.Id, ID.Null); var parentData = new ItemData(parentDef, Language.Parse("en"), Version.Parse(1), new FieldList()); var parent = new Mock <Item>(parentId, parentData, db); // Mock the Sitecore services var factoryMock = new Mock <BaseFactory>(); factoryMock.Setup(x => x.GetDatabase(It.IsAny <string>())).Returns(db); var factory = factoryMock.Object; var itemManager = Mock.Of <BaseItemManager>(); // Mock search context, so we are testing LINQ to Objects instead of LINQ to Sitecore var itemUri = new ItemUri("sitecore://master/{11111111-1111-1111-1111-111111111111}?lang=en&ver=1"); var mockSearchContext = new Mock <IProviderSearchContext>(); mockSearchContext.Setup(x => x.GetQueryable <ProductSearchQuery>()) .Returns(new[] { // Matches Path and Template new ProductSearchQuery { UniqueId = itemUri, Templates = new[] { Templates.Product.Id }, Paths = new[] { parentId } }, // Matches Path and Template new ProductSearchQuery { UniqueId = itemUri, Templates = new[] { ID.NewID, Templates.Product.Id, ID.NewID }, Paths = new[] { ID.NewID, parentId, ID.NewID } }, // Matches Template Only new ProductSearchQuery { UniqueId = itemUri, Templates = new[] { Templates.Product.Id }, Paths = new[] { ID.NewID } }, // Matches Path Only new ProductSearchQuery { UniqueId = itemUri, Templates = new[] { ID.NewID }, Paths = new[] { parentId } } }.AsQueryable()); // Use Moq.Protected to ensure our test object uses the mock search context var mockRepo = new Mock <ProductRepository>(factory, itemManager); mockRepo.Protected() .Setup <IProviderSearchContext>("GetSearchContext", ItExpr.IsAny <Item>()) .Returns(mockSearchContext.Object); // Act var result = mockRepo.Object.GetProducts(parent.Object).ToList(); // If the tested class is filtering appropriately, we should get predictible results Assert.Equal(2, result.Count); }
public async void DoesNotOverwriteNonNullRecipientValues() { const string skillRecipientId = "skillBot"; Func <HttpRequestMessage, Task <HttpResponseMessage> > verifyRequestAndCreateResponse = (HttpRequestMessage request) => { var content = request.Content.ReadAsStringAsync().Result; var a = JsonConvert.DeserializeObject <Activity>(content); Assert.NotNull(a.Recipient); Assert.Equal(skillRecipientId, a.Recipient?.Id); var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StringContent(new JObject { }.ToString()); return(Task.FromResult(response)); }; var mockHttpMessageHandler = new Mock <HttpMessageHandler>(); mockHttpMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => verifyRequestAndCreateResponse(request)) .Verifiable(); var httpClient = new HttpClient(mockHttpMessageHandler.Object); var mockCredentialProvider = new Mock <ICredentialProvider>(); var client = new BotFrameworkHttpClient(httpClient, mockCredentialProvider.Object); var activity = new Activity { Conversation = new ConversationAccount(), Recipient = new ChannelAccount("skillBot") }; await client.PostActivityAsync(string.Empty, string.Empty, new Uri("https://skillbot.com/api/messages"), new Uri("https://parentbot.com/api/messages"), "NewConversationId", activity); // Assert Assert.Equal("skillBot", activity?.Recipient?.Id); }
public async Task HTTPステータスが200かつSuccessが1_Orderを返す() { var handler = new Mock <HttpMessageHandler>(); handler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Callback <HttpRequestMessage, CancellationToken>((request, _) => { Assert.StartsWith("https://api.bitbank.cc/v1/", request.RequestUri.AbsoluteUri, StringComparison.Ordinal); }) .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(Json) }); using var client = new HttpClient(handler.Object); using var restApi = new BitbankRestApiClient(client, " ", " "); var result = await restApi.GetOrderAsync(default, default).ConfigureAwait(false);
public void RegisteredUser_IsAllowed_ByDefault() { // Arrange this._mockDnnAuthorizeAttribute.Protected().Setup <bool>("IsAuthenticated").Returns(true); this._mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny <AuthorizationContext>()); var sut = this._mockDnnAuthorizeAttribute.Object; this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var controllerContext = new ControllerContext(); var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert this._mockRepository.VerifyAll(); }
public void RegisteredUser_IsDenied_If_IncludedIn_StaticRoles() { // Arrange const string roleName = "MyRole"; var user = this.SetUpUserWithRole(roleName); this._mockDnnAuthorizeAttribute.Protected().Setup <bool>("IsAuthenticated").Returns(true); this._mockDnnAuthorizeAttribute.Protected().Setup("HandleAuthorizedRequest", ItExpr.IsAny <AuthorizationContext>()); this._mockDnnAuthorizeAttribute.Protected().Setup <UserInfo>("GetCurrentUser").Returns(user); var sut = this._mockDnnAuthorizeAttribute.Object; sut.StaticRoles = roleName; this._mockActionDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); this._mockControllerDescriptor.Setup(x => x.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false); this._mockActionDescriptor.SetupGet(x => x.ControllerDescriptor).Returns(this._mockControllerDescriptor.Object); var controllerContext = new ControllerContext(); var context = new AuthorizationContext(controllerContext, this._mockActionDescriptor.Object); // Act sut.OnAuthorization(context); // Assert this._mockRepository.VerifyAll(); }
[InlineData((TransferFormat)42)] // Unexpected value public async Task LongPollingTransportThrowsForInvalidTransferFormat(TransferFormat transferFormat) { var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); var exception = await Assert.ThrowsAsync <ArgumentException>(() => longPollingTransport.StartAsync(TestUri, transferFormat)); Assert.Contains($"The '{transferFormat}' transfer format is not supported by this transport.", exception.Message); Assert.Equal("transferFormat", exception.ParamName); } }
public async Task LongPollingTransportShutsDownWhenChannelIsClosed() { var mockHttpHandler = new Mock <HttpMessageHandler>(); var stopped = false; mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); if (request.Method == HttpMethod.Delete) { stopped = true; return(ResponseUtils.CreateResponse(HttpStatusCode.Accepted)); } else { return(stopped ? ResponseUtils.CreateResponse(HttpStatusCode.NoContent) : ResponseUtils.CreateResponse(HttpStatusCode.OK)); } }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); longPollingTransport.Output.Complete(); await longPollingTransport.Running.OrTimeout(); await longPollingTransport.Input.ReadAllAsync().OrTimeout(); } finally { await longPollingTransport.StopAsync(); } } }
public async Task LongPollingTransportRePollsIfRequestCanceled() { var numPolls = 0; var completionTcs = new TaskCompletionSource <object>(); var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); if (Interlocked.Increment(ref numPolls) < 3) { throw new OperationCanceledException(); } completionTcs.SetResult(null); return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); var completedTask = await Task.WhenAny(completionTcs.Task, longPollingTransport.Running).OrTimeout(); Assert.Equal(completionTcs.Task, completedTask); } finally { await longPollingTransport.StopAsync(); } } }
public async Task LongPollingTransportShutsDownImmediatelyEvenIfServerDoesntCompletePoll() { var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); longPollingTransport.Output.Complete(); await longPollingTransport.Running.OrTimeout(); await longPollingTransport.Input.ReadAllAsync().OrTimeout(); } finally { await longPollingTransport.StopAsync(); } } }
public async Task LongPollingTransportResponseWithNoContentDoesNotStopPoll() { var requests = 0; var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); if (requests == 0) { requests++; return(ResponseUtils.CreateResponse(HttpStatusCode.OK, "Hello")); } else if (requests == 1) { requests++; // Time out return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); } else if (requests == 2) { requests++; return(ResponseUtils.CreateResponse(HttpStatusCode.OK, "World")); } // Done return(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); var data = await longPollingTransport.Input.ReadAllAsync().OrTimeout(); await longPollingTransport.Running.OrTimeout(); Assert.Equal(Encoding.UTF8.GetBytes("HelloWorld"), data); } finally { await longPollingTransport.StopAsync(); } } }
public async Task LongPollingTransportStopsPollAndSendLoopsWhenTransportStopped() { var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); Task transportActiveTask; using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); transportActiveTask = longPollingTransport.Running; Assert.False(transportActiveTask.IsCompleted); } finally { await longPollingTransport.StopAsync(); } await transportActiveTask.OrTimeout(); } }
private static HttpClient MockHttpClient(HttpStatusCode httpClientStatus) { string movieApiResponse = JsonConvert.SerializeObject(MockMovieApiResponse()); var httpMessageHandler = new Mock <HttpMessageHandler>(); httpMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns(Task.FromResult(new HttpResponseMessage { StatusCode = httpClientStatus, Content = new StringContent(movieApiResponse, Encoding.UTF8, "application/json") })); var httpClient = new HttpClient(httpMessageHandler.Object); return(httpClient); }
public async Task LongPollingTransportDispatchesMessagesReceivedFromPoll() { var message1Payload = new[] { (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o' }; var firstCall = true; var mockHttpHandler = new Mock <HttpMessageHandler>(); var sentRequests = new List <HttpRequestMessage>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { sentRequests.Add(request); await Task.Yield(); if (firstCall) { firstCall = false; return(ResponseUtils.CreateResponse(HttpStatusCode.OK, message1Payload)); } return(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { // Start the transport await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); // Wait for the transport to finish await longPollingTransport.Running.OrTimeout(); // Pull Messages out of the channel var message = await longPollingTransport.Input.ReadAllAsync(); // Check the provided request Assert.Equal(2, sentRequests.Count); // Check the messages received Assert.Equal(message1Payload, message); } finally { await longPollingTransport.StopAsync(); } } }
public async Task Execute_Exception_ReturnsFailResult() { var fixture = new Fixture(); var clientName = fixture.Create <string>(); var apiKey = fixture.Create <string>(); var query = fixture.Create <string>(); _handler.ConfigException(); var httpClient = new HttpClient(_handler.Object); httpClient.BaseAddress = new Uri("http://test.com/"); _httpClientFactory.Setup(z => z.CreateClient(clientName)).Returns(httpClient); var result = await _subjectUnderTest.Execute(clientName, apiKey, query); _httpClientFactory.Verify(z => z.CreateClient(clientName), Times.Once); _handler.Protected().Verify("SendAsync", Times.Once(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); result.IsSuccess.Should().BeFalse(); }
public async Task LongPollingTransportSendsAvailableMessagesWhenTheyArrive() { var sentRequests = new List <byte[]>(); var tcs = new TaskCompletionSource <HttpResponseMessage>(); var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); if (request.Method == HttpMethod.Post) { // Build a new request object, but convert the entire payload to string sentRequests.Add(await request.Content.ReadAsByteArrayAsync()); } else if (request.Method == HttpMethod.Get) { cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken)); // This is the poll task return(await tcs.Task); } else if (request.Method == HttpMethod.Delete) { return(ResponseUtils.CreateResponse(HttpStatusCode.Accepted)); } return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { // Start the transport await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); longPollingTransport.Output.Write(Encoding.UTF8.GetBytes("Hello")); longPollingTransport.Output.Write(Encoding.UTF8.GetBytes("World")); await longPollingTransport.Output.FlushAsync(); longPollingTransport.Output.Complete(); await longPollingTransport.Running.OrTimeout(); await longPollingTransport.Input.ReadAllAsync(); Assert.Single(sentRequests); Assert.Equal(new[] { (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'W', (byte)'o', (byte)'r', (byte)'l', (byte)'d' }, sentRequests[0]); } finally { await longPollingTransport.StopAsync(); } } }
public void OnSetup() { DateTime.TryParse("06/02/2020 09:00", out _tiempoApp); _dateTimeNow = _tiempoApp; _filasPedidos = new string[1]; _path = "f:\\somedirectory"; _fileName = "xfile.csv"; _clockMock = new Mock <IClock>(); _clockMock.Setup(m => m.GetTime()).Returns(_dateTimeNow); _fileExistValidatorMock = new Mock <IFileExistValidator>(); _fileExistValidatorMock.Setup(m => m.ValidateFileExist(It.IsAny <string>(), It.IsAny <string>())).Returns(""); _fileDataReaderMock = new Mock <IFileDataReader>(); _fileDataReaderMock.Setup(m => m.GetFileDataRows(It.IsAny <string>(), It.IsAny <string>())).Returns(_filasPedidos); _procesador = new ProcesadorArchivoPedidos(_path, _fileName, _fileExistValidatorMock.Object, _fileDataReaderMock.Object, _clockMock.Object); _procesadorMock = new Mock <ProcesadorArchivoPedidos>(_path, _fileName, _fileExistValidatorMock.Object, _fileDataReaderMock.Object, _clockMock.Object) { CallBase = true }; _procesadorMock.Protected().Setup <bool>("LlamarMetodoConsoleMethods", ItExpr.IsAny <string>()).Returns(true); _procesadorMock.Protected().Setup <bool>("LlamarImprimirMensajesPedidoProcesadorPedido", ItExpr.IsAny <IProcesadorPedidos>()).Returns(true); }
public async Task LongPollingTransportSendsDeleteAfterPollEnds() { var sentRequests = new List <byte[]>(); var pollTcs = new TaskCompletionSource <HttpResponseMessage>(); var deleteTcs = new TaskCompletionSource <object>(); var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); if (request.Method == HttpMethod.Post) { // Build a new request object, but convert the entire payload to string sentRequests.Add(await request.Content.ReadAsByteArrayAsync()); } else if (request.Method == HttpMethod.Get) { cancellationToken.Register(() => pollTcs.TrySetCanceled(cancellationToken)); // This is the poll task return(await pollTcs.Task); } else if (request.Method == HttpMethod.Delete) { // The poll task should have been completed Assert.True(pollTcs.Task.IsCompleted); deleteTcs.TrySetResult(null); return(ResponseUtils.CreateResponse(HttpStatusCode.Accepted)); } return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); // Start the transport await longPollingTransport.StartAsync(TestUri, TransferFormat.Binary); var task = longPollingTransport.StopAsync(); await deleteTcs.Task.OrTimeout(); await task.OrTimeout(); } }
public void ProcesarArchivo_Method_Should_Call_LlamarMetodoConsoleMethods_Method_When_Validate_File_Returns_Error() { //Arrange _fileExistValidatorMock.Setup(m => m.ValidateFileExist(It.IsAny <string>(), It.IsAny <string>())).Returns("El archivo o directorio no existen"); //Act _procesadorMock.Object.ProcesarArchivo(); //Assert _procesadorMock.Protected().Verify <bool>("LlamarMetodoConsoleMethods", Times.Once(), ItExpr.IsAny <string>()); }
public async Task LongPollingTransportSetsTransferFormat(TransferFormat transferFormat) { var mockHttpHandler = new Mock <HttpMessageHandler>(); mockHttpHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns <HttpRequestMessage, CancellationToken>(async(request, cancellationToken) => { await Task.Yield(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK)); }); using (var httpClient = new HttpClient(mockHttpHandler.Object)) { var longPollingTransport = new LongPollingTransport(httpClient); try { await longPollingTransport.StartAsync(TestUri, transferFormat); } finally { await longPollingTransport.StopAsync(); } } }
public async Task ListFolderAsync_NoErrorOccured_ReturnsResponse() { //Arrange messageHandlerMock.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.Is <HttpRequestMessage>(x => x.RequestUri.ToString().StartsWith(BASE_ADDRESS + API_VERSION + "/listFolder")), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(MockResponses.ReturnListFolderResponse()), Encoding.Default, "application/json") }); //Act var result = await SUT.ListFolderAsync(MockRequests.ReturnListFolderRequest()); //Assert Assert.IsType <ListFolderResponse>(result); }
private void setupSuccessfulHttpResponse() { mockMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(() => { var mockData = typeof(GithubServiceTest).Assembly.GetManifestResourceStream("Consumer.Tests.Data.testData.json"); return(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StreamContent(mockData) }); }); }