public void Test_AsyncRelayCommand_WithCanExecuteFunctionFalse()
        {
            int ticks = 0;

            var command = new AsyncRelayCommand(
                () =>
            {
                ticks++;
                return(Task.CompletedTask);
            }, () => false);

            Assert.IsFalse(command.CanExecute(null));
            Assert.IsFalse(command.CanExecute(new object()));

            Assert.IsFalse(command.CanBeCanceled);
            Assert.IsFalse(command.IsCancellationRequested);

            command.Execute(null);

            Assert.AreEqual(ticks, 0);

            command.Execute(new object());

            Assert.AreEqual(ticks, 0);
        }
Example #2
0
        public async Task Test_AsyncRelayCommand_WithCancellation()
        {
            TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();

            var command = new AsyncRelayCommand(token => tcs.Task);

            Assert.IsTrue(command.CanExecute(null));
            Assert.IsTrue(command.CanExecute(new object()));

            Assert.IsTrue(command.CanBeCanceled);
            Assert.IsFalse(command.IsCancellationRequested);

            command.Execute(null);

            Assert.IsFalse(command.IsCancellationRequested);

            command.Cancel();

            Assert.IsTrue(command.IsCancellationRequested);

            tcs.SetResult(null);

            await command.ExecutionTask !;

            Assert.IsTrue(command.IsCancellationRequested);
        }
        public async Task CommandCanAlwaysBeInvokedDirectly_RegardlessWhetherTheCommandCanBeExecutedOrNot()
        {
            int                    number     = 0;
            bool                   canExecute = false;
            IAsyncCommand          command    = new AsyncRelayCommand(() => { number++; return(Task.CompletedTask); }, () => canExecute);
            IAsyncCommand <string> commandT   = new AsyncRelayCommand <string>(_ => { number--; return(Task.CompletedTask); }, _ => canExecute);

            Assert.False(command.CanExecute());
            await command.ExecuteAsync();

            Assert.Equal(1, number);
            Assert.False(commandT.CanExecute("F0"));
            await commandT.ExecuteAsync("F0");

            Assert.Equal(0, number);

            canExecute = true;

            Assert.True(command.CanExecute());
            await command.ExecuteAsync();

            Assert.Equal(1, number);
            Assert.True(commandT.CanExecute("F0"));
            await commandT.ExecuteAsync("F0");

            Assert.Equal(0, number);
        }
        public async Task Test_AsyncRelayCommand_WithCancellation()
        {
            TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();

            // We need to test the cancellation support here, so we use the overload with an input
            // parameter, which is a cancellation token. The token is the one that is internally managed
            // by the AsyncRelayCommand instance, and canceled when using IAsyncRelayCommand.Cancel().
            var command = new AsyncRelayCommand(token => tcs.Task);

            List <PropertyChangedEventArgs> args = new List <PropertyChangedEventArgs>();

            command.PropertyChanged += (s, e) => args.Add(e);

            // We have no canExecute parameter, so the command can always be invoked
            Assert.IsTrue(command.CanExecute(null));
            Assert.IsTrue(command.CanExecute(new object()));

            // The command isn't running, so it can't be canceled yet
            Assert.IsFalse(command.CanBeCanceled);
            Assert.IsFalse(command.IsCancellationRequested);

            // Start the command, which will return the token from our task completion source.
            // We can use that to easily keep the command running while we do our tests, and then
            // stop the processing by completing the source when we need (see below).
            command.Execute(null);

            // The command is running, so it can be canceled, as we used the token overload
            Assert.IsTrue(command.CanBeCanceled);
            Assert.IsFalse(command.IsCancellationRequested);

            // Validate the various event args for all the properties that were updated when executing the command
            Assert.AreEqual(args.Count, 4);
            Assert.AreEqual(args[0].PropertyName, nameof(IAsyncRelayCommand.IsCancellationRequested));
            Assert.AreEqual(args[1].PropertyName, nameof(IAsyncRelayCommand.ExecutionTask));
            Assert.AreEqual(args[2].PropertyName, nameof(IAsyncRelayCommand.IsRunning));
            Assert.AreEqual(args[3].PropertyName, nameof(IAsyncRelayCommand.CanBeCanceled));

            command.Cancel();

            // Verify that these two properties raised notifications correctly when canceling the command too.
            // We need to ensure all command properties support notifications so that users can bind to them.
            Assert.AreEqual(args.Count, 6);
            Assert.AreEqual(args[4].PropertyName, nameof(IAsyncRelayCommand.IsCancellationRequested));
            Assert.AreEqual(args[5].PropertyName, nameof(IAsyncRelayCommand.CanBeCanceled));

            Assert.IsTrue(command.IsCancellationRequested);

            // Complete the source, which will mark the command as completed too (as it returned the same task)
            tcs.SetResult(null);

            await command.ExecutionTask !;

            // Verify that the command can no longer be canceled, and that the cancellation is
            // instead still true, as that's reset when executing a command and not on completion.
            Assert.IsFalse(command.CanBeCanceled);
            Assert.IsTrue(command.IsCancellationRequested);
        }
        public void TheExecutionStatusLogicDeterminesWhetherTheAsyncRelayCommandCanExecuteInItsCurrentState()
        {
            bool                   canExecute = false;
            IAsyncCommand          command    = new AsyncRelayCommand(() => Task.CompletedTask, () => canExecute);
            IAsyncCommand <string> commandT   = new AsyncRelayCommand <string>(_ => Task.CompletedTask, _ => canExecute);

            Assert.False(command.CanExecute());
            Assert.False(commandT.CanExecute("F0"));

            canExecute = true;

            Assert.True(command.CanExecute());
            Assert.True(commandT.CanExecute("F0"));
        }
