public void InvokeMethodGrpcAsync_CanInvokeMethodWithNoReturnTypeAndData() { var request = new Request() { RequestParameter = "Hello " }; var client = new MockClient(); var data = new Response() { Name = "Look, I was invoked!" }; var invokeResponse = new InvokeResponse { Data = Any.Pack(data), }; var response = client.Call <InvokeResponse>() .SetResponse(invokeResponse) .Build(); client.Mock .Setup(m => m.InvokeServiceAsync(It.IsAny <Autogen.Grpc.v1.InvokeServiceRequest>(), It.IsAny <CallOptions>())) .Returns(response); FluentActions.Awaiting(async() => await client.DaprClient.InvokeMethodGrpcAsync <Request>("test", "test", request)).Should().NotThrow(); }
public void InvokeMethodAsync_CanInvokeMethodWithNoReturnTypeAndData() { Request request = new Request() { RequestParameter = "Hello " }; var client = new MockClient(); var data = new Response() { Name = "Look, I was invoked!" }; var invokeResponse = new InvokeResponse(); invokeResponse.Data = TypeConverters.ToAny(data); var response = client.Call <InvokeResponse>() .SetResponse(invokeResponse) .Build(); // Setup the mock client to throw an Rpc Exception with the expected details info client.Mock .Setup(m => m.InvokeServiceAsync(It.IsAny <Autogen.Grpc.v1.InvokeServiceRequest>(), It.IsAny <CallOptions>())) .Returns(response); FluentActions.Awaiting(async() => await client.DaprClient.InvokeMethodAsync <Request>("test", "test", request)).Should().NotThrow(); }
public async Task InvokeMethodAsync_CanInvokeMethodWithNoReturnTypeAndData_ThrowsErrorNonSuccess() { var client = new MockClient(); var data = new Response() { Name = "Look, I was invoked!" }; var invokeResponse = new InvokeResponse(); invokeResponse.Data = TypeConverters.ToAny(data); var response = client.Call <InvokeResponse>() .SetResponse(invokeResponse) .Build(); const string rpcExceptionMessage = "RPC exception"; const StatusCode rpcStatusCode = StatusCode.Unavailable; const string rpcStatusDetail = "Non success"; var rpcStatus = new Status(rpcStatusCode, rpcStatusDetail); var rpcException = new RpcException(rpcStatus, new Metadata(), rpcExceptionMessage); // Setup the mock client to throw an Rpc Exception with the expected details info client.Mock .Setup(m => m.InvokeServiceAsync(It.IsAny <Autogen.Grpc.v1.InvokeServiceRequest>(), It.IsAny <CallOptions>())) .Throws(rpcException); await FluentActions.Awaiting(async() => await client.DaprClient.InvokeMethodAsync <Request>("test", "test", new Request() { RequestParameter = "Hello " })) .Should().ThrowAsync <RpcException>(); }
public async Task InvokeMethodAsync_CanInvokeMethodWithReturnTypeNoData_ThrowsExceptionNonSuccess() { // Configure Client var httpClient = new TestHttpClient(); var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { HttpClient = httpClient }) .Build(); var task = daprClient.InvokeMethodAsync <Response>("test", "test"); // Get Request and validate httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); var envelope = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeServiceRequest>(entry.Request); envelope.Id.Should().Be("test"); envelope.Message.Method.Should().Be("test"); envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationJson); // Create Response & Respond var response = GrpcUtils.CreateResponse(HttpStatusCode.NotAcceptable); entry.Completion.SetResult(response); //validate response await FluentActions.Awaiting(async() => await task).Should().ThrowAsync <RpcException>(); }
public async Task InvokeBindingAsync_WithCancelledToken() { // Configure Client var httpClient = new TestHttpClient(); var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true }) .Build(); var ctSource = new CancellationTokenSource(); CancellationToken ct = ctSource.Token; ctSource.Cancel(); var metadata = new Dictionary <string, string>(); metadata.Add("key1", "value1"); metadata.Add("key2", "value2"); var invokeRequest = new InvokeRequest() { RequestParameter = "Hello " }; var task = daprClient.InvokeBindingAsync <InvokeRequest>("test", "create", invokeRequest, metadata, ct); await FluentActions.Awaiting(async() => await task) .Should().ThrowAsync <OperationCanceledException>(); }
internal Task Should_Throw_On_DeleteSubscription_When_ConsumerGroup_IsNull( EventStoreClient sut, CancellationToken cancellationToken) => FluentActions .Awaiting(() => sut.DeleteSubscriptionAsync(null, cancellationToken)) .Should() .ThrowAsync <ArgumentNullException>();
public async Task CreateBankAccountForCurrentUser_AccountNameExists_ThrowsException() { // Arrange var bankAccountModel = new BankAccountModel { AccountType = BankAccountType.Checking, Disabled = true, Name = "BankAccountName", StartBalance = 1000 }; InsertEntity(new BankAccountEntity { Name = bankAccountModel.Name, UserId = _defaultUserId }); var bankAccountService = _mocker.CreateInstance <BankAccountService>(); // Act var result = FluentActions.Awaiting(async() => await bankAccountService.CreateBankAccountForCurrentUser(bankAccountModel)); // Assert await result.Should().ThrowAsync <AlreadyExistsException>(); }
public async Task UpdateBankAccountForCurrentUser_UserDoesNotOwnAccount_ThrowsException() { // Arrange var existingEntity = new BankAccountEntity { AccountType = BankAccountType.Checking, Disabled = false, CurrentBalance = 100, StartBalance = 100, Name = "BankAccountName", UserId = _defaultUserId + 1 }; InsertEntity(existingEntity); var bankAccountModel = new BankAccountModel { Id = existingEntity.Id, AccountType = BankAccountType.Checking, Name = "OtherName" }; var bankAccountService = _mocker.CreateInstance <BankAccountService>(); // Act var result = FluentActions.Awaiting(async() => await bankAccountService.UpdateBankAccountForCurrentUser(bankAccountModel)); // Arrange await result.Should().ThrowAsync <NotFoundException>(); }
public async Task Call_ValidateUnsuccessfulResponse() { var handler = new TestHttpClientHandler(); var httpInteractor = new DaprHttpInteractor(handler); var actorType = "ActorType_Test"; var actorId = "ActorId_Test"; var timerName = "TimerName"; var task = httpInteractor.UnregisterTimerAsync(actorType, actorId, timerName); handler.Requests.TryDequeue(out var entry).Should().BeTrue(); var error = new DaprError() { ErrorCode = "ERR_STATE_STORE", Message = "State Store Error" }; var message = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(JsonSerializer.Serialize(error)) }; entry.Completion.SetResult(message); await FluentActions.Awaiting(async() => await task).Should().ThrowAsync <DaprException>(); }
public async Task ParseJsonBodyAsync_WithValidatorAndInvalidData_ShouldThrowValidationException() { // arrange var sampleDto = Mother.SampleDto .Random .WithId(Guid.Empty) .Build(); var sampleAsJson = JsonSerializer.Serialize(sampleDto); var ms = new MemoryStream(); await using var writer = new StreamWriter(ms); await writer.WriteAsync(sampleAsJson); await writer.FlushAsync(); ms.Position = 0; var request = A.Fake <HttpRequest>(); A.CallTo(() => request.Body) .Returns(ms); // act && assert FluentActions.Awaiting(() => request.ParseJsonBodyAsync(new SampleDtoValidator())).Should() .Throw <ValidationException>(); }
public async Task CanNotShutdownMultipleTimes() { using var dispatcher = new Dispatcher(); var thread = new Thread(dispatcher.Run); thread.Start(); await dispatcher.InvokeAsync(() => { }); // Await starting dispatcher Forget(dispatcher.InvokeAsync(() => Thread.Sleep(10))); // Add some tasks running Forget(dispatcher.InvokeAsync(() => Thread.Sleep(10))); // Add some tasks running Forget(dispatcher.InvokeAsync(() => Thread.Sleep(10))); // Add some tasks running const Int32 requestsCount = 100; const Int32 faultedCount = requestsCount - 1; var shutdownTasks = new Task[requestsCount]; Parallel.For( 0, requestsCount, i => { // ReSharper disable once AccessToDisposedClosure shutdownTasks[i] = Task.Run(dispatcher.InvokeShutdownAsync); } ); FluentActions.Awaiting(async() => await Task.WhenAll(shutdownTasks)).Should().Throw <DispatcherException>(); shutdownTasks.Count(t => t.IsCompletedSuccessfully).Should().Be(1); shutdownTasks.Count(t => t.IsFaulted).Should().Be(faultedCount); }
public async Task ExecuteStateTransactionAsync_ThrowsForNonSuccess() { // Configure Client var httpClient = new TestHttpClient(); var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { HttpClient = httpClient }) .Build(); var widget1 = new Widget() { Size = "small", Color = "yellow", }; var state1 = new StateTransactionRequest("stateKey1", JsonSerializer.SerializeToUtf8Bytes(widget1), StateOperationType.Upsert); var states = new List <StateTransactionRequest>(); states.Add(state1); var task = daprClient.ExecuteStateTransactionAsync("testStore", states); // Create Response & Respond httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); var response = GrpcUtils.CreateResponse(HttpStatusCode.NotAcceptable); entry.Completion.SetResult(response); await FluentActions.Awaiting(async() => await task).Should().ThrowAsync <RpcException>(); }
public void ShouldThrow_WhenFileDoesntExist(DownloadFileQuery query) { FluentActions.Awaiting(() => SendAsync(query)) .Should() .Throw <ValidationException>() .And.Error.Message.Should() .Be("File doesn't exist"); }
public void Handle_FinancialProjectIdEmpty_ShouldThrowValidationException() { var command = new DeleteReceiptItemCommand { Id = "asdas", FinancialProjectId = "" }; FluentActions.Awaiting(() => SendAsync(command)).Should().Throw <ValidationException>(); }
public async Task TryDeleteStateAsync_NullEtagThrowsArgumentException() { var client = new MockClient(); var response = client.CallStateApi<string>() .Build(); await FluentActions.Awaiting(async () => await client.DaprClient.TryDeleteStateAsync("test", "test", null)) .Should().ThrowAsync<ArgumentException>(); }
public void Handle_InvalidId_ShouldThrowNotFoundException() { var command = new DeleteReceiptItemCommand { Id = "nah", FinancialProjectId = "ada" }; FluentActions.Awaiting(() => SendAsync(command)).Should().Throw <NotFoundException>(); }
public void Handle_UserIdsNull_ThrowValidationException() { var create = new CreateReceiptItemCommand { Count = 2, Price = 2, Name = "sds", ReceiptId = "asdsa", ItemGroup = (int)ItemGroup.Essentials }; FluentActions.Awaiting(() => SendAsync(create)).Should().Throw <ValidationException>(); }
public async Task GetBankAccountByIdForCurrentUser_AccountDoesNotExist_ThrowsException() { // Arrange var bankAccountId = 1; var bankAccountService = _mocker.CreateInstance <BankAccountService>(); // Act var result = FluentActions.Awaiting(async() => await bankAccountService.GetBankAccountByIdForCurrentUser(bankAccountId)); // Arrange await result.Should().ThrowAsync <NotFoundException>(); }
public async Task GetStateAsync_ThrowsForNonSuccess() { var httpClient = new TestHttpClient(); var client = new StateHttpClient(httpClient, new JsonSerializerOptions()); var task = client.GetStateAsync <Widget>("test"); httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); entry.Request.RequestUri.ToString().Should().Be(GetStateUrl(3500, "test")); entry.Respond(new HttpResponseMessage(HttpStatusCode.NotAcceptable)); await FluentActions.Awaiting(async() => await task).Should().ThrowAsync <HttpRequestException>(); }
public void Handle_UsersIsNull_ShouldThrowValidationException() { var updateCommand = new UpdateReceiptItemCommand { Count = 1235, ItemGroup = (int)ItemGroup.Essentials, Price = 231.32321, Id = "asdasdasd", UserDtos = null !, FinancialProjectId = "asd" }; FluentActions.Awaiting(() => SendAsync(updateCommand)).Should().Throw <ValidationException>(); }
public async Task InvokeMethodAsync_CanInvokeMethodWithReturnTypeNoData_ThrowsExceptionNonSuccess() { var httpClient = new TestHttpClient(); var invokeClient = new InvokeHttpClient(httpClient, new JsonSerializerOptions()); var task = invokeClient.InvokeMethodAsync <InvokedResponse>("test", "test"); httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); entry.Request.RequestUri.ToString().Should().Be(GetInvokeUrl(3500, "test", "test")); entry.Respond(new HttpResponseMessage(HttpStatusCode.NotAcceptable)); await FluentActions.Awaiting(async() => await task).Should().ThrowAsync <HttpRequestException>(); }
public void Handle_InvalidId_ShouldThrowParentObjectNotFoundException() { var create = new CreateReceiptItemCommand { Count = 2, Price = 2, Name = "sds", ReceiptId = "asdsa", ItemGroup = (int)ItemGroup.Essentials, UserIds = new List <string> { User.Id } }; FluentActions.Awaiting(() => SendAsync(create)).Should().Throw <ParentObjectNotFoundException>(); }
public void Handle_CountBelowZero_ThrowValidationException() { var create = new CreateReceiptItemCommand { Count = -5, Price = 2, Name = "sds", ItemGroup = (int)ItemGroup.Essentials, ReceiptId = "asdsa", UserIds = new List <string> { User.Id } }; FluentActions.Awaiting(() => SendAsync(create)).Should().Throw <ValidationException>(); }
public void SendMessageAsync_ShouldBeCancellable() { ServiceCollection services = new(); services.AddMediator(); services.AddTransient <Handler1>(); services.AddTransient <Handler2>(); using var container = services.BuildServiceProvider(); var mediator = container.GetRequiredService <IMediator>(); using CancellationTokenSource cancellationTokenSource = new(); var cancellationToken = cancellationTokenSource.Token; var sendTask = mediator.SendMessageAsync(new Message(), cancellationToken); cancellationTokenSource.Cancel(); FluentActions.Awaiting(() => sendTask).Should().Throw <OperationCanceledException>(); }
public async Task Call_ValidateUnauthorizedResponse() { var handler = new TestHttpClientHandler(); var httpInteractor = new DaprHttpInteractor(handler); var actorType = "ActorType_Test"; var actorId = "ActorId_Test"; var timerName = "TimerName"; var task = httpInteractor.UnregisterTimerAsync(actorType, actorId, timerName); handler.Requests.TryDequeue(out var entry).Should().BeTrue(); var message = new HttpResponseMessage(HttpStatusCode.Unauthorized); entry.Completion.SetResult(message); await FluentActions.Awaiting(async() => await task).Should().ThrowAsync <AuthenticationException>(); }
public async Task PublishEventAsync_WithCancelledToken() { var httpClient = new TestHttpClient(); var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true }) .Build(); var ctSource = new CancellationTokenSource(); CancellationToken ct = ctSource.Token; ctSource.Cancel(); await FluentActions.Awaiting(async() => await daprClient.PublishEventAsync(TestPubsubName, "test", cancellationToken: ct)) .Should().ThrowAsync <OperationCanceledException>(); }
public async Task SaveStateAsync_WithCancelledToken() { // Configure Client var httpClient = new TestHttpClient(); var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true }) .Build(); var ctSource = new CancellationTokenSource(); CancellationToken ct = ctSource.Token; ctSource.Cancel(); await FluentActions.Awaiting(async() => await daprClient.SaveStateAsync <object>("testStore", "test", null, cancellationToken: ct)) .Should().ThrowAsync <OperationCanceledException>(); }
public void Handle_ReceiptItemIdEmpty_ShouldThrowValidationException() { var updateCommand = new UpdateReceiptItemCommand { Count = 1235, ItemGroup = (int)ItemGroup.Essentials, Price = 231.32321, UserDtos = new List <UserDto> { new UserDto { Id = User.Id } }, FinancialProjectId = "asd" }; FluentActions.Awaiting(() => SendAsync(updateCommand)).Should().Throw <ValidationException>(); }
public async Task SetStateAsync_ThrowsForNonSuccess() { var httpClient = new TestHttpClient(); var client = new StateHttpClient(httpClient, new JsonSerializerOptions()); var widget = new Widget() { Size = "small", Color = "yellow", }; var task = client.SaveStateAsync("test", widget); httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); entry.Request.RequestUri.ToString().Should().Be(SaveStateUrl(3500)); entry.Respond(new HttpResponseMessage(HttpStatusCode.NotAcceptable)); await FluentActions.Awaiting(async() => await task).Should().ThrowAsync <HttpRequestException>(); }
public void Handle_ItemGroupLessThanZero_ShouldThrowValidationException() { var updateCommand = new UpdateReceiptItemCommand { Count = 1235, Price = 231.32321, Id = "dont even matter lmao", ItemGroup = -1, UserDtos = new List <UserDto> { new UserDto { Id = User.Id } }, FinancialProjectId = "asd" }; FluentActions.Awaiting(() => SendAsync(updateCommand)).Should().Throw <ValidationException>(); }