Beispiel #1
0
            public Task Should_Throw_When_Cancelled()
            {
                return(Assert.ThrowsAnyAsync <OperationCanceledException>(async() =>
                {
                    var commandHandler = new TestCommandHandler(_outputHelper);
                    var registration = new CommandHandlerRegistration();
                    registration.Register(() => (ICommandAsyncHandler <DoSomethingForSpecifiedDurationCommand>)commandHandler);

                    var cts = new CancellationTokenSource();

                    var dispatcher = new CommandDispatcher(registration);
                    Task task = dispatcher.DispatchAsync(new DoSomethingForSpecifiedDurationCommand(2000), cts.Token);

                    cts.Cancel();

                    try
                    {
                        await task;
                    }
                    catch (Exception ex)
                    {
                        _outputHelper.WriteLine(ex.ToString());
                        throw;
                    }
                }));
            }
Beispiel #2
0
            public async Task Failure_To_Send_On_Exception_Event_Will_Log_The_Exception()
            {
                //Arrange
                const string exceptionMessage = "Test Exception";
                var          result           = 0;
                var          testCommand      =
                    new TestCommand(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), () => { result = 10; });
                var handler =
                    new TestCommandHandler(Mock.Of <IDbContext>(), _mockMessageDispatcher.Object, _mockEventLogger.Object)
                {
                    CreateOnSuccessEvent = false
                };

                _mockMessageDispatcher.Setup(x => x.SendMessage(It.IsAny <Message>(), It.IsAny <CancellationToken>()))
                .Throws(new Exception(exceptionMessage));

                //Act
                await handler.Handle(testCommand, CancellationToken.None);

                //Assert
                Assert.That(result, Is.EqualTo(10));
                _mockMessageDispatcher.Verify(
                    x => x.SendMessage(It.IsAny <OnExceptionEvent>(), It.IsAny <CancellationToken>()), Times.Once);
                //_mockEventLogger.Verify(x => x.Log(SeverityLevel.Error, It.Is<EventId>(i => i == EventId.BaseMessageError), It.Is<Type>(t => t == typeof(TestCommandHandler)), It.Is<Exception>(e => e.Message == exceptionMessage)));
            }
        public void cancel_should_not_cancel_others()
        {
            var bus     = new CommandBus("local");
            var handler = new CancelableTestCommandHandler();

            bus.Subscribe((IHandleCommand <TestCommands.TestCommand>)handler);
            bus.Subscribe((IHandleCommand <TestCommands.TestCommand2>)handler);
            var handler2 = new TestCommandHandler();

            bus.Subscribe((IHandleCommand <TestCommands.TestCommand3>)handler2);
            var cmd1 = new TestCommands.TestCommand(Guid.NewGuid(), null);
            var cmd2 = new TestCommands.TestCommand2(Guid.NewGuid(), null);
            var cmd3 = new TestCommands.TestCommand3(Guid.NewGuid(), null);

            Task.Delay(100).ContinueWith(t => bus.RequestCancel(cmd1));
            Task.Run(() => bus.Fire(cmd2));
            Task.Run(() => bus.Fire(cmd3));
            Assert.Throws <CommandCanceledException>(
                () =>
            {
                try
                {
                    bus.Fire(cmd1);
                }
                catch (Exception ex)
                {
                    throw ex.InnerException;
                }
            });
        }
            public Task Should_Check_For_Correct_Command_Type()
            {
                return(Assert.ThrowsAnyAsync <ArgumentException>(async() =>
                {
                    var commandHandler = new TestCommandHandler(_testOutputHelper);

                    var registration = new CommandHandlerRegistration();
                    registration.Register(() => (ICommandHandler <DoSomethingCommand>)commandHandler);

                    CommandHandlerDelegate commandHandlerDelegate = registration.ResolveCommandHandler <DoSomethingCommand>();

                    Assert.NotNull(commandHandlerDelegate);

                    try
                    {
                        // This delegate handles DoSomethingCommand, but was passed in a DoSomethingWithCancellationCommand.
                        await commandHandlerDelegate.Invoke(new DoSomethingForSpecifiedDurationCommand(100));
                    }
                    catch (Exception ex)
                    {
                        _testOutputHelper.WriteLine(ex.ToString());
                        throw;
                    }
                }));
            }
        public async Task Should_ExecuteScheduledJob()
        {
            bool   canExecute   = true;
            string message      = string.Empty;
            var    scheduledJob = Substitute.For <IScheduledJob>();
            Func <IScheduledJob> _jobFactory = () => { return(scheduledJob); };

            scheduledJob.ExecuteAsync().Returns(Task.FromResult <object>(null));

            var item = new Item {
                Name = "Test"
            };
            var command = new TestCommand(item, c => { canExecute = c; }, m => { message = m; });
            var handler = new TestCommandHandler(_jobFactory);

            handler.Handle(command);

            Thread.Sleep(50);

            await scheduledJob.Received().ExecuteAsync()
            .ConfigureAwait(true);

            Assert.AreSame(scheduledJob.Item, command.Item);
            Assert.IsFalse(string.IsNullOrEmpty(message));
            Assert.IsTrue(canExecute);
        }
        public async Task Handle_Failure_Should_ReturnUnit_Detail_NoValidatorsForTheRequest()
        {
            IPipelineBehavior <TestCommand, Unit> validationPipeline = new ValidationBehavior <TestCommand, Unit>(
                new List <IValidator <TestCommand> >());

            var testCommand = new TestCommand();
            var testHandler = new TestCommandHandler();

            var unit = await validationPipeline.Handle(testCommand,
Beispiel #7
0
            public void Can_Be_Successfully_Constructed()
            {
                //Arrange

                //Act
                var handler = new TestCommandHandler(Mock.Of <IDbContext>(), Mock.Of <IMessageDispatcher>(), Mock.Of <IGWLogger <BaseMessageHandler <TestCommand> > >());

                //Assert
                Assert.That(handler, Is.Not.Null);
            }
        public void ShouldCallOnCommandExecuted()
        {
            var command = new TestCommand
            {
                Value = "Hello"
            };
            var commandHandler = new TestCommandHandler();

            commandHandler.Execute(command);
            Assert.AreEqual("Hello", commandHandler.AggregateRoot.Value);
        }
        public void noncancelable_commands_will_ignore_cancel()
        {
            var bus     = new CommandBus("local");
            var handler = new TestCommandHandler();

            bus.Subscribe((IHandleCommand <TestCommands.TestCommand3>)handler);
            var cmd = new TestCommands.TestCommand3(Guid.NewGuid(), null);

            Task.Delay(100).ContinueWith(t => bus.RequestCancel(cmd));

            bus.Fire(cmd);
        }
        public void CommandHandler_SubscribeShouldCallCommandBusSubscribe()
        {
            var commandBus = new Mock<ICommandBus>();

            var commandHandler = new TestCommandHandler(commandBus.Object);

            commandBus.Setup(x => x.Subscribe(commandHandler)).Verifiable();

            commandHandler.Subscribe();

            commandBus.Verify(x => x.Subscribe(commandHandler), Times.Once);
        }
Beispiel #11
0
        public async Task HandlerInvokerTest()
        {
            //ARRANGE
            var result         = 0;
            var command        = new TestCommand(Guid.NewGuid(), Guid.NewGuid());
            var handler        = new TestCommandHandler(() => result = 10);
            var handlerInvoker = new HandlerInvoker();
            //ACT
            await handlerInvoker.InvokeHandlers(new[] { handler }, command);

            //ASSERT
            Assert.AreEqual(10, result);
        }
Beispiel #12
0
            public async Task Should_Invoke_Registered_Command_Handler()
            {
                var commandHandler = new TestCommandHandler(_outputHelper);
                var registration   = new CommandHandlerRegistration();

                registration.Register(() => (ICommandAsyncHandler <DoSomethingCommand>)commandHandler);

                var dispatcher = new CommandDispatcher(registration);
                await dispatcher.DispatchAsync(new DoSomethingCommand());

                Assert.Equal(1, commandHandler.HandledCommands.Count);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand);
            }
Beispiel #13
0
        public async Task Given_TestCommand_When_SendAsync_Then_CommandHandlerIsFired()
        {
            //Arrange
            var command                  = new TestCommand();
            var commandHandler           = new TestCommandHandler();
            Func <Type, object> resolver = type => { return(commandHandler); };
            var commandBus               = new CommandBus(resolver);
            //Act
            await commandBus.SendAsync(command);

            //Assert
            Assert.That(commandHandler.IsFired, Is.True);
        }
        public async Task Handle_Success_Should_LogInitial_Detail_SpanishText()
        {
            var logger             = Mock.Of <ILogger <TestCommand> >();
            var requestInformation = new RequestInformation <TestCommand>();
            var describer          = new QuickerSpanishLoggingDescriber();

            IPipelineBehavior <TestCommand, Unit> loggingPipeline = new LoggingBehavior <TestCommand, Unit>(
                logger, requestInformation, describer);

            var testCommand = new TestCommand();
            var testHandler = new TestCommandHandler();

            var unit = await loggingPipeline.Handle(testCommand,
        public void ShouldEmitEventsToStream()
        {
            var streams = new InMemoryEventStreams();
            var handler = new TestCommandHandler();
            var command = new TestCommand {
                Value = "test"
            };

            handler.Execute(command);
            var stream = streams.GetStream("MyTestStream");

            Assert.AreEqual(1, stream.Count, "stream.Count was not 1");
            Assert.AreEqual("TestEvent", stream.First().EventName);
        }
        public void AuditDecorator_Calls_Command()
        {
            var commandHandler = new TestCommandHandler();
            var command        = new TestCommand("Value");
            var decorator      = new AuditDecorator <TestCommand>(_repository, _serializer)
            {
                Handler = commandHandler
            };

            var result = decorator.Execute(command);

            result.Errors.Should().HaveCount(1);
            result.Errors.First().Message.Should().Be("Error success");
        }
Beispiel #17
0
        public async Task ExecuteAsync_WhenHandlerIsRegistered_ExecutesHandler()
        {
            var handlerWasCalled = false;
            var handler          = new TestCommandHandler(() => handlerWasCalled = true);

            var serviceProvider = Substitute.For <IServiceProvider>();

            serviceProvider.GetService(typeof(ICommandHandler <TestCommand>))
            .Returns(handler);

            var commandExecutor = new CommandDispatcher(serviceProvider);
            await commandExecutor.ExecuteAsync(new TestCommand());

            handlerWasCalled.Should().BeTrue();
        }
        public void CoreDispatcher_RemoveHandlerFromDispatcher_CommandHandler()
        {
            var h = new TestCommandHandler();

            CoreDispatcher.AddHandlerToDispatcher(h);

            var coreHandler = CoreDispatcher.TryGetHandlersForCommandType(typeof(TestCommand));

            coreHandler.Should().NotBeEmpty();

            CoreDispatcher.RemoveHandlerFromDispatcher(h);

            coreHandler = CoreDispatcher.TryGetHandlersForCommandType(typeof(TestCommand));
            coreHandler.Should().BeEmpty();
        }
Beispiel #19
0
        public void HandlerDelegateFactoryTest()
        {
            //ARRANGE
            var result  = 0;
            var command = new TestCommand(Guid.NewGuid(), Guid.NewGuid());
            var handler = new TestCommandHandler(() => result = 10);

            //ACT
            var del = HandlerDelegateFactory.GetdMessageHandlerDelegate(typeof(TestCommandHandler), typeof(TestCommand));

            del(handler, new[] { command });

            //ASSERT
            Assert.AreEqual(10, result);
        }
Beispiel #20
0
            public async Task Should_Invoke_Registered_Command_Handler_In_Container()
            {
                var commandHandler = new TestCommandHandler(_outputHelper);
                var container      = new Container();

                container.Register <ICommandHandler <DoSomethingCommand> >(() => commandHandler, Lifestyle.Singleton);

                var containerAdapter = new SimpleInjectorContainerAdapter(container);
                var dispatcher       = new CommandDispatcher(new ContainerCommandHandlerResolver(containerAdapter)); // Sync handler resolver

                await dispatcher.DispatchAsync(new DoSomethingCommand());

                Assert.Equal(1, commandHandler.HandledCommands.Count);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand);
            }
Beispiel #21
0
        public async Task FactMethodName_IsSuccess_Should_CallProcessMethod()
        {
            var configuration      = new StopwatchConfiguration(true, 50, 50, 50, 50);
            var requestProcessor   = Mock.Of <IRequestProcessor <TestCommand> >();
            var requestInformation = new RequestInformation <TestCommand>
            {
                Elapsed = 500
            };

            IPipelineBehavior <TestCommand, Unit> stopwatchPipeline = new StopwatchBehavior <TestCommand, Unit>(
                configuration, requestInformation, requestProcessor);

            var testCommand = new TestCommand();
            var testHandler = new TestCommandHandler();

            var unit = await stopwatchPipeline.Handle(testCommand,
Beispiel #22
0
        public async Task Given_TestCommand_When_SendAsync_Then_CommandHandlerIsFired()
        {
            //Arrange
            var services       = new ServiceCollection();
            var command        = new TestCommand();
            var commandHandler = new TestCommandHandler();

            services.AddScoped <ICommandHandler <TestCommand> >(provider => commandHandler);
            var serviceProvider = services.BuildServiceProvider();
            var commandBus      = new CommandBus(serviceProvider.GetService);
            //Act
            await commandBus.SendAsync(command);

            //Assert
            Assert.That(commandHandler.IsFired, Is.True);
        }
        public void AuditDecorator_Succeeds()
        {
            var commandHandler = new TestCommandHandler();
            var command        = new TestCommand("Value");
            var decorator      = new AuditDecorator <TestCommand>(_repository, _serializer)
            {
                Handler = commandHandler
            };

            decorator.Execute(command);

            _context.CommandExecutions.Should().HaveCount(1);
            _context.CommandExecutions.First().Date.Should().BeCloseTo(DateTime.UtcNow, 1000);
            _context.CommandExecutions.First().CommandType.Should().Be("AzurePlayground.CommandHandlers.Tests.Decorators.AuditDecoratorTests+TestCommand");
            _context.CommandExecutions.First().CommandData.Should().Be(_serializer.SerializeToJson(command));
        }
Beispiel #24
0
        public TestCommand()
            : base("test", "Test a database connection to see whether it is available.")
        {
            var timeoutOption = new Option <int>(
                "--timeout",
                getDefaultValue: () => 10,
                description: "A timeout (in seconds) to wait for."
                );

            AddOption(timeoutOption);

            Handler = CommandHandler.Create <FileInfo, IConsole, int, CancellationToken>((config, console, timeout, cancellationToken) =>
            {
                var handler = new TestCommandHandler(config);
                return(handler.HandleCommandAsync(console, timeout, cancellationToken));
            });
        }
Beispiel #25
0
            public void ShouldResolveAsyncCommandHandlerFromContainer()
            {
                var commandHandler = new TestCommandHandler(_outputHelper);

                IMessageHandlerResolver resolver = CreateContainerCommandAsyncHandlerResolver(container =>
                {
                    container.RegisterSingleton <ICommandAsyncHandler <TestCommand> >(commandHandler);
                });

                MessageHandlerDelegate commandHandlerDelegate = resolver.ResolveMessageHandler(typeof(TestCommand));

                // Delegate should invoke the actual command handler - TestCommandHandler.
                commandHandlerDelegate.Invoke(new TestCommand());

                commandHandler.HandledCommands.Should().HaveCount(1);
                commandHandler.HasHandledCommand <TestCommand>().Should().BeTrue();
            }
            public void Should_Register_All_Command_Handlers()
            {
                var commandHandler = new TestCommandHandler(_testOutputHelper);

                var registration = new CommandHandlerRegistration();

                registration.Register(() => (ICommandHandler <DoSomethingCommand>)commandHandler);

                CommandHandlerDelegate commandHandlerDelegate = registration.ResolveCommandHandler <DoSomethingCommand>();

                Assert.NotNull(commandHandlerDelegate);

                // Delegate should invoke the actual command handler - TestCommandHandler.
                commandHandlerDelegate.Invoke(new DoSomethingCommand());

                Assert.Equal(1, commandHandler.HandledCommands.Count);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand);
            }
Beispiel #27
0
        public void ShouldValidateSuccessfulSendCommand()
        {
            var handler = new TestCommandHandler(_messageRepository);

            var testMessage = new TestCommand()
            {
                HelloMessage  = "Olá Mundo!",
                MessageId     = Guid.NewGuid(),
                PublisherName = nameof(InMemoryBusTests),
                Timestamp     = DateTime.Now,
            };

            _inMemomoryBus.Receive(handler);

            _inMemomoryBus.Send(testMessage);


            Assert.AreEqual(testMessage, _messageRepository.GetMessageById(testMessage.MessageId));
        }
            public async Task Should_Invoke_The_Actual_Registered_Command_Handler()
            {
                var commandHandler = new TestCommandHandler(_testOutputHelper);

                var registration = new CommandHandlerRegistration();

                registration.Register(() => (ICommandHandler <DoSomethingCommand>)commandHandler);

                CommandHandlerDelegate commandHandlerDelegate = registration.ResolveCommandHandler <DoSomethingCommand>();

                Assert.NotNull(commandHandlerDelegate);

                // Invoke.
                await commandHandlerDelegate.Invoke(new DoSomethingCommand());

                // Check if actual command handler instance was invoked.
                Assert.Equal(1, commandHandler.HandledCommands.Count);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand);
            }
Beispiel #29
0
        public async Task HandlerInvokerTest()
        {
            //ARRANGE
            var result         = 0;
            var command        = new TestCommand(Guid.NewGuid(), Guid.NewGuid());
            var handler        = new TestCommandHandler(() => result = 10);
            var handlerInvoker = new HandlerInvoker();
            var serialised     = JsonConvert.SerializeObject(command, command.GetType(), new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Objects
            });
            var deserialised = JsonConvert.DeserializeObject(serialised, new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Objects
            });
            //ACT
            await handlerInvoker.InvokeHandlers(new[] { handler }, (object)deserialised);

            //ASSERT
            Assert.AreEqual(10, result);
        }
