Example #1
0
        public void DefaultConstructorConfiguresPowerShellHosting()
        {
            TestCommand cmd = new TestCommand();

            Assert.IsType<PowerShellHostEnvironment>(cmd.HostEnvironment);
            Assert.IsType<PowerShellInvoker>(cmd.Invoker);
        }
Example #2
0
		public void CommandCallsFinalize()
		{
			TestCommand cmd = new TestCommand();
			cmd.Finish += new EventHandler(OnFinish);
			cmd.BeginInvoke();
			WaitOnBool(ref _onFinishCalled);
		}
 public void Specifying_too_many_arguments_will_send_error()
 {
     var stream = new MemoryStream();
     var cmd = new TestCommand(stream);
     bool result = cmd.Init("b", "1", "2", "3","noreply","3");
     Assert.IsFalse(result);
     Assert.AreEqual("CLIENT_ERROR Expected to get 'test <key> <flags> <exptime> <bytes> [noreply]'\r\n", ReadAll(stream));
 }
 public void When_calling_send_to_client_when_noreply_specified_will_NOT_write_to_stream()
 {
     var stream = new MemoryStream();
     var cmd = new TestCommand(stream);
     cmd.Init("my_key", "1234", "1", "50", "noreply");
     cmd.SendToClient();
     Assert.AreEqual("", ReadAll(stream));
 }
 public void When_calling_send_to_client_will_write_to_stream()
 {
     var stream = new MemoryStream();
     var cmd = new TestCommand(stream);
     cmd.Init("my_key", "1234", "1", "50");
     cmd.SendToClient();
     Assert.AreEqual("foo\r\n", ReadAll(stream));
 }
 public void When_expiry_is_larger_than_30_days_will_use_unix_epoch()
 {
     var stream = new MemoryStream();
     var cmd = new TestCommand(stream);
     string expiry = TimeSpan.FromDays(31).TotalSeconds.ToString();
     cmd.Init("my_key", "1234", expiry, "50", "noreply");
     Assert.AreEqual(new DateTime(1970, 1, 1).AddDays(31), cmd.ExpiresAt);
 }
        public void RegisterACommandShouldRaiseCanExecuteEvent()
        {
            TestableCompositeCommand multiCommand = new TestableCompositeCommand();
            TestCommand testCommand = new TestCommand();

            multiCommand.RegisterCommand(new TestCommand());
            Assert.True(multiCommand.CanExecuteChangedRaised);
        }
        public void CommandPropertyShouldBeValidatedObject()
        {
            var command = new TestCommand();
            var wrapper = new AsyncCommand(command);

            ValidationContext.Ensure(wrapper).IsValid();

            Assert.IsFalse(ValidationContext.IsValid);
        }
 public void When_initializing_will_parse_command_line_without_noreply()
 {
     var cmd = new TestCommand(new MemoryStream());
     cmd.Init("my_key", "1234", "60", "50");
     Assert.AreEqual("my_key", cmd.Key);
     Assert.AreEqual(1234, cmd.Flags);
     Assert.AreEqual(new DateTime(2000, 1, 1, 0, 1, 0), cmd.ExpiresAt);
     Assert.AreEqual(50, cmd.BytesCount);
     Assert.IsFalse(cmd.NoReply);
 }
 public void When_initializing_will_parse_command_line_with_noreply()
 {
     var stream = new MemoryStream();
     var cmd = new TestCommand(stream);
     cmd.Init("my_key", "1234", "60", "50", "noreply");
     Assert.AreEqual("my_key", cmd.Key);
     Assert.AreEqual(1234, cmd.Flags);
     Assert.AreEqual(new DateTime(2000, 1, 1, 0, 1, 0), cmd.ExpiresAt);
     Assert.IsTrue(cmd.NoReply);
 }
        public void Setup()
        {
            command = new TestCommand();
            commandHandler = Substitute.For<IAsyncCommandHandler<TestCommand>>();
            
            commandHandlerResolver = Substitute.For<ICommandHandlerResolver>();
            commandHandlerResolver.ResolveCommandHandler<IAsyncCommandHandler<TestCommand>>().Returns(commandHandler);

            sut = new AsyncCommandBus(commandHandlerResolver);
        }
        public void SetUp()
        {
            configFile = Path.GetTempFileName();
            sessionFactory = Substitute.For<IOctopusSessionFactory>();
            command = new TestCommand(sessionFactory, Substitute.For<ILog>());

            session = Substitute.For<IOctopusSession>();
            sessionFactory.OpenSession(Arg.Any<Uri>(), Arg.Any<NetworkCredential>(), Arg.Any<string>(), Arg.Any<bool>()).Returns(session);
            session.RootDocument.Returns(new RootDocument());
        }
        public async void Execute_ExecuteSuccessfulCommand_Successful()
        {
            // arrange
            var command = new TestCommand(canExecute: true, executeResultSuccessful: true);

            // act
            var commandResult = await this.CommandExecutor.ExecuteAsync(command);

            // assert
            Assert.IsTrue(commandResult.IsSuccess);
        }
