Exemplo n.º 1
0
        public void MethodShouldTimeout_WhenTimeoutsAreNotIgnored()
        {
            var classToProxy = new CancellableWithOverrunnningMethod();
            var proxy        = CommandInterceptor.CreateProxy <ICancellableTimeoutPreserved>(classToProxy);

            Assert.Throws <CommandTimeoutException>(() => proxy.CancellableMethod(CancellationToken.None));
        }
        public void CreateProxy_NonInterface_ThrowsInvalidOperationException()
        {
            var ex = Assert.Throws <InvalidOperationException>(() => {
                CommandInterceptor.CreateProxy(typeof(TestImplementation));
            });

            Assert.Equal("Proxies may only be created for interfaces", ex.Message);
        }
        public void MethodShouldNotTimeout_WhenTimeoutsAreIgnored()
        {
            ConfigProvider.Instance.Set(IgnoreTimeoutsKey, true);
            var classToProxy = new CancellableWithOverrunnningMethodTimeoutsIgnored();
            var proxy        = CommandInterceptor.CreateProxy <ICancellableIgnoredTimeout>(classToProxy);

            Assert.DoesNotThrow(() => proxy.CancellableMethod(CancellationToken.None));
            ConfigProvider.Instance.Set(IgnoreTimeoutsKey, false);
        }
        public void InterceptorCreateCommand_CommandName_IsInterfaceNameAndMethodName()
        {
            var method         = typeof(ITestInterfaceWithImplementation).GetMethod("InvokeString");
            var mockInvocation = new Mock <IInvocation>();

            mockInvocation.SetupGet(m => m.Method).Returns(method);

            var command = new CommandInterceptor().CreateCommand <string>(mockInvocation.Object);

            Assert.Equal("foo.ITestInterfaceWithImplementation-InvokeString", command.Name);
        }
        public void WithNonNullableCancellationTokenParameter_CancellationTokenIsEmpty_UsesTokenFromExecuteAsync()
        {
            const string expected = "quux";
            var          instance = new Cancellable(expected);
            var          proxy    = CommandInterceptor.CreateProxy <ICancellable>(instance);

            proxy.CancellationTokenOnly(CancellationToken.None);

            Assert.NotNull(instance.ReceivedToken);
            Assert.False(instance.ReceivedToken.Value.IsCancellationRequested);
            Thread.Sleep(Cancellable.CancellationTestTimeoutMillis + 50);
            Assert.True(instance.ReceivedToken.Value.IsCancellationRequested);
        }
