System.Threading.Tasks.Task.FromException(System.Exception)

Here are the examples of the csharp api System.Threading.Tasks.Task.FromException(System.Exception) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

524 Examples 7

19 View Source File : CallCredentialTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task CallCredentialsWithHttps_WhenAsyncAuthInterceptorThrow_ShouldThrow()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddNUnitLogger();
            var loggerFactory = services.BuildServiceProvider().GetRequiredService<ILoggerFactory>();

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var reply = new HelloReply { Message = "Hello world" };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();
                return ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent);
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient, loggerFactory);

            // Act
            var expectedException = new Exception("Some AsyncAuthInterceptor Exception");

            var callCredentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                return Task.FromException(expectedException);
            });

            var call = invoker.AsyncUnaryCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(credentials: callCredentials), new HelloRequest());
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            // replacedert
            replacedert.AreSame(expectedException, ex.Status.DebugException);
        }

19 View Source File : ConnectionTests.cs
License : Apache License 2.0
Project Creator : grpc

[TestCase(SocketError.HostNotFound, StatusCode.Unavailable)]
        [TestCase(SocketError.ConnectionRefused, StatusCode.Unavailable)]
        public async Task UnaryCall_SocketException_ThrowCorrectStatus(SocketError socketError, StatusCode statusCode)
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new HttpRequestException("Blah", new SocketException((int)socketError)));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncUnaryCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: invoker.Channel.Clock.UtcNow.AddSeconds(1)), new HelloRequest());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            replacedert.AreEqual(statusCode, ex.StatusCode);
        }

19 View Source File : DeadlineTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task AsyncUnaryCall_ServerResetsCancelCodeBeforeDeadline_CancelStatus()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddNUnitLogger();
            var serviceProvider = services.BuildServiceProvider();

            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new Http2StreamException("The HTTP/2 server reset the stream. HTTP/2 error code 'CANCEL' (0x8)."));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker = HttpClientCallInvokerFactory.Create(
                httpClient,
                systemClock: testSystemClock,
                loggerFactory: serviceProvider.GetRequiredService<ILoggerFactory>());

            // Act
            var responseTask = invoker.AsyncUnaryCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: invoker.Channel.Clock.UtcNow.AddSeconds(1)), new HelloRequest()).ResponseAsync;

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => responseTask).DefaultTimeout();
            replacedert.AreEqual(StatusCode.Cancelled, ex.StatusCode);
        }

19 View Source File : HedgingTests.cs
License : Apache License 2.0
Project Creator : grpc

[TestCase(null)]
        [TestCase(0)]
        [TestCase(20)]
        public async Task Unary_ExceedAttempts_Failure(int? hedgingDelay)
        {
            Task<DataMessage> UnaryFailure(DataMessage request, ServerCallContext context)
            {
                return Task.FromException<DataMessage>(new RpcException(new Status(StatusCode.Unavailable, "")));
            }

            // Ignore errors
            SetExpectedErrorsFilter(writeContext =>
            {
                return true;
            });

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<DataMessage, DataMessage>(UnaryFailure);

            var delay = (hedgingDelay == null)
                ? (TimeSpan?)null
                : TimeSpan.FromMilliseconds(hedgingDelay.Value);
            var channel = CreateChannel(serviceConfig: ServiceConfigHelpers.CreateHedgingServiceConfig(maxAttempts: 5, hedgingDelay: delay));

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();
            replacedert.AreEqual(StatusCode.Unavailable, ex.StatusCode);
            replacedert.AreEqual(StatusCode.Unavailable, call.GetStatus().StatusCode);

            replacedertHasLog(LogLevel.Debug, "CallCommited", "Call commited. Reason: ExceededAttemptCount");
        }

19 View Source File : HedgingTests.cs
License : Apache License 2.0
Project Creator : grpc