Example #14
0
        public void CanExecuteShouldReturnTrueIfAllRegistrantsTrue()
        {
            TestableCompositeCommand multiCommand = new TestableCompositeCommand();
            TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
            TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = true };

            multiCommand.RegisterCommand(testCommandOne);
            multiCommand.RegisterCommand(testCommandTwo);

            Assert.True(multiCommand.CanExecute(null));
        }
        public async void Execute_ExecuteFailingCommand_Failure()
        {
            // arrange
            var command = new TestCommand(canExecute: true, executeResultSuccessful: false);

            // act
            var commandResult = await this.CommandExecutor.ExecuteAsync(command);

            // assert
            Assert.IsFalse(commandResult.IsSuccess);
        }
Example #16
0
        public void ShouldDelegateCanExecuteToSingleRegistrant()
        {
            TestableCompositeCommand multiCommand = new TestableCompositeCommand();
            TestCommand testCommand = new TestCommand();

            multiCommand.RegisterCommand(testCommand);

            Assert.False(testCommand.CanExecuteCalled);
            multiCommand.CanExecute(null);
            Assert.True(testCommand.CanExecuteCalled);
        }
        public void CallTheInnerMediatorSend()
        {
            var mocks = new MockRepository();
            var innerMediator = MockInnerMediator();

            var command = new TestCommand();
            innerMediator.Expect(m => m.Send(command))
                .Repeat.Once();
            Mediator.Send(command);

            mocks.VerifyAll();
        }
        public void ItShouldBePossibleToCancelCommandSendingThroughSendingEvent()
        {
            var command = new TestCommand();
            _bus.Setup(x => x.Send(
                It.IsAny<IAsyncCommandEnqueuingMessage<TestCommand>>()))
                .Callback<IApplicationBusMessage>(x => ((IAsyncCommandEnqueuingMessage<TestCommand>)x).CancelEnqueuing());

            _dispatcher.Handle(new AsyncCommand(command));

            _queueMock.Verify(x => x.Enqueue(It.IsAny<CommandBase>()), Times.Never());
            _bus.Verify(x => x.Send(It.IsAny<IAsyncCommandEnqueuedMessage<TestCommand>>()), Times.Never());
        }
Example #19
0
        public void Send_Should_invoke_the_commandhandler()
        {
            var commandhandler = MockRepository.GenerateStrictMock<ICommandHandler<TestCommand>>();
            commandHandlerFactory.Stub(f => f.CreateHandler<TestCommand>()).Return(commandhandler);

            var command = new TestCommand();
            commandhandler.Expect(h => h.Handle(command))
                          .Message("The commandhandler was not invoked in the expected way");

            commandBus.Send(command);

            commandhandler.VerifyAllExpectations();
        }
        public async Task handler_is_being_invoked()
        {
            var container = Substitute.For<IContainer>();
            var scope = Substitute.For<IContainerScope>();
            var handler = Substitute.For<ICommandHandler<TestCommand>>();
            var command = new TestCommand();
            container.CreateScope().Returns(scope);
            scope.ResolveAll<ICommandHandler<TestCommand>>().Returns(new[]{handler});

            var sut = new IocCommandBus(container);
            await sut.ExecuteAsync(command);

            handler.Received().ExecuteAsync(command);
        }