Exemplo n.º 6
0
        public void ProxyPassesOnTokenToMethod_WhenTimeoutsNotIgnored()
        {
            var expectedResult = "test";
            var classToProxy   = new CancellableWithTimeoutPreserved(expectedResult);
            var proxy          = CommandInterceptor.CreateProxy <ICancellableTimeoutPreserved>(classToProxy);
            // If we pass a valid token to the proxy then it should pass the token to the method call.
            var token  = new CancellationTokenSource(500).Token;
            var result = proxy.CancellableMethod(token);

            Assert.True(classToProxy.CallMade);
            Assert.Equal(classToProxy.TokenRecievedFromProxy, token);
            Assert.Equal(expectedResult, result);
        }
        public void SlowSleepMethod_WithoutFireAndForget_BlocksUntilCompletion()
        {
            var instance = new Sleepy();
            var proxy    = CommandInterceptor.CreateProxy <ISleepy>(instance);

            var stopwatch = Stopwatch.StartNew();

            proxy.SleepWithoutFireAndForget(500);
            stopwatch.Stop();

            Assert.True(stopwatch.Elapsed.TotalMilliseconds > 500);
            Assert.True(instance.IsCompleted);
        }
        public void FireAndForget_WhenThrows_DoesntThrowExceptionToCaller()
        {
            // The default TaskScheduler doesn't guarantee execution on another thread,
            // so we might get the exception back here. We catch and log in the interceptor
            // to avoid that.

            var instance = new ThrowingFireAndForget();
            var proxy    = CommandInterceptor.CreateProxy <IThrowingFireAndForget>(instance);

            proxy.ImmediatelyThrowWithFireAndForget();

            Assert.True(true); // Expecting no exception to be thrown.
        }
        public void WithNonNullableCancellationTokenParameter_NonEmptyCancellationToken_DoesntReplace()
        {
            const string expected = "quux";
            var          instance = new Cancellable(expected);
            var          proxy    = CommandInterceptor.CreateProxy <ICancellable>(instance);

            var source = new CancellationTokenSource(TimeSpan.FromMilliseconds(10000)); // Not 500, which is the value in the [Command] attribute.
            var token  = source.Token;

            var result = proxy.CancellationTokenOnly(token);

            Assert.Equal(token, instance.ReceivedToken);
            Assert.Equal(expected, result);
        }
        public void ProxyStillPassesOnTokenToMethod_WhenTimeoutsAreIgnored()
        {
            ConfigProvider.Instance.Set(IgnoreTimeoutsKey, true);
            var expectedResult = "test";
            var classToProxy   = new CancellableWithIgnoredTimeout(expectedResult);
            var proxy          = CommandInterceptor.CreateProxy <ICancellableIgnoredTimeout>(classToProxy);
            // If we pass CancellationToken.None to the proxy then it should pass a timeout tokem to the method call.
            var token  = new CancellationTokenSource(500).Token;
            var result = proxy.CancellableMethod(token);

            Assert.True(classToProxy.CallMade);
            Assert.Equal(classToProxy.TokenRecievedFromProxy, token);
            Assert.Equal(expectedResult, result);
            ConfigProvider.Instance.Set(IgnoreTimeoutsKey, false);
        }
        public void ProxyPassesNoneToMethod_WhenTimeoutsIgnored()
        {
            ConfigProvider.Instance.Set(IgnoreTimeoutsKey, true);
            var expectedResult = "test";
            var classToProxy   = new CancellableWithIgnoredTimeout(expectedResult);
            var proxy          = CommandInterceptor.CreateProxy <ICancellableIgnoredTimeout>(classToProxy);
            // If we pass CancellationToken.None to the proxy then it should pass this along to the method call, rather than a CancellationToken with a timeout. This should
            // be the case because we've set the Command to ignore timeouts
            var result = proxy.CancellableMethod(CancellationToken.None);

            Assert.True(classToProxy.CallMade);
            Assert.Equal(classToProxy.TokenRecievedFromProxy, CancellationToken.None);
            Assert.Equal(expectedResult, result);
            ConfigProvider.Instance.Set(IgnoreTimeoutsKey, false);
        }
Exemplo n.º 12
0
        public void ProxyPassesATimeoutTokenToMethod_WhenTimeoutsNotIgnored()
        {
            var expectedResult = "test";
            var classToProxy   = new CancellableWithTimeoutPreserved(expectedResult);
            var proxy          = CommandInterceptor.CreateProxy <ICancellableTimeoutPreserved>(classToProxy);
            // If we pass CancellationToken.None to the proxy then it should pass a timeout tokem to the method call.
            var result = proxy.CancellableMethod(CancellationToken.None);

            Assert.True(classToProxy.CallMade && classToProxy.TokenRecievedFromProxy != CancellationToken.None);
            // This shouldn't be cancelled yet.
            Assert.False(classToProxy.TokenRecievedFromProxy.IsCancellationRequested);
            // Now sleep past the timeout.
            Thread.Sleep(CancellableWithTimeoutPreserved.Timeout + 50);
            Assert.True(classToProxy.TokenRecievedFromProxy.IsCancellationRequested);
            Assert.Equal(expectedResult, result);
        }
        public void SlowSleepMethod_FireAndForget_ReturnsImmediatelyButStillCompletes()
        {
            var instance = new Sleepy();
            var proxy    = CommandInterceptor.CreateProxy <ISleepy>(instance);

            var stopwatch = Stopwatch.StartNew();

            proxy.SleepWithFireAndForget(500);
            stopwatch.Stop();

            // Should have returned immediately; for sure before the sleep time.
            Assert.True(stopwatch.Elapsed.TotalMilliseconds < 400);
            Assert.False(instance.IsCompleted);

            Thread.Sleep(510);
            Assert.True(instance.IsCompleted);
        }