[TestCase(1)]
        [TestCase(2)]
        public async Task Unary_DeadlineExceedAfterServerCall_Failure(int exceptedServerCallCount)
        {
            var callCount = 0;
            var tcs = new TaskCompletionSource<DataMessage>(TaskCreationOptions.RunContinuationsAsynchronously);
            Task<DataMessage> UnaryFailure(DataMessage request, ServerCallContext context)
            {
                callCount++;

                if (callCount < exceptedServerCallCount)
                {
                    return Task.FromException<DataMessage>(new RpcException(new Status(StatusCode.DeadlineExceeded, "")));
                }

                return tcs.Task;
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<DataMessage, DataMessage>(UnaryFailure);

            var serviceConfig = ServiceConfigHelpers.CreateHedgingServiceConfig(nonFatalStatusCodes: new List<StatusCode> { StatusCode.DeadlineExceeded });
            var channel = CreateChannel(serviceConfig: serviceConfig);

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage(), new CallOptions(deadline: DateTime.UtcNow.AddMilliseconds(200)));

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();
            replacedert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);
            replacedert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);

            replacedert.IsFalse(Logs.Any(l => l.EventId.Name == "DeadlineTimerRescheduled"));
        }

19 View Source File : HedgingTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task Unary_TriggerRetryThrottling_Failure()
        {
            var callCount = 0;
            Task<DataMessage> UnaryFailure(DataMessage request, ServerCallContext context)
            {
                callCount++;
                return Task.FromException<DataMessage>(new RpcException(new Status(StatusCode.Unavailable, "")));
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<DataMessage, DataMessage>(UnaryFailure);

            var channel = CreateChannel(serviceConfig: ServiceConfigHelpers.CreateHedgingServiceConfig(
                hedgingDelay: TimeSpan.FromSeconds(10),
                retryThrottling: new RetryThrottlingPolicy
                {
                    MaxTokens = 5,
                    TokenRatio = 0.1
                }));

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();
            replacedert.AreEqual(StatusCode.Unavailable, ex.StatusCode);
            replacedert.AreEqual(StatusCode.Unavailable, call.GetStatus().StatusCode);

            replacedert.AreEqual(3, callCount);
            replacedertHasLog(LogLevel.Debug, "CallCommited", "Call commited. Reason: Throttled");
        }

19 View Source File : HedgingTests.cs
License : Apache License 2.0
Project Creator : grpc

[TestCase(0)]
        [TestCase(20)]
        public async Task Unary_AttemptsGreaterThanDefaultClientLimit_LimitedAttemptsMade(int hedgingDelay)
        {
            var callCount = 0;
            Task<DataMessage> UnaryFailure(DataMessage request, ServerCallContext context)
            {
                Interlocked.Increment(ref callCount);
                return Task.FromException<DataMessage>(new RpcException(new Status(StatusCode.Unavailable, "")));
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<DataMessage, DataMessage>(UnaryFailure);

            var channel = CreateChannel(serviceConfig: ServiceConfigHelpers.CreateHedgingServiceConfig(maxAttempts: 10, hedgingDelay: TimeSpan.FromMilliseconds(hedgingDelay)));

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();
            replacedert.AreEqual(StatusCode.Unavailable, ex.StatusCode);
            replacedert.AreEqual(StatusCode.Unavailable, call.GetStatus().StatusCode);

            replacedert.AreEqual(5, callCount);

            replacedertHasLog(LogLevel.Debug, "MaxAttemptsLimited", "The method has 10 attempts specified in the service config. The number of attempts has been limited by channel configuration to 5.");
            replacedertHasLog(LogLevel.Debug, "CallCommited", "Call commited. Reason: ExceededAttemptCount");
        }

19 View Source File : ResponseAsyncTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task AsyncUnaryCall_ErrorSendingRequest_ThrowsError()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new Exception("An error!"));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncUnaryCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest());
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            // replacedert
            replacedert.AreEqual(StatusCode.Internal, ex.StatusCode);
            replacedert.AreEqual("Error starting gRPC call. Exception: An error!", ex.Status.Detail);
            replacedert.AreEqual("An error!", ex.Status.DebugException.Message);
            replacedert.AreEqual(StatusCode.Internal, call.GetStatus().StatusCode);
        }

