コード例 #1
0
        public void WaitAndUnwrapExceptionWithCT_Faulted_UnwrapsException()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Task task = Task.Run(() => throw new NotImplementedException());

            AsyncAssert.Throws <NotImplementedException>(() => task.WaitAndUnwrapException(cts.Token));
        }
コード例 #2
0
 public void Throws_DelegateDoesNotThrow_Fails()
 {
     Assert.Throws <Exception>(() =>
     {
         AsyncAssert.Throws(() => { });
     });
 }
コード例 #3
0
        public void Release_Overflow_ThrowsException()
        {
            AsyncSemaphore semaphore = new AsyncSemaphore(long.MaxValue);

            Assert.Equal(long.MaxValue, semaphore.CurrentCount);
            AsyncAssert.Throws <OverflowException>(() => semaphore.Release());
        }
コード例 #4
0
        public void WaitAndUnwrapExceptionResultWithCT_Faulted_UnwrapsException()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Task <int> task             = Task.Run((Func <int>)(() => throw new NotImplementedException()));

            AsyncAssert.Throws <NotImplementedException>(() => task.WaitAndUnwrapException(cts.Token), allowDerivedTypes: false);
        }
コード例 #5
0
 public void Throws_DelegateThrowsBaseException_Fails()
 {
     Assert.Throws <Exception>(() =>
     {
         AsyncAssert.Throws <TaskCanceledException>(() => { throw new OperationCanceledException(); });
     });
 }
コード例 #6
0
 public void Throws_ExpectingSpecificException_DelegateThrowsDerivedException_Fails()
 {
     Assert.Throws <Exception>(() =>
     {
         AsyncAssert.Throws <OperationCanceledException>(() => { throw new TaskCanceledException(); }, false);
     });
 }
コード例 #7
0
        public void Throws_DelegateThrowsDerivedException_ReturnsException()
        {
            var expectedException = new TaskCanceledException();
            var result            = AsyncAssert.Throws <OperationCanceledException>(() => { throw expectedException; });

            Assert.Same(expectedException, result);
        }
コード例 #8
0
        public void Throws_DelegateThrowsExpectedException_ReturnsException()
        {
            var expectedException = new InvalidOperationException();
            var result            = AsyncAssert.Throws <InvalidOperationException>(() => { throw expectedException; });

            Assert.Same(expectedException, result);
        }
コード例 #9
0
 public void Throws_DelegateThrowsWrongException_Fails()
 {
     Assert.Throws <Exception>(() =>
     {
         AsyncAssert.Throws <NotImplementedException>(() => { throw new InvalidOperationException(); });
     });
 }
コード例 #10
0
        public void Release_Overflow_ThrowsException()
        {
            var semaphore = new AsyncSemaphore(int.MaxValue);

            Assert.Equal(int.MaxValue, semaphore.CurrentCount);
            AsyncAssert.Throws <InvalidOperationException>(() => semaphore.Release());
        }
コード例 #11
0
        public async Task HandleFinalHandshakeFailureCorrectly()
        {
            var initialHandshakeResponse = "96:0{ \"sid\":\"i4VXx68U4C_w6qiFAAAm\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":5000}2:40";
            var initialHandshakeClient   = new MockHttpClient(initialHandshakeResponse, HttpStatusCode.OK);

            var secondaryHandshakeResponse = "ok";
            var secondaryHandshakeClient   = new MockHttpClient(secondaryHandshakeResponse, HttpStatusCode.OK);

            var protocolUpgradeResponse = "";
            var protocolUpgradeClient   = new MockHttpClient(protocolUpgradeResponse, HttpStatusCode.SwitchingProtocols);

            protocolUpgradeClient.AddHeader("Sec-Websocket-Accept", "RWZIQcMHYHEyvemvvKIkivC1Tvo=");

            var finalHandshakeResponse = "1:6";
            var finalHandshakeClient   = new MockHttpClient(finalHandshakeResponse, HttpStatusCode.RequestTimeout);

            var factoryMock = new Mock <IHttpClientFactory>();

            factoryMock.SetupSequence(f => f.CreateHttpClient())
            .Returns(initialHandshakeClient)
            .Returns(secondaryHandshakeClient)
            .Returns(protocolUpgradeClient)
            .Returns(finalHandshakeClient);

            var socketFactoryMock = new Mock <IClientSocketFactory>();

            var mediator = new SocketMediator("ws://localhost:7200/collections");

            await AsyncAssert.Throws <HttpRequestException>(
                () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object));

            Mock.VerifyAll(factoryMock);
        }