Example #6
0
        public void ActionPredicateInvocation()
        {
            IAsyncExecutionContext context = new AsyncExecutionContext();
            var invoked           = false;
            var canExecuteInvoked = false;

            ICommand rc = new AsyncRelayCommand(context,
                                                async(t) => invoked = true,
                                                () =>
            {
                canExecuteInvoked = true;
                return(true);
            });

            Assert.IsFalse(invoked);
            Assert.IsFalse(canExecuteInvoked);

            Assert.IsTrue(rc.CanExecute(null));

            Assert.IsFalse(invoked);
            Assert.IsTrue(canExecuteInvoked);

            canExecuteInvoked = false;

            rc.Execute(null);

            Assert.IsTrue(invoked);
            Assert.IsTrue(canExecuteInvoked);
        }
        public async Task Test_AsyncRelayCommand_AlwaysEnabled()
        {
            int ticks = 0;

            var command = new AsyncRelayCommand(async() =>
            {
                await Task.Delay(1000);
                ticks++;
                await Task.Delay(1000);
            });

            Assert.IsTrue(command.CanExecute(null));
            Assert.IsTrue(command.CanExecute(new object()));

            Assert.IsFalse(command.CanBeCanceled);
            Assert.IsFalse(command.IsCancellationRequested);

            (object, EventArgs)args = default;

            command.CanExecuteChanged += (s, e) => args = (s, e);

            command.NotifyCanExecuteChanged();

            Assert.AreSame(args.Item1, command);
            Assert.AreSame(args.Item2, EventArgs.Empty);

            Assert.IsNull(command.ExecutionTask);
            Assert.IsFalse(command.IsRunning);

            Task task = command.ExecuteAsync(null);

            Assert.IsNotNull(command.ExecutionTask);
            Assert.AreSame(command.ExecutionTask, task);
            Assert.IsTrue(command.IsRunning);

            await task;

            Assert.IsFalse(command.IsRunning);

            Assert.AreEqual(ticks, 1);

            command.Execute(new object());

            await command.ExecutionTask !;

            Assert.AreEqual(ticks, 2);
        }