19 View Source File : RetryTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task Unary_ExceedRetryAttempts_Failure()
        {
            Task<DataMessage> UnaryFailure(DataMessage request, ServerCallContext context)
            {
                var metadata = new Metadata();
                metadata.Add("grpc-retry-pushback-ms", "5");

                return Task.FromException<DataMessage>(new RpcException(new Status(StatusCode.Unavailable, ""), metadata));
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<DataMessage, DataMessage>(UnaryFailure);

            var channel = CreateChannel(serviceConfig: ServiceConfigHelpers.CreateRetryServiceConfig());

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();
            replacedert.AreEqual(StatusCode.Unavailable, ex.StatusCode);
            replacedert.AreEqual(StatusCode.Unavailable, call.GetStatus().StatusCode);

            replacedertHasLog(LogLevel.Debug, "RetryPushbackReceived", "Retry pushback of '5' received from the failed gRPC call.");
            replacedertHasLog(LogLevel.Debug, "RetryEvaluated", "Evaluated retry for failed gRPC call. Status code: 'Unavailable', Attempt: 1, Retry: True");
            replacedertHasLog(LogLevel.Trace, "StartingRetryDelay", "Starting retry delay of 00:00:00.0050000.");
            replacedertHasLog(LogLevel.Debug, "RetryEvaluated", "Evaluated retry for failed gRPC call. Status code: 'Unavailable', Attempt: 5, Retry: False");
            replacedertHasLog(LogLevel.Debug, "CallCommited", "Call commited. Reason: ExceededAttemptCount");
        }

19 View Source File : RetryTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task Unary_DeadlineExceedDuringBackoff_Failure()
        {
            var callCount = 0;
            Task<DataMessage> UnaryFailureWithPushback(DataMessage request, ServerCallContext context)
            {
                callCount++;

                Logger.LogInformation($"Server sending pushback for call {callCount}.");
                return Task.FromException<DataMessage>(new RpcException(new Status(StatusCode.Unavailable, ""), new Metadata
                {
                    new Metadata.Entry("grpc-retry-pushback-ms", TimeSpan.FromSeconds(10).TotalMilliseconds.ToString())
                }));
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<DataMessage, DataMessage>(UnaryFailureWithPushback, nameof(UnaryFailureWithPushback));

            var serviceConfig = ServiceConfigHelpers.CreateRetryServiceConfig(
                initialBackoff: TimeSpan.FromSeconds(10),
                maxBackoff: TimeSpan.FromSeconds(10),
                retryableStatusCodes: new List<StatusCode> { StatusCode.Unavailable });
            var channel = CreateChannel(serviceConfig: serviceConfig);

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage(), new CallOptions(deadline: DateTime.UtcNow.AddMilliseconds(500)));

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();
            replacedert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);
            replacedert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);
            replacedert.AreEqual(1, callCount);

            replacedert.IsFalse(Logs.Any(l => l.EventId.Name == "DeadlineTimerRescheduled"));
        }

19 View Source File : RetryTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task Duplex_DeadlineExceedDuringBackoff_Failure()
        {
            var callCount = 0;
            Task DuplexDeadlineExceeded(IAsyncStreamReader<DataMessage> requestStream, IServerStreamWriter<DataMessage> responseStream, ServerCallContext context)
            {
                callCount++;

                return Task.FromException(new RpcException(new Status(StatusCode.Unavailable, ""), new Metadata
                {
                    new Metadata.Entry("grpc-retry-pushback-ms", TimeSpan.FromSeconds(10).TotalMilliseconds.ToString())
                }));
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddDuplexStreamingMethod<DataMessage, DataMessage>(DuplexDeadlineExceeded);

            var serviceConfig = ServiceConfigHelpers.CreateRetryServiceConfig(
                initialBackoff: TimeSpan.FromSeconds(10),
                maxBackoff: TimeSpan.FromSeconds(10),
                retryableStatusCodes: new List<StatusCode> { StatusCode.Unavailable });
            var channel = CreateChannel(serviceConfig: serviceConfig);

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.DuplexStreamingCall(new CallOptions(deadline: DateTime.UtcNow.AddMilliseconds(300)));

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseStream.MoveNext(CancellationToken.None)).DefaultTimeout();
            replacedert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);

            ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.RequestStream.WriteAsync(new DataMessage())).DefaultTimeout();
            replacedert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);

            replacedert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);
            replacedert.AreEqual(1, callCount);

            replacedert.IsFalse(Logs.Any(l => l.EventId.Name == "DeadlineTimerRescheduled"));
        }

19 View Source File : RetryTests.cs
License : Apache License 2.0
Project Creator : grpc