コード例 #12
0
        public void WaitWithoutExceptionWithCancellationToken_CanceledToken_DoesNotBlockButThrowsException()
        {
            Task task = new TaskCompletionSource <object>().Task;
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Cancel();
            AsyncAssert.Throws <OperationCanceledException>(() => task.WaitWithoutException(cts.Token));
        }
コード例 #13
0
        public void WaitAndUnwrapExceptionResultWithCT_CancellationTokenCancelled_Cancels()
        {
            TaskCompletionSource <int> tcs = new TaskCompletionSource <int>();
            CancellationTokenSource    cts = new CancellationTokenSource();

            cts.Cancel();
            AsyncAssert.Throws <OperationCanceledException>(() => tcs.Task.WaitAndUnwrapException(cts.Token));
        }
コード例 #14
0
        public void WaitAndUnwrapExceptionWithCT_CancellationTokenCancelled_Cancels()
        {
            var  tcs  = new TaskCompletionSource <object>();
            Task task = tcs.Task;
            var  cts  = new CancellationTokenSource();

            cts.Cancel();
            AsyncAssert.Throws <OperationCanceledException>(() => task.WaitAndUnwrapException(cts.Token));
        }
コード例 #15
0
        public void SynchronizationContextPost_PropagatesException()
        {
            Action test = () => AsyncContext.Run(async() =>
            {
                SynchronizationContext.Current.Post(_ => throw new NotImplementedException(), null);
                await Task.Yield();
            });

            AsyncAssert.Throws <NotImplementedException>(test, allowDerivedTypes: false);
        }
コード例 #16
0
        public async Task GetDevicesInvalidState()
        {
            // arrange
            var output = new List <string>
            {
                "List of devices attached",
                "0123456789ABCDE\tinvalidstate"
            };
            var processManager = new TestProcessManager();

            processManager.AddProcess(output);
            var adb = new Adb(processManager);

            // act + assert
            await AsyncAssert.Throws <UnexpectedOutputException>(async() => (await adb.GetDevices()).ToList());
        }