Example #8
0
        public void TestCanExecuteYieldsTrueWithoutDelegate()
        {
            var cmd = new AsyncRelayCommand(() => Task.CompletedTask, null);

            bool canExecute = cmd.CanExecute();

            Assert.AreEqual(true, canExecute);
        }
        public async Task Test_AsyncRelayCommandOfT_AlwaysEnabled()
        {
            int ticks = 0;

            var command = new AsyncRelayCommand <string>(async s =>
            {
                await Task.Delay(1000);
                ticks = int.Parse(s);
                await Task.Delay(1000);
            });

            Assert.IsTrue(command.CanExecute(null));
            Assert.IsTrue(command.CanExecute("1"));

            (object, EventArgs)args = default;

            command.CanExecuteChanged += (s, e) => args = (s, e);

            command.NotifyCanExecuteChanged();

            Assert.AreSame(args.Item1, command);
            Assert.AreSame(args.Item2, EventArgs.Empty);

            Assert.IsNull(command.ExecutionTask);
            Assert.IsFalse(command.IsRunning);

            Task task = command.ExecuteAsync((object)"42");

            Assert.IsNotNull(command.ExecutionTask);
            Assert.AreSame(command.ExecutionTask, task);
            Assert.IsTrue(command.IsRunning);

            await task;

            Assert.IsFalse(command.IsRunning);

            Assert.AreEqual(ticks, 42);

            command.Execute("2");

            await command.ExecutionTask !;

            Assert.AreEqual(ticks, 2);

            Assert.ThrowsException <InvalidCastException>(() => command.Execute(new object()));
        }
        public void TheDefaultReturnValueForTheCanExecuteMethodIsTrue()
        {
            IAsyncCommand          command  = new AsyncRelayCommand(() => Task.CompletedTask);
            IAsyncCommand <string> commandT = new AsyncRelayCommand <string>(_ => Task.CompletedTask);

            Assert.True(command.CanExecute());
            Assert.True(commandT.CanExecute("F0"));
        }
Example #11
0
        public void CanExecuteReturnsTrueWithoutCanExecuteDelegate()
        {
            var handlers = new AsyncDelegateObjectHandlers();
            var command  = new AsyncRelayCommand <object>(async o => await handlers.Execute(o));

            var condition = command.CanExecute(null);

            Assert.True(condition);
        }
Example #12
0
        public void Test_WithParameter_CanExecute()
        {
            // Arrange.
            var command = new AsyncRelayCommand <bool>(DelayAndSet, b => b);

            // Act.
            bool actual = command.CanExecute(true);

            // Assert.
            Assert.True(actual);
        }
Example #13
0
        public void Test_WithoutParameter_CanExecute()
        {
            // Arrange.
            var command = new AsyncRelayCommand(DelayAndSet, () => false);

            // Act.
            bool actual = command.CanExecute(true);

            // Assert.
            Assert.False(actual);
        }
Example #14
0
        public void Test_WithParameter_CanExecute_WrongType()
        {
            // Arrange.
            var command = new AsyncRelayCommand <bool>(DelayAndSet, b => b);

            // Act.
            bool actual = command.CanExecute("parameter");

            // Assert.
            Assert.False(actual);
        }
Example #15
0
        public void Test_WithoutParameter_CanExecute_NoPredicate()
        {
            // Arrange.
            var command = new AsyncRelayCommand(DelayAndSet);

            // Act.
            bool actual = command.CanExecute(false);

            // Assert.
            Assert.True(actual);
        }
Example #16
0
        public void CanExecuteCallsPassedInCanExecuteDelegate()
        {
            var handlers  = new AsyncDelegateObjectHandlers();
            var command   = new AsyncRelayCommand <object>(async o => await handlers.Execute(o), handlers.CanExecute);
            var parameter = new object();

            handlers.CanExecuteReturnValue = true;
            var actual = command.CanExecute(parameter);

            Assert.AreSame(parameter, handlers.CanExecuteParameter);
            Assert.AreEqual(handlers.CanExecuteReturnValue, actual);
        }
        public void Test_AsyncRelayCommandOfT_WithCanExecuteFunctionFalse()
        {
            int ticks = 0;

            var command = new AsyncRelayCommand <string>(
                s =>
            {
                ticks = int.Parse(s);
                return(Task.CompletedTask);
            }, s => false);

            Assert.IsFalse(command.CanExecute(null));
            Assert.IsFalse(command.CanExecute("1"));

            command.Execute("2");

            Assert.AreEqual(ticks, 0);

            command.Execute("42");

            Assert.AreEqual(ticks, 0);
        }
        public async Task InContrastToTheNonGenericCommandWhichDoesNotSupportDataToBePassed_DataIsUsedByTheStronglyTypedCommand()
        {
            int number = 0;
            IAsyncCommand <int> commandT = new AsyncRelayCommand <int>(addend => { number += addend; return(Task.CompletedTask); }, integer => integer % 2 == 0);

            Assert.False(commandT.CanExecute(1));
            Assert.True(commandT.CanExecute(2));

            Assert.Equal(0, number);
            await commandT.ExecuteAsync(1);

            Assert.Equal(1, number);
            await commandT.ExecuteAsync(2);

            Assert.Equal(3, number);
            await commandT.ExecuteAsync(3);

            Assert.Equal(6, number);
            await commandT.ExecuteAsync(-9);

            Assert.Equal(-3, number);
        }