[TestCase(1)]
        [TestCase(20)]
        public async Task Unary_AttemptsGreaterThanDefaultClientLimit_LimitedAttemptsMade(int hedgingDelay)
        {
            var callCount = 0;
            Task<DataMessage> UnaryFailure(DataMessage request, ServerCallContext context)
            {
                Interlocked.Increment(ref callCount);
                return Task.FromException<DataMessage>(new RpcException(new Status(StatusCode.Unavailable, "")));
            }

            using var httpEventListener = new HttpEventSourceListener(LoggerFactory);

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<DataMessage, DataMessage>(UnaryFailure);

            var channel = CreateChannel(serviceConfig: ServiceConfigHelpers.CreateRetryServiceConfig(maxAttempts: 10, initialBackoff: TimeSpan.FromMilliseconds(hedgingDelay)));

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new DataMessage());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();
            replacedert.AreEqual(StatusCode.Unavailable, ex.StatusCode);
            replacedert.AreEqual(StatusCode.Unavailable, call.GetStatus().StatusCode);

            replacedert.AreEqual(5, callCount);

            replacedertHasLog(LogLevel.Debug, "MaxAttemptsLimited", "The method has 10 attempts specified in the service config. The number of attempts has been limited by channel configuration to 5.");
            replacedertHasLog(LogLevel.Debug, "CallCommited", "Call commited. Reason: ExceededAttemptCount");
        }

19 View Source File : TrailerMetadataTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task GetTrailers_UnaryMethodThrowsExceptionWithTrailers_TrailersAvailableInClient()
        {
            Task<HelloReply> UnaryDeadlineExceeded(HelloRequest request, ServerCallContext context)
            {
                var trailers = new Metadata();
                trailers.Add(new Metadata.Entry("Name", "the value was empty"));
                trailers.Add(new Metadata.Entry("grpc-status-details-bin", Encoding.UTF8.GetBytes("Hello world")));
                return Task.FromException<HelloReply>(new RpcException(new Status(StatusCode.InvalidArgument, "Validation failed"), trailers));
            }

            // Arrange
            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.EventId.Name == "ErrorReadingMessage" &&
                    writeContext.Message == "Error reading message.")
                {
                    return true;
                }

                return false;
            });

            var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>(UnaryDeadlineExceeded);

            var channel = CreateChannel();

            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new HelloRequest());

            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            // replacedert
            var trailers = call.GetTrailers();
            replacedert.GreaterOrEqual(trailers.Count, 2);
            replacedert.AreEqual("the value was empty", trailers.GetValue("name"));
            replacedert.AreEqual("Hello world", Encoding.UTF8.GetString(trailers.GetValueBytes("grpc-status-details-bin")));

            replacedert.AreEqual(StatusCode.InvalidArgument, ex.StatusCode);
            replacedert.AreEqual("Validation failed", ex.Status.Detail);
            replacedert.GreaterOrEqual(ex.Trailers.Count, 2);
            replacedert.AreEqual("the value was empty", ex.Trailers.GetValue("name"));
            replacedert.AreEqual("Hello world", Encoding.UTF8.GetString(ex.Trailers.GetValueBytes("grpc-status-details-bin")));

            replacedertHasLogRpcConnectionError(StatusCode.InvalidArgument, "Validation failed");
        }

19 View Source File : UnaryTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task ThrowErrorWithOK_ClientThrowsFailedToDeserializeError()
        {
            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.State.ToString() == "Message not returned from unary or client streaming call.")
                {
                    return true;
                }

                return false;
            });

            Task<HelloReply> UnaryThrowError(HelloRequest request, ServerCallContext context)
            {
                return Task.FromException<HelloReply>(new RpcException(new Status(StatusCode.OK, "Message")));
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>(UnaryThrowError);
            var channel = CreateChannel();
            var client = TestClientFactory.Create(channel, method);

            // Act
            var call = client.UnaryCall(new HelloRequest());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            replacedert.AreEqual(StatusCode.Internal, ex.Status.StatusCode);
            replacedert.AreEqual("Failed to deserialize response message.", ex.Status.Detail);

            replacedert.AreEqual(StatusCode.Internal, call.GetStatus().StatusCode);
            replacedert.AreEqual("Failed to deserialize response message.", call.GetStatus().Detail);
        }