コード例 #17
0
        public async Task Handles2ProbeSendFailureCorrectly()
        {
            // 1. Initial handshake
            var initialHandshakeResponse = "96:0{ \"sid\":\"i4VXx68U4C_w6qiFAAAm\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":5000}2:40";
            var initialHandshakeClient   = new MockHttpClient(initialHandshakeResponse, HttpStatusCode.OK);

            var secondaryHandshakeResponse = "ok";
            var secondaryHandshakeClient   = new MockHttpClient(secondaryHandshakeResponse, HttpStatusCode.OK);

            var protocolUpgradeResponse = "";
            var protocolUpgradeClient   = new MockHttpClient(protocolUpgradeResponse, HttpStatusCode.SwitchingProtocols);

            protocolUpgradeClient.AddHeader("Sec-Websocket-Accept", "RWZIQcMHYHEyvemvvKIkivC1Tvo=");

            var finalHandshakeResponse = "15:40/collections,";
            var finalHandshakeClient   = new MockHttpClient(finalHandshakeResponse, HttpStatusCode.OK);

            var factoryMock = new Mock <IHttpClientFactory>();

            factoryMock.SetupSequence(f => f.CreateHttpClient())
            .Returns(initialHandshakeClient)
            .Returns(secondaryHandshakeClient)
            .Returns(protocolUpgradeClient)
            .Returns(finalHandshakeClient);

            // 2. Connection upgrade and handshake
            var socketMock = new Mock <IClientSocket>();

            socketMock.Setup(s => s.ConnectAsync(It.IsAny <Uri>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            // The ws client handshake sends "2probe" and the server returns "3probe"
            socketMock.Setup(s => s.SendAsync(It.IsAny <ArraySegment <byte> >(),
                                              It.IsAny <WebSocketMessageType>(), It.IsAny <bool>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromException(new HttpRequestException()));

            var socketFactoryMock = new Mock <IClientSocketFactory>();

            socketFactoryMock.Setup(f => f.CreateSocketClient()).Returns(socketMock.Object);


            var mediator = new SocketMediator("ws://localhost:7200/collections");
            await AsyncAssert.Throws <HttpRequestException>(
                () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object));

            Mock.VerifyAll(socketMock, socketFactoryMock, factoryMock);
        }
コード例 #18
0
        public async Task HandleFirstHandshakeFailureCorrectly()
        {
            var initialHandshakeClient = new MockHttpClient("", HttpStatusCode.RequestTimeout);

            var factoryMock = new Mock <IHttpClientFactory>();

            factoryMock.Setup(f => f.CreateHttpClient())
            .Returns(initialHandshakeClient);

            var socketFactoryMock = new Mock <IClientSocketFactory>();

            var mediator = new SocketMediator("ws://localhost:7200/collections");

            await AsyncAssert.Throws <HttpRequestException>(
                () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object));

            Mock.VerifyAll(factoryMock);
        }
コード例 #19
0
        public async Task HandleSecondHandshakeFailureCorrectly()
        {
            var initialHandshakeResponse = "96:0{ \"sid\":\"i4VXx68U4C_w6qiFAAAm\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":5000}2:40";
            var initialHandshakeClient   = new MockHttpClient(initialHandshakeResponse, HttpStatusCode.OK);

            var secondaryHandshakeClient = new MockHttpClient("", HttpStatusCode.RequestTimeout);

            var factoryMock = new Mock <IHttpClientFactory>();

            factoryMock.SetupSequence(f => f.CreateHttpClient())
            .Returns(initialHandshakeClient)
            .Returns(secondaryHandshakeClient);

            var socketFactoryMock = new Mock <IClientSocketFactory>();

            var mediator = new SocketMediator("ws://localhost:7200/collections");

            await AsyncAssert.Throws <HttpRequestException>(
                () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object));

            Mock.VerifyAll(factoryMock);
        }