Example #21
0
        public void IsSerializableAndDeserializableInJson()
        {
            var command1 = new TestCommand();

            string output = JsonConvert.SerializeObject(command1);

            Assert.NotNull(output);
            Assert.True(output.Length > 0);

            var command2 = JsonConvert.DeserializeObject<TestCommand>(output);

            Assert.NotNull(command2);
            Assert.Equal(command1.Id, command2.Id);
        }
Example #22
0
		public void CommandCanBeCancelled()
		{
			TestCommand cmd = new TestCommand();
			cmd.BeginInvoke();
			Thread.Sleep(10);
			Assert.IsFalse(cmd.Enabled);
			cmd.Cancel();
			Assert.IsTrue(cmd.Canceling);
			WaitOnBool(ref cmd.wasCancelled);
			//no: it doesn't do this            Assert.IsTrue(cmd.Enabled);

			//todo: I can't see a way to know that it ended, if you cancel it.
			//finish isn't called. Should it be ?
		}
Example #23
0
        public void ShouldDelegateCanExecuteToMultipleRegistrants()
        {
            TestableCompositeCommand multiCommand = new TestableCompositeCommand();
            TestCommand testCommandOne = new TestCommand();
            TestCommand testCommandTwo = new TestCommand();

            multiCommand.RegisterCommand(testCommandOne);
            multiCommand.RegisterCommand(testCommandTwo);

            Assert.False(testCommandOne.CanExecuteCalled);
            Assert.False(testCommandTwo.CanExecuteCalled);
            multiCommand.CanExecute(null);
            Assert.True(testCommandOne.CanExecuteCalled);
            Assert.True(testCommandTwo.CanExecuteCalled);
        }
		public async Task Execute_ShouldCallInnerCommandHandlers(
			IEnumerable<Mock<IAsyncCommandHandler<TestCommand>>> commandHandlers,
			TestCommand command)
		{
			//arrange
			var sut = new CompositeCommandHandler<TestCommand>(commandHandlers.Select(c => c.Object));

			//act
			await sut.Execute(command);

			//assert
			foreach (var commandHandler in commandHandlers)
			{
				commandHandler.Verify(c => c.Execute(command), Times.Once());
			}
		}
        public void ItShouldRaiseSentEventAfterCommandSending()
        {
            var command = new TestCommand();
            _bus.Setup(x => x.Send(
                It.IsAny<IAsyncCommandEnqueuedMessage<TestCommand>>()))
                .Callback(() => Assert.IsTrue(command.Executed));

            _bus.Setup(x => x.Send(It.IsAny<IAsyncCommandEnqueuedMessage<TestCommand>>()))
                .Callback<IApplicationBusMessage>(
                    x => Assert.AreSame(((IAsyncCommandEnqueuedMessage<TestCommand>)x).Command, command));

            _dispatcher.Handle(new AsyncCommand(command));

            _bus.Verify(x => x.Send(
                It.IsAny<IAsyncCommandEnqueuedMessage<TestCommand>>()), Times.Once());
        }
        public void CallTheInnerHandler()
        {
            var mockRepository = new MockRepository();
            var command = new TestCommand();
            var commandHandler = mockRepository.StrictMock<ICommandHandler<TestCommand>>();
            var publisher = mockRepository.DynamicMock<IDomainEventsPublisher>();
            var decorator = new DomainEventsPublisherCommandHandler<TestCommand>(commandHandler, publisher);

            using (mockRepository.Record())
                commandHandler
                    .Expect(h => h.Handle(command))
                    .Repeat.Once();

            using (mockRepository.Playback())
                decorator.Handle(command);

            mockRepository.VerifyAll();
        }
		public async Task Process_ShouldRunCorrectNumberOfConcurrentInnerProcessCommand(
			[Frozen]Mock<IAsyncCommandBus> mockCommandBus,
			ConcurrencyExecutionAsyncCommandBus sut,
			TestCommand command)
		{
			//arrange
			mockCommandBus.Setup(m => m.ProcessCommand(It.IsAny<TestCommand>()))
				.ReturnsDefaultTask();
			sut.ForCommand<TestCommand>(1);

			//act
			var t1 = Task.Run(() => sut.ProcessCommand(command));
			var t2 = Task.Run(() => sut.ProcessCommand(command));
			await Task.WhenAll(t1, t2);

			//assert
			mockCommandBus.Verify(m => m.ProcessCommand(command), Times.Exactly(2));
		}
        public void ShouldExecuteReferencedCommand()
        {
            bool canExecuteChangedCalled = false;
            TestCommand testCommand = new TestCommand();
            CommandReference commandReference = new CommandReference { Command = testCommand };
            commandReference.CanExecuteChanged += ((sender, eventArgs) => canExecuteChangedCalled = true);

            object canExecuteParameter = new object();
            bool canExecute = commandReference.CanExecute(canExecuteParameter);
            Assert.IsTrue(canExecute);
            Assert.AreSame(canExecuteParameter, testCommand.CanExecuteParameter);

            object executeParameter = new object();
            commandReference.Execute(executeParameter);
            Assert.AreSame(executeParameter, testCommand.ExecuteParameter);

            Assert.IsFalse(canExecuteChangedCalled);
        }