19 View Source File : WebsiteProcess.cs
License : Apache License 2.0
Project Creator : grpc

public Task WaitForReadyAsync()
        {
            if (Process.HasExited)
            {
                return Task.FromException(new InvalidOperationException("Server is not running."));
            }

            return _startTcs.Task;
        }

19 View Source File : UnaryMethodTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task ServerMethodThrowsNonRpcException_FailureResponse()
        {
            // Arrange
            SetExpectedErrorsFilter(writeContext =>
            {
                return writeContext.LoggerName == TestConstants.ServerCallHandlerTestName &&
                       writeContext.EventId.Name == "ErrorExecutingServiceMethod" &&
                       writeContext.State.ToString() == "Error when executing service method 'GrpcErrorMethod'." &&
                       writeContext.Exception!.Message == "Non RPC exception.";
            });

            var ex = new InvalidOperationException("Non RPC exception.");
            var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>((request, context) =>
            {
                return Task.FromException<HelloReply>(ex);
            }, "GrpcErrorMethod");

            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();
            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                method.FullName,
                new GrpcStreamContent(ms)).DefaultTimeout();

            // replacedert
            response.replacedertIsSuccessfulGrpcRequest();

            response.replacedertTrailerStatus(StatusCode.Unknown, "Exception was thrown by handler. InvalidOperationException: Non RPC exception.");

            replacedertHasLog(LogLevel.Error, "ErrorExecutingServiceMethod", "Error when executing service method 'GrpcErrorMethod'.", e => e == ex);
        }

19 View Source File : AsyncClientStreamingCallTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task ClientStreamWriter_CallThrowsException_WriteAsyncThrowsError()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new InvalidOperationException("Error!"));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncClientStreamingCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions());
            var writeException = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.RequestStream.WriteAsync(new HelloRequest())).DefaultTimeout();
            var resultException = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            // replacedert
            replacedert.AreEqual("Error starting gRPC call. InvalidOperationException: Error!", writeException.Status.Detail);
            replacedert.AreEqual("Error starting gRPC call. InvalidOperationException: Error!", resultException.Status.Detail);
            replacedert.AreEqual(StatusCode.Internal, call.GetStatus().StatusCode);
        }

19 View Source File : ConnectionTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task UnaryCall_IOException_ThrowCorrectStatus()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new HttpRequestException("Blah", new IOException("")));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncUnaryCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: invoker.Channel.Clock.UtcNow.AddSeconds(1)), new HelloRequest());

            // replacedert
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            replacedert.AreEqual(StatusCode.Unavailable, ex.StatusCode);
        }

19 View Source File : GetTrailersTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public void AsyncUnaryCall_ErrorCall_ThrowsError()
        {
            // Arrange
            var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);

            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new Exception("An error!"));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncUnaryCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest());
            var ex = replacedert.Throws<InvalidOperationException>(() => call.GetTrailers())!;

            // replacedert
            replacedert.AreEqual("Can't get the call trailers because the call has not completed successfully.", ex.Message);
        }

19 View Source File : GrpcChannelTests.cs
License : Apache License 2.0
Project Creator : grpc

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                return Task.FromException<HttpResponseMessage>(new InvalidOperationException(ExceptionMessage));
            }

19 View Source File : HttpContentClientStreamReaderTests.cs
License : Apache License 2.0
Project Creator : grpc

public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
            {
                return new ValueTask<int>(Task.FromException<int>(new IOException("Test")));
            }

19 View Source File : ResponseAsyncTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task AsyncUnaryCall_ErrorSendingRequest_ThrowsErrorWithInnerExceptionDetail()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new Exception("An error!", new Exception("Nested error!")));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncUnaryCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest());
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseAsync).DefaultTimeout();

            // replacedert
            replacedert.AreEqual(StatusCode.Internal, ex.StatusCode);
            replacedert.AreEqual("Error starting gRPC call. Exception: An error! Exception: Nested error!", ex.Status.Detail);
            replacedert.AreEqual("Nested error!", ex.Status.DebugException.InnerException!.Message);
            replacedert.AreEqual(StatusCode.Internal, call.GetStatus().StatusCode);
        }

19 View Source File : ResponseHeadersAsyncTests.cs
License : Apache License 2.0
Project Creator : grpc