コード例 #20
0
        public async Task Handles2ProbeFailureCorrectly()
        {
            // 1. Initial handshake
            var initialHandshakeResponse = "96:0{ \"sid\":\"i4VXx68U4C_w6qiFAAAm\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":5000}2:40";
            var initialHandshakeClient   = new MockHttpClient(initialHandshakeResponse, HttpStatusCode.OK);

            var secondaryHandshakeResponse = "ok";
            var secondaryHandshakeClient   = new MockHttpClient(secondaryHandshakeResponse, HttpStatusCode.OK);

            var protocolUpgradeResponse = "";
            var protocolUpgradeClient   = new MockHttpClient(protocolUpgradeResponse, HttpStatusCode.SwitchingProtocols);

            protocolUpgradeClient.AddHeader("Sec-Websocket-Accept", "RWZIQcMHYHEyvemvvKIkivC1Tvo=");

            var finalHandshakeResponse = "15:40/collections,";
            var finalHandshakeClient   = new MockHttpClient(finalHandshakeResponse, HttpStatusCode.OK);

            var factoryMock = new Mock <IHttpClientFactory>();

            factoryMock.SetupSequence(f => f.CreateHttpClient())
            .Returns(initialHandshakeClient)
            .Returns(secondaryHandshakeClient)
            .Returns(protocolUpgradeClient)
            .Returns(finalHandshakeClient);

            // 2. Connection upgrade and handshake
            var socketMock = new Mock <IClientSocket>();

            socketMock.Setup(s => s.ConnectAsync(It.IsAny <Uri>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            // The ws client handshake sends "2probe" and the server returns "3probe"
            socketMock.Setup(s => s.SendAsync(It.IsAny <ArraySegment <byte> >(),
                                              It.IsAny <WebSocketMessageType>(), It.IsAny <bool>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            // "3probe" response
            var         initialProbeResponse = Encoding.UTF8.GetBytes("HahaKeed");
            List <byte> initialProbeBytes    = new List <byte>(initialProbeResponse);
            var         originalBytes        = initialProbeBytes.Count;

            var dataProvider = new MockSocketDataProvider(initialProbeBytes);

            socketMock.Setup(s => s.ReceiveAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <CancellationToken>()))
            .Returns((ArraySegment <byte> buffer, CancellationToken token) =>
            {
                var writeResult = dataProvider.GetDataChunk(buffer.Array.Length);
                writeResult.buffer.CopyTo(buffer.Array, 0);

                return(MockSocketTaskFactory.CreateTask(initialProbeBytes.Count, writeResult.bytesWritten));
            });

            var socketFactoryMock = new Mock <IClientSocketFactory>();

            socketFactoryMock.Setup(f => f.CreateSocketClient()).Returns(socketMock.Object);


            var mediator = new SocketMediator("ws://localhost:7200/collections");
            await AsyncAssert.Throws <HttpRequestException>(
                () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object));

            Mock.VerifyAll(socketMock, socketFactoryMock, factoryMock);
        }
コード例 #21
0
        public void AddCount_Overflow_ThrowsException()
        {
            var ce = new AsyncCountdownEvent(long.MaxValue);

            AsyncAssert.Throws <OverflowException>(() => ce.AddCount());
        }
コード例 #22
0
 public void ConstructorWithMaxCountSmallerThanCollectionCount_Throws()
 {
     AsyncAssert.Throws <ArgumentException>(() => new AsyncProducerConsumerQueue <int>(new[] { 3, 5 }, 1));
 }
コード例 #23
0
 public void ConstructorWithZeroMaxCountAndCollection_Throws()
 {
     AsyncAssert.Throws <ArgumentOutOfRangeException>(() => new AsyncProducerConsumerQueue <int>(new int[0], 0));
 }
コード例 #24
0
        public void Signal_Underflow_ThrowsException()
        {
            var ce = new AsyncCountdownEvent(long.MinValue);

            AsyncAssert.Throws <OverflowException>(() => ce.Signal());
        }
コード例 #25
0
        public void WaitAndUnwrapExceptionResult_Faulted_UnwrapsException()
        {
            Task <int> task = Task.Run((Func <int>)(() => throw new NotImplementedException()));

            AsyncAssert.Throws <NotImplementedException>(() => task.WaitAndUnwrapException(), allowDerivedTypes: false);
        }
コード例 #26
0
        public void Run_PropagatesException()
        {
            Action test = () => AsyncContext.Run(() => throw new NotImplementedException());

            AsyncAssert.Throws <NotImplementedException>(test, allowDerivedTypes: false);
        }
コード例 #27
0
        public void WaitAndUnwrapException_Faulted_UnwrapsException()
        {
            Task task = Task.Run(() => throw new NotImplementedException());

            AsyncAssert.Throws <NotImplementedException>(() => task.WaitAndUnwrapException());
        }
コード例 #28
0
        public void Run_Async_PropagatesException()
        {
            Action test = () => AsyncContext.Run(async() => { await Task.Yield(); throw new NotImplementedException(); });

            AsyncAssert.Throws <NotImplementedException>(test, allowDerivedTypes: false);
        }