Example #29
0
 public void TestEditingStackOperations()
 {
     var commands = new XTMFCommand[20];
     for ( int i = 0; i < commands.Length; i++ )
     {
         commands[i] = new TestCommand();
     }
     EditingStack stack = new EditingStack( 10 );
     Assert.AreEqual( 0, stack.Count, "The stack's count is incorrect!" );
     // fill the stack
     for ( int i = 0; i < 10; i++ )
     {
         stack.Add( commands[i] );
         Assert.AreEqual( i + 1, stack.Count, "The stack's count is incorrect!" );
     }
     // over fill the stack
     for ( int i = 10; i < 20; i++ )
     {
         stack.Add( commands[i] );
         Assert.AreEqual( 10, stack.Count, "The stack's count is incorrect!" );
     }
     // Make sure the first don't exist anymore
     for ( int i = 0; i < 10; i++ )
     {
         Assert.AreEqual( false, stack.Contains( commands[i] ), "The stack retained a command it should have lost!" );
     }
     // Make sure the newer ones still exist
     for ( int i = 10; i < 20; i++ )
     {
         Assert.AreEqual( true, stack.Contains( commands[i] ), "The stack lost a command it should have retained!" );
     }
     XTMFCommand command;
     for ( int i = 19; i >= 10; i-- )
     {
         if ( stack.TryPop( out command ) )
         {
             Assert.AreEqual( commands[i], command, "While popping we popped an unexpected command!" );
         }
         else
         {
             Assert.Fail( "A pop failed that should have succeeded!" );
         }
     }
 }
        public void ExecuteWithValidCommandExecutesCommand()
        {
            var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
            var commandHandlerMock = new Mock<ICommandHandler<TestCommand>>(MockBehavior.Strict);

            var sut = new CommandProcessor(serviceProviderMock.Object);

            var command = new TestCommand();

            serviceProviderMock
                .Setup(sp => sp.GetService(typeof(ICommandHandler<TestCommand>)))
                .Returns(commandHandlerMock.Object);

            commandHandlerMock.Setup(ch => ch.Handle(command));

            sut.Execute(command);

            serviceProviderMock.VerifyAll();
            commandHandlerMock.VerifyAll();
        }
Example #31
0
 /// <summary>
 ///     Wrap a command and return the result.
 /// </summary>
 /// <param name="command">The command to be wrapped</param>
 /// <returns>The wrapped command</returns>
 public TestCommand Wrap(TestCommand command) =>
 new RetryCommand(innerCommand: command, tryCount: this._tryCount);
Example #32
0
 public SetCultureCommand(TestCommand command) : base(command)
 {
 }
Example #33
0
 public IActionResult Pass([FromBody] TestCommand test)
 {
     return(PublishCommand(test));
 }
Example #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomRetryCommand"/> class.
 /// </summary>
 /// <param name="innerCommand">The inner command.</param>
 /// <param name="retryCount">The number of repetitions</param>
 public CustomRetryCommand(TestCommand innerCommand, int retryCount)
     : base(innerCommand)
 {
     _retryCount = retryCount;
 }