[Test]
        public async Task AsyncServerStreamingCall_ErrorSendingRequest_ReturnsError()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromException<HttpResponseMessage>(new Exception("An error!"));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            var call = invoker.AsyncServerStreamingCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest());
            var ex = await Exceptionreplacedert.ThrowsAsync<RpcException>(() => call.ResponseHeadersAsync).DefaultTimeout();

            // replacedert
            replacedert.AreEqual(StatusCode.Internal, ex.StatusCode);
            replacedert.AreEqual("Error starting gRPC call. Exception: An error!", ex.Status.Detail);
            replacedert.AreEqual(StatusCode.Internal, call.GetStatus().StatusCode);
        }

19 View Source File : CrawlerManager.cs
License : MIT License
Project Creator : Haishi2016

public virtual async Task<List<CrawlJob>> CreateJobs ()
        {
            return await Task.FromException<List<CrawlJob>>(new InvalidOperationException());
        }

19 View Source File : State.cs
License : MIT License
Project Creator : hardkoded

public virtual Task StartAsync(LauncherBase p) => Task.FromException(InvalidOperation("start"));

19 View Source File : State.cs
License : MIT License
Project Creator : hardkoded

public virtual Task KillAsync(LauncherBase p) => Task.FromException(InvalidOperation("kill"));

19 View Source File : InitialState.cs
License : MIT License
Project Creator : hardkoded

public override Task WaitForExitAsync(LauncherBase p) => Task.FromException(InvalidOperation("wait for exit"));

19 View Source File : State.cs
License : MIT License
Project Creator : hardkoded

public virtual Task EnterFromAsync(LauncherBase p, State fromState, TimeSpan timeout) => Task.FromException(InvalidOperation("enterFrom"));

19 View Source File : State.cs
License : MIT License
Project Creator : hardkoded

public virtual Task ExitAsync(LauncherBase p, TimeSpan timeout) => Task.FromException(InvalidOperation("exit"));

19 View Source File : LocationSpecRocksDb.cs
License : Apache License 2.0
Project Creator : Horusiath

public override Task<BatchReadResult> Read(long fromSequenceNr, long toSequenceNr, int max)
            {
                if (fromSequenceNr == ErrorSequenceNr) 
                    return Task.FromException<BatchReadResult>(IntegrationTestException.Instance);
                
                return base.Read(fromSequenceNr, toSequenceNr, max);
            }

19 View Source File : LocationSpecRocksDb.cs
License : Apache License 2.0
Project Creator : Horusiath

public override Task<BatchReadResult> Read(long fromSequenceNr, long toSequenceNr, int max, string aggregateId)
            {
                if (fromSequenceNr == ErrorSequenceNr) 
                    return Task.FromException<BatchReadResult>(IntegrationTestException.Instance);

                return base.Read(fromSequenceNr, toSequenceNr, max, aggregateId);
            }

19 View Source File : LocationSpecRocksDb.cs
License : Apache License 2.0
Project Creator : Horusiath

public override Task<BatchReadResult> ReplicationRead(long fromSequenceNr, long toSequenceNr, int max, int scanLimit, Func<DurableEvent, bool> filter)
            {
                if (fromSequenceNr == ErrorSequenceNr) 
                    return Task.FromException<BatchReadResult>(IntegrationTestException.Instance);

                return base.ReplicationRead(fromSequenceNr, toSequenceNr, max, scanLimit, filter);
            }

19 View Source File : SocketMediator.tests.cs
License : Apache License 2.0
Project Creator : IBM

[TestMethod]
        public async Task HandlesConnectionUpgradeFailureCorrectly()
        {
            // 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);

            var initialProbeResponse = Encoding.UTF8.GetBytes("3probe");
            var secondaryProbeResponse = Encoding.UTF8.GetBytes("5");


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

            socketMock.Setup(s => s.ConnectAsync(It.IsAny<Uri>(), 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 Asyncreplacedert.Throws<HttpRequestException>(
                () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object));

            Mock.VerifyAll(socketMock, socketFactoryMock, factoryMock);
        }

19 View Source File : SocketMediator.tests.cs
License : Apache License 2.0
Project Creator : IBM

[TestMethod]
        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 Asyncreplacedert.Throws<HttpRequestException>(
                () => mediator.InitConnection(factoryMock.Object, socketFactoryMock.Object));

            Mock.VerifyAll(socketMock, socketFactoryMock, factoryMock);
        }