Beispiel #30
0
            public async Task Should_Invoke_Registered_Command_Handler_With_Composite_Resolver()
            {
                var commandHandler = new TestCommandHandler(_outputHelper);
                var container      = new Container();

                container.Register <ICommandHandler <DoSomethingCommand> >(() => commandHandler, Lifestyle.Singleton);
                container.Register <ICommandAsyncHandler <DoSomethingWithCancellationCommand> >(() => commandHandler, Lifestyle.Singleton);

                var containerAdapter = new SimpleInjectorContainerAdapter(container);
                var containerAsyncHandlerResolver = new ContainerCommandAsyncHandlerResolver(containerAdapter);
                var containerHandlerResolver      = new ContainerCommandHandlerResolver(containerAdapter);

                Func <Exception, bool> exceptionHandler = (ex) =>
                {
                    var exception = ex as NoCommandHandlerResolvedException;
                    if (exception != null)
                    {
                        _outputHelper.WriteLine($"Ignoring encountered exception while trying to resolve command handler for {exception.CommandType.Name}...");

                        // Notify as handled if no command handler is resolved from other resolvers.
                        return(true);
                    }

                    return(false);
                };

                var compositeResolver = new CompositeCommandHandlerResolver(new List <ICommandHandlerResolver>()
                {
                    containerAsyncHandlerResolver,
                    containerHandlerResolver
                }, exceptionHandler);                                      // Pass in an exception handler.

                var dispatcher = new CommandDispatcher(compositeResolver); // Composite resolver

                await dispatcher.DispatchAsync(new DoSomethingCommand());

                await dispatcher.DispatchAsync(new DoSomethingWithCancellationCommand());

                Assert.Equal(2, commandHandler.HandledCommands.Count);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingWithCancellationCommand);
            }
            public void ShouldRegisterCommandAsyncHandler()
            {
                var commandHandler = new TestCommandHandler(_outputHelper);

                var registration = new SingleMessageHandlerRegistration();

                registration.RegisterCommandHandler(() => commandHandler.AsCommandAsyncHandler <TestCommand>());

                IMessageHandlerResolver resolver = registration.BuildMessageHandlerResolver();

                MessageHandlerDelegate commandHandlerDelegate = resolver.ResolveMessageHandler(typeof(TestCommand));

                commandHandlerDelegate.Should().NotBeNull();

                // Delegate should invoke the actual command handler - TestCommandHandler.
                commandHandlerDelegate.Invoke(new TestCommand());

                commandHandler.HandledCommands.Should().HaveCount(1);
                commandHandler.HasHandledCommand <TestCommand>().Should().BeTrue();
            }
Beispiel #32
0
 protected override void BeforeScenario()
 {
     _commandHandler = new TestCommandHandler();
     _childCommandHandler = new TestChildCommandHandler();
     _commandBus = new CommandExecutor(new ICommandHandler[] { _commandHandler, _childCommandHandler });
 }