Example #19
0
        public void Test_AsyncRelayCommand_WithCanExecuteFunctionTrue()
        {
            int ticks = 0;

            var command = new AsyncRelayCommand(
                () =>
            {
                ticks++;
                return(Task.CompletedTask);
            }, () => true);

            Assert.IsTrue(command.CanExecute(null));
            Assert.IsTrue(command.CanExecute(new object()));

            command.Execute(null);

            Assert.AreEqual(ticks, 1);

            command.Execute(new object());

            Assert.AreEqual(ticks, 2);
        }
Example #20
0
        public void TestCanExecuteRunsDelegate()
        {
            int canExecuteRunCount      = 0;
            Func <int, bool> canExecute = (x) =>
            {
                canExecuteRunCount++;
                return(true);
            };

            var cmd = new AsyncRelayCommand <int>((x) => Task.CompletedTask, canExecute);

            cmd.CanExecute(5);

            Assert.AreEqual(1, canExecuteRunCount);
        }
Example #21
0
        public void TestExplicitCanExecute()
        {
            int         canExecuteRunCount = 0;
            Func <bool> canExecute         = () =>
            {
                canExecuteRunCount++;
                return(true);
            };

            ICommand cmd = new AsyncRelayCommand(() => Task.CompletedTask, canExecute);

            cmd.CanExecute(null);

            Assert.AreEqual(1, canExecuteRunCount);
        }
Example #22
0
        public void ShouldPassParameterInstanceOnCanExecute()
        {
            var      canExecuteCalled = false;
            var      testClass        = new MyClass();
            ICommand command          = new AsyncRelayCommand <MyClass>(
                async o => await Task.Yield(),
                delegate(MyClass parameter)
            {
                Assert.AreSame(testClass, parameter);
                canExecuteCalled = true;
                return(true);
            });

            command.CanExecute(testClass);
            Assert.True(canExecuteCalled);
        }
        public void NonGenericAsyncRelayCommandCanExecuteShouldInvokeCanExecuteFunc()
        {
            var invoked = false;
            var command = new AsyncRelayCommand(
                async() => await Task.Yield(),
                () =>
            {
                invoked = true;
                return(true);
            });

            var canExecute = command.CanExecute();

            Assert.True(invoked);
            Assert.True(canExecute);
        }
Example #24
0
        public void TestExplicitCanExecuteWrongType()
        {
            int canExecuteRunCount      = 0;
            Func <int, bool> canExecute = (x) =>
            {
                canExecuteRunCount++;
                return(true);
            };

            ICommand cmd = new AsyncRelayCommand <int>((x) => Task.CompletedTask, canExecute);

            // exact exception will depend on the conversion
            Assert.ThrowsException <InvalidCastException>(
                () => cmd.CanExecute(new IncompatibleType())
                );

            Assert.AreEqual(0, canExecuteRunCount);
        }
        public void Test_AsyncRelayCommandOfT_NullWithValueType()
        {
            int n = 0;

            var command = new AsyncRelayCommand <int>(i =>
            {
                n = i;
                return(Task.CompletedTask);
            });

            // Special case for null value types
            Assert.IsTrue(command.CanExecute(null));

            command = new AsyncRelayCommand <int>(
                i =>
            {
                n = i;
                return(Task.CompletedTask);
            }, i => i > 0);

            Assert.ThrowsException <NullReferenceException>(() => command.CanExecute(null));
        }
 public void CanExecute_ConditionIsFalse_FalseReturned()
 {
     var command = new AsyncRelayCommand(() => null, () => false);
     NUnit.Framework.Assert.IsFalse(command.CanExecute(null));
 }