19 View Source File : TaskHelper_GetAll.cs
License : MIT License
Project Creator : impworks

[Test]
        public void GetAll_throws_exception_if_task_failed()
        {
            replacedert.ThrowsAsync<NotImplementedException>(async () =>
            {
                await TaskHelper.GetAll(
                    Task.FromResult(1),
                    Task.FromException<int>(new NotImplementedException())
                );
            });
        }

19 View Source File : RemoteGattServer.android.cs
License : MIT License
Project Creator : inthehand

Task PlatformConnect()
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

            void handler(object s, ConnectionStateEventArgs e)
            {
                ConnectionStateChanged -= handler;

                switch (e.Status)
                {
                    case ABluetooth.GattStatus.Success:
                        tcs.SetResult(e.State == ABluetooth.ProfileState.Connected);
                        break;

                    default:
                        tcs.SetResult(false);
                        break;
                }
            }

            ConnectionStateChanged += handler;
            bool success = _gatt.Connect();
            if (success)
            {
                if (IsConnected)
                    return Task.FromResult(true);

                return tcs.Task;
            }
            else
            {
                ConnectionStateChanged -= handler;
                return Task.FromException(new OperationCanceledException());
            }
        }

19 View Source File : Bluetooth.standard.cs
License : MIT License
Project Creator : inthehand

private static Task<BluetoothDevice> PlatformRequestDevice(RequestDeviceOptions options)
        {
            return Task.FromException<BluetoothDevice>(new PlatformNotSupportedException());
        }

19 View Source File : Bluetooth.standard.cs
License : MIT License
Project Creator : inthehand

private static Task<IReadOnlyCollection<BluetoothDevice>> PlatformScanForDevices(RequestDeviceOptions options)
        {
            return Task.FromException<IReadOnlyCollection<BluetoothDevice>>(new PlatformNotSupportedException());
        }

19 View Source File : Bluetooth.standard.cs
License : MIT License
Project Creator : inthehand

private static Task<IReadOnlyCollection<BluetoothDevice>> PlatformGetPairedDevices()
        {
            return Task.FromException<IReadOnlyCollection<BluetoothDevice>>(new PlatformNotSupportedException());
        }

19 View Source File : Bluetooth.standard.cs
License : MIT License
Project Creator : inthehand

private static Task<BluetoothLEScan> PlatformRequestLEScan(BluetoothLEScanOptions options)
        {
            return Task.FromException<BluetoothLEScan>(new PlatformNotSupportedException());
        }

19 View Source File : GattCharacteristic.standard.cs
License : MIT License
Project Creator : inthehand

Task PlatformWriteValue(byte[] value, bool requireResponse)
        {
            return Task.FromException(new PlatformNotSupportedException());
        }

19 View Source File : GattCharacteristic.standard.cs
License : MIT License
Project Creator : inthehand

private Task PlatformStartNotifications()
        {
            return Task.FromException(new PlatformNotSupportedException());
        }

19 View Source File : GattCharacteristic.standard.cs
License : MIT License
Project Creator : inthehand

private Task PlatformStopNotifications()
        {
            return Task.FromException(new PlatformNotSupportedException());
        }

19 View Source File : NdefReader.Standard.cs
License : MIT License
Project Creator : inthehand

private Task PlatformScanAsync(NdefScanOptions options = null)
        {
            return Task.FromException(new PlatformNotSupportedException());
        }

19 View Source File : GattDescriptor.android.cs
License : MIT License
Project Creator : inthehand

Task PlatformWriteValue(byte[] value)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

            void handler(object s, DescriptorEventArgs e)
            {
                if (e.Descriptor == _descriptor)
                {
                    Characteristic.Service.Device.Gatt.DescriptorWrite -= handler;

                    if (!tcs.Task.IsCompleted)
                    {
                        tcs.SetResult(e.Status == ABluetooth.GattStatus.Success);
                    }
                }
            };

            Characteristic.Service.Device.Gatt.DescriptorWrite += handler;
            bool written = _descriptor.SetValue(value);
            written = ((ABluetooth.BluetoothGatt)Characteristic.Service.Device.Gatt).WriteDescriptor(_descriptor);
            if(written)
                return tcs.Task;

            return Task.FromException(new OperationCanceledException());
        }