Example #35
0
 public UnobservedTaskExceptionCommand(TestCommand innerCommand)
     : base(innerCommand)
 {
 }
Example #36
0
 /// <inheritdoc/>
 public TestCommand Wrap(TestCommand command)
 {
     return(new TimeoutCommand(command, this._timeout));
 }
Example #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DependencyGroupCommand"/> class.
 /// </summary>
 /// <param name="innerCommand">The inner <see cref="TestCommand"/>.</param>
 /// <param name="group">The group name.</param>
 public DependencyGroupCommand(TestCommand innerCommand, string group) : base(innerCommand)
 {
     _group = Check.NotEmpty(group, nameof(group));
 }
Example #38
0
 /// <summary>
 /// Wrap a command and return the result.
 /// </summary>
 /// <param name="command">The command to be wrapped</param>
 /// <returns>The wrapped command</returns>
 public TestCommand Wrap(TestCommand command)
 {
     return(new RetryCommand(command, _tryCount));
 }
 public ExpectedExceptionCommand(TestCommand innerCommand, Type expectedType)
     : base(innerCommand)
 {
     this._expectedType = expectedType;
 }
 public TestCommand Wrap(TestCommand command)
 {
     return(new ExpectedExceptionCommand(command, this.expectedExceptionType));
 }
Example #41
0
        protected override IEnumerable PerformWork()
        {
            if (IsCancelledRun())
            {
                yield break;
            }

            if (m_DontRunRestoringResult)
            {
                if (EditModeTestCallbacks.RestoringTestContext == null)
                {
                    throw new NullReferenceException("RestoringTestContext is not set");
                }
                EditModeTestCallbacks.RestoringTestContext();
                Result = Context.CurrentResult;
                yield break;
            }

            try
            {
                if (IsCancelledRun())
                {
                    yield break;
                }

                if (m_Command is SkipCommand)
                {
                    m_Command.Execute(Context);
                    Result = Context.CurrentResult;
                    yield break;
                }

                //Check if we can execute this test
                var firstEnumerableCommand = FindFirstIEnumerableTestMethodCommand(m_Command);
                if (firstEnumerableCommand == null)
                {
                    Context.CurrentResult.SetResult(ResultState.Error, "Returning IEnumerator but not using test attribute supporting this");
                    yield break;
                }

                if (m_Command.Test.Method.ReturnType.IsType(typeof(IEnumerator)))
                {
                    if (m_Command is ApplyChangesToContextCommand)
                    {
                        var applyChangesToContextCommand = ((ApplyChangesToContextCommand)m_Command);
                        applyChangesToContextCommand.ApplyChanges(Context);
                        m_Command = applyChangesToContextCommand.GetInnerCommand();
                    }

                    var innerCommand = m_Command as IEnumerableTestMethodCommand;
                    if (innerCommand == null)
                    {
                        Debug.Log("failed getting innerCommand");
                        throw new Exception("Tests returning IEnumerator can only use test attributes handling those");
                    }

                    foreach (var workItemStep in innerCommand.ExecuteEnumerable(Context))
                    {
                        if (IsCancelledRun())
                        {
                            yield break;
                        }

                        if (workItemStep is TestEnumerator)
                        {
                            if (EnumeratorStepHelper.UpdateEnumeratorPcIfNeeded(TestEnumerator.Enumerator))
                            {
                                yield return(new RestoreTestContextAfterDomainReload());
                            }
                            continue;
                        }

                        if (workItemStep is AsyncOperation)
                        {
                            var asyncOperation = (AsyncOperation)workItemStep;
                            while (!asyncOperation.isDone)
                            {
                                if (IsCancelledRun())
                                {
                                    yield break;
                                }

                                yield return(null);
                            }
                            continue;
                        }

                        ResultedInDomainReload = false;

                        if (workItemStep is IEditModeTestYieldInstruction)
                        {
                            var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)workItemStep;
                            yield return(editModeTestYieldInstruction);

                            var enumerator = editModeTestYieldInstruction.Perform();
                            while (true)
                            {
                                bool moveNext;
                                try
                                {
                                    moveNext = enumerator.MoveNext();
                                }
                                catch (Exception e)
                                {
                                    Context.CurrentResult.RecordException(e);
                                    break;
                                }

                                if (!moveNext)
                                {
                                    break;
                                }
                                yield return(null);
                            }
                        }
                        else
                        {
                            yield return(workItemStep);
                        }
                    }

                    Result = Context.CurrentResult;
                    EditorApplication.isPlaying = false;
                    yield return(null);
                }
            }
            finally
            {
                WorkItemComplete();
            }
        }