Exemplo n.º 14
0
        private async Task <ChartSet> IdealCommandAttribute(string key)
        {
            _testConfigProvider.Set("mjolnir.breaker." + key + ".minimumOperations", 5);
            _testConfigProvider.Set("mjolnir.breaker." + key + ".thresholdPercentage", 50);
            _testConfigProvider.Set("mjolnir.breaker." + key + ".trippedDurationMillis", 5000);
            _testConfigProvider.Set("mjolnir.metrics." + key + ".windowMillis", 10000);

            // Command timeout is defined on the interface.
            var instance = new HttpClientService();
            var proxy    = CommandInterceptor.CreateProxy <IHttpClientService>(instance);

            using (var server = new HttpServer(1))
            {
                var url = string.Format("http://*****:*****@"c:\hudl\logs\mjolnir-metrics-{0}-{1}.txt", key, DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")), _testStats.Metrics.Select(m => m.ToCsvLine()));

            return(new ChartSet
            {
                Name = "Ideal (Command Attribute)",
                Description = "30s @ 5/sec.<br/>Command: Inherited<br/>Timeout: 10000<br/>Server: Immediate 200<br/>Breaker: 50% / 10sec, min 5 ops, 5s tripped",
                Charts = GatherChartData(_testStats.Metrics, key, key + ".IHttpClientService-MakeRequest"),
            });
        }
Exemplo n.º 15
0
        public void RaiseCanExecuteChangedShouldRaiseEvent()
        {
            // arrange
            var command = new Mock<INotifyCommandChanged>();

            command.Setup( c => c.RaiseCanExecuteChanged() );

            var interceptor = new CommandInterceptor<object>( DefaultAction.None, DefaultAction.None, command.Object );

            // act
            interceptor.RaiseCanExecuteChanged();

            // assert
            command.Verify( c => c.RaiseCanExecuteChanged(), Times.Once() );
        }
Exemplo n.º 16
0
        public void InterceptorCreateCommand_CommandName_IsInterfaceNameAndMethodName()
        {
            var method = typeof (ITestInterfaceWithImplementation).GetMethod("InvokeString");
            var mockInvocation = new Mock<IInvocation>();
            mockInvocation.SetupGet(m => m.Method).Returns(method);

            var command = new CommandInterceptor().CreateCommand<string>(mockInvocation.Object);

            Assert.Equal("foo.ITestInterfaceWithImplementation-InvokeString", command.Name);
        }
Exemplo n.º 17
0
        public void CanExecuteShouldInvokeCommand()
        {
            // arrange
            var command = new Mock<ICommand>();

            command.Setup( c => c.CanExecute( It.IsAny<object>() ) ).Returns( true );

            var interceptor = new CommandInterceptor<object>( DefaultAction.None, DefaultAction.None, command.Object );

            // act
            Assert.True( interceptor.CanExecute() );

            // assert
            command.Verify( c => c.CanExecute( null ), Times.Once() );
        }
        // TODO How do we test for an unhandled exception thrown by a FireAndForget on a different thread?

        private ITestInterfaceWithImplementation CreateForImplementation(ITestInterfaceWithImplementation instance)
        {
            return(CommandInterceptor.CreateProxy(instance));
        }
Exemplo n.º 19
0
        public void ExecuteShouldInvokeCommand()
        {
            // arrange
            var pre = new Mock<Action<object>>();
            var post = new Mock<Action<object>>();

            pre.Setup( f => f( It.IsAny<object>() ) );
            post.Setup( f => f( It.IsAny<object>() ) );

            var command = new Mock<INotifyCommandChanged>();

            command.Setup( c => c.Execute( It.IsAny<object>() ) ).Raises( c => c.Executed += null, EventArgs.Empty );

            var interceptor = new CommandInterceptor<object>( pre.Object, post.Object, command.Object );
            var raised = false;

            interceptor.Executed += ( s, e ) => raised = true;

            // act
            interceptor.Execute();

            // assert
            pre.Verify( f => f( null ), Times.Once() );
            command.Verify( c => c.Execute( null ), Times.Once() );
            post.Verify( f => f( null ), Times.Once() );
            Assert.True( raised );
        }