19 View Source File : BrowseAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "BrowseAsync")]
        [Theory(DisplayName = "BrowseAsync throws TimeoutException on timeout"), AutoData]
        public async Task BrowseAsync_Throws_TimeoutException_On_Timeout(string username, IPEndPoint endpoint, string localUsername)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.WaitIndefinitely<BrowseResponse>(It.IsAny<WaitKey>(), It.IsAny<CancellationToken>()));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, endpoint.Address, endpoint.Port)));

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            waiter.Setup(m => m.Wait<(MessageReceivedEventArgs, IMessageConnection)>(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken?>()))
                .Returns(Task.FromException<(MessageReceivedEventArgs, IMessageConnection)>(new TimeoutException()));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: conn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("Username", localUsername);
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.BrowseAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<TimeoutException>(ex);
            }
        }

19 View Source File : ChangePasswordAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "ChangePreplacedwordAsync")]
        [Theory(DisplayName = "ChangePreplacedwordAsync throws SoulseekClientException on throw"), AutoData]
        public async Task ChangePreplacedwordAsync_Throws_SoulseekClientException_On_Throw(string preplacedword)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<string>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(preplacedword));

            var serverConn = new Mock<IMessageConnection>();
            serverConn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new ConnectionException()));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.ChangePreplacedwordAsync(preplacedword));

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
                replacedert.IsType<ConnectionException>(ex.InnerException);
            }
        }

19 View Source File : GetDirectoryContentsAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetDirectoryContentsAsync")]
        [Theory(DisplayName = "GetDirectoryContentsAsync throws TimeoutException on timeout"), AutoData]
        public async Task GetDirectoryContentsAsync_Throws_TimeoutException_On_Timeout(string username, string directory)
        {
            var result = new Directory(directory);

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<Directory>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(result));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, IPAddress.Parse("127.0.0.1"), 1)));

            var serverConn = new Mock<IMessageConnection>();
            serverConn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new TimeoutException()));

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, It.IsAny<IPEndPoint>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                Directory dir = null;
                var ex = await Record.ExceptionAsync(async () => dir = await s.GetDirectoryContentsAsync(username, directory));

                replacedert.NotNull(ex);
                replacedert.IsType<TimeoutException>(ex);
            }
        }

19 View Source File : GetDirectoryContentsAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetDirectoryContentsAsync")]
        [Theory(DisplayName = "GetDirectoryContentsAsync throws OperationCanceledException on cancellation"), AutoData]
        public async Task GetDirectoryContentsAsync_Throws_OperationCanceledException_On_Cancellation(string username, string directory)
        {
            var result = new Directory(directory);

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<Directory>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(result));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, IPAddress.Parse("127.0.0.1"), 1)));

            var serverConn = new Mock<IMessageConnection>();
            serverConn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new OperationCanceledException()));

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, It.IsAny<IPEndPoint>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                Directory dir = null;
                var ex = await Record.ExceptionAsync(async () => dir = await s.GetDirectoryContentsAsync(username, directory));

                replacedert.NotNull(ex);
                replacedert.IsType<OperationCanceledException>(ex);
            }
        }

19 View Source File : GetDownloadPlaceInQueueAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetDownloadPlaceInQueueAsync")]
        [Theory(DisplayName = "GetDownloadPlaceInQueueAsync throws UserOfflineException on user offline"), AutoData]
        public async Task GetDownloadPlaceInQueueAsync_Throws_UserOfflineException_On_User_Offline(string username, string filename)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserAddressResponse>(new UserOfflineException()));

            var serverConn = new Mock<IMessageConnection>();
            var connManager = new Mock<IPeerConnectionManager>();

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var dict = new ConcurrentDictionary<int, TransferInternal>();
                dict.GetOrAdd(0, new TransferInternal(TransferDirection.Download, username, filename, 0));

                s.SetProperty("Downloads", dict);

                var ex = await Record.ExceptionAsync(() => s.GetDownloadPlaceInQueueAsync(username, filename));

                replacedert.NotNull(ex);
                replacedert.IsType<UserOfflineException>(ex);
            }
        }

See More Examples