Example #42
0
        private static IEnumerableTestMethodCommand FindFirstIEnumerableTestMethodCommand(TestCommand command)
        {
            if (command == null)
            {
                return(null);
            }

            if (command is IEnumerableTestMethodCommand)
            {
                return((IEnumerableTestMethodCommand)command);
            }

            if (command is DelegatingTestCommand)
            {
                var delegatingTestCommand = (DelegatingTestCommand)command;
                return(FindFirstIEnumerableTestMethodCommand(delegatingTestCommand.GetInnerCommand()));
            }
            return(null);
        }
Example #43
0
 public EditorEnumeratorTestWorkItem(TestMethod test, ITestFilter filter)
     : base(test, null)
 {
     m_Command = TestCommandBuilder.BuildTestCommand(test, filter);
 }
Example #44
0
 public TestCommand Wrap(TestCommand command)
 {
     return(null);
 }
 public UnityLogCheckDelegatingCommand(TestCommand innerCommand)
     : base(innerCommand)
 {
 }
 public ExpectedExceptionCommand(TestCommand innerCommand)
     : base(innerCommand)
 {
 }
Example #47
0
 public TimeoutCommand(TestCommand innerCommand, int timeout) : base(innerCommand)
 {
     _timeout = timeout;
 }
 public TestCommand Wrap(TestCommand command)
 {
     return(new ExpectedExceptionCommand(command));
 }
Example #49
0
 TestCommand ICommandWrapper.Wrap(TestCommand command)
 {
     return(new MaxTimeCommand(command, _milliseconds));
 }
 public ClickEventCommandOrderButtonBase()
 {
     Command = new TestCommand();
     Click  += OnClick;
     OnClick();
 }
Example #51
0
 /// <summary>
 /// Wraps the current test command in a <see cref="UnobservedTaskExceptionCommand"/>.
 /// </summary>
 /// <param name="command">the test command</param>
 /// <returns>the wrapped test command</returns>
 public TestCommand Wrap(TestCommand command)
 => new UnobservedTaskExceptionCommand(command);
 public void Setup()
 {
     _command = new TestCommand();
 }
Example #53
0
 /// <summary>
 /// Wrap a command and return the result.
 /// </summary>
 /// <param name="command">The command to be wrapped</param>
 /// <returns>The wrapped command</returns>
 public TestCommand Wrap(TestCommand command)
 {
     return(new CustomRetryCommand(command, _count));
 }
 public CustomCommand(TestCommand command) : base(innerCommand)
 {
     this.command = command;
 }
 public RetryCommand(TestCommand innerCommand, int tryCount, int timeout)
     : base(innerCommand)
 {
     _tryCount = tryCount;
     _timeout  = timeout;
 }
 public TestCommand Wrap(TestCommand command)
 {
     return(new CustomCommand(command));
 }
Example #57
0
 TestCommand ICommandDecorator.Decorate(TestCommand command)
 {
     return(new SetCultureCommand(command));
 }
 public TestCommand Wrap(TestCommand command)
 {
     return new ExpectedExceptionCommand(command, _expectedExceptionType);
 }
Example #59
0
        TestCommand ICommandWrapper.Wrap(TestCommand command)
        {
            var testMethod = (TestMethod)command.Test;

            return(GetTestCommand(testMethod, testMethod, ExpectedException, ExpectCompilerException));
        }
Example #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryCommand"/> class.
 /// </summary>
 /// <param name="innerCommand">The inner command.</param>
 /// <param name="tryCount">The maximum number of repetitions</param>
 public RetryCommand(TestCommand innerCommand, int tryCount)
     : base(innerCommand)
 {
     _tryCount = tryCount;
 }