コード例 #1
0
        public async Task ServerMethodReturnsNull_FailureResponse()
        {
            // Arrange
            SetExpectedErrorsFilter(writeContext =>
            {
                return(writeContext.LoggerName == typeof(CounterService).FullName &&
                       writeContext.EventId.Name == "RpcConnectionError" &&
                       writeContext.State.ToString() == "Error status code 'Cancelled' raised." &&
                       GetRpcExceptionDetail(writeContext.Exception) == "No message returned from method.");
            });

            var requestMessage = new CounterRequest
            {
                Count = 1
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                "Count.Counter/IncrementCountReturnNull",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            Assert.AreEqual(StatusCode.Cancelled.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
            Assert.AreEqual("No message returned from method.", Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.MessageTrailer].Single());
        }
コード例 #2
0
        public async Task SendCompressedMessageAndReturnResultWithNoCompressFlag_ResponseNotCompressed()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage, "gzip");

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Compression.CompressionService/WriteMessageWithoutCompression");

            httpRequest.Headers.Add(GrpcProtocolConstants.MessageEncodingHeader, "gzip");
            httpRequest.Headers.Add(GrpcProtocolConstants.MessageAcceptEncodingHeader, "gzip");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            // The overall encoding is gzip but the actual response does not use compression
            Assert.AreEqual("gzip", response.Headers.GetValues(GrpcProtocolConstants.MessageEncodingHeader).Single());

            var responseMessage = MessageHelpers.AssertReadMessage <HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());

            Assert.AreEqual("Hello World", responseMessage.Message);
            response.AssertTrailerStatus();
        }
コード例 #3
0
        public async Task SendCompressedMessageWithIdentity_ReturnInternalError()
        {
            // Arrange
            SetExpectedErrorsFilter(writeContext =>
            {
                return(writeContext.LoggerName == typeof(GreeterService).FullName &&
                       writeContext.EventId.Name == "RpcConnectionError" &&
                       writeContext.State.ToString() == "Error status code 'Internal' raised.");
            });

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

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage, "gzip");

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");

            httpRequest.Headers.Add(GrpcProtocolConstants.MessageEncodingHeader, "identity");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            response.AssertTrailerStatus(StatusCode.Internal, "Request sent 'identity' grpc-encoding value with compressed message.");
        }
コード例 #4
0
        public async Task SendIdentityGrpcAcceptEncodingToServiceWithCompression_ResponseUncompressed()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = GrpcHttpHelper.Create("Compression.CompressionService/SayHello");

            httpRequest.Headers.Add(GrpcProtocolConstants.MessageEncodingHeader, "identity");
            httpRequest.Headers.Add(GrpcProtocolConstants.MessageAcceptEncodingHeader, "identity");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual("identity", response.Headers.GetValues(GrpcProtocolConstants.MessageEncodingHeader).Single());

            var responseMessage = MessageHelpers.AssertReadMessage <HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());

            Assert.AreEqual("Hello World", responseMessage.Message);
            response.AssertTrailerStatus();
        }
        protected virtual byte[] GetMessageData(HelloReply message)
        {
            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, message);
            return(ms.ToArray());
        }
コード例 #6
0
        public async Task HttpContextExtensionMethod_ReturnContextInTrailer()
        {
            // Arrange
            var url = Fixture.DynamicGrpc.AddUnaryMethod <HttpContextTests, HelloRequest, HelloReply>((request, context) =>
            {
                var httpContext = context.GetHttpContext();
                context.ResponseTrailers.Add("Test-HttpContext-PathAndQueryString", httpContext.Request.Path + httpContext.Request.QueryString);

                return(Task.FromResult(new HelloReply {
                    Message = "Hello " + request.Name
                }));
            });

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

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, $"{url}?query=extra");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].ToString());
            Assert.AreEqual($"{url}?query=extra", Fixture.TrailersContainer.Trailers["Test-HttpContext-PathAndQueryString"].ToString());
        }
コード例 #7
0
        public async Task AdditionalDataAfterStreamedMessage_ErrorResponse()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            var requestStream = new SyncPointMemoryStream();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");

            httpRequest.Content = new StreamContent(requestStream);

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");

            await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();

            await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();

            await responseTask.DefaultTimeout();

            Assert.AreEqual(StatusCode.Internal.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
            Assert.AreEqual("Additional data after the message received.", Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.MessageTrailer].Single());
        }
コード例 #8
0
        public async Task ServerMethodReturnsNull_FailureResponse()
        {
            // Arrange
            var url = Fixture.DynamicGrpc.AddClientStreamingMethod <ClientStreamingMethodTests, Empty, CounterReply>((requestStream, context) => Task.FromResult <CounterReply>(null));

            SetExpectedErrorsFilter(writeContext =>
            {
                return(writeContext.LoggerName == typeof(ClientStreamingMethodTests).FullName &&
                       writeContext.EventId.Name == "RpcConnectionError" &&
                       writeContext.State.ToString() == "Error status code 'Cancelled' raised." &&
                       GetRpcExceptionDetail(writeContext.Exception) == "No message returned from method.");
            });

            var requestMessage = new CounterRequest
            {
                Count = 1
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

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

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            Assert.AreEqual(StatusCode.Cancelled.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
            Assert.AreEqual("No message returned from method.", Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.MessageTrailer].Single());
        }
コード例 #9
0
        public async Task HostActivityTags_ReturnedInTrailers_Success()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            var httpRequest = GrpcHttpHelper.Create("Greet.Greeter/SayHello");

            httpRequest.Content = new GrpcStreamContent(ms);
            httpRequest.Headers.Add("return-tags-trailers", "true");

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            var responseMessage = await response.GetSuccessfulGrpcMessageAsync <HelloReply>().DefaultTimeout();

            Assert.AreEqual("Hello World", responseMessage.Message);
            response.AssertTrailerStatus();

            var trailers = response.TrailingHeaders;

            Assert.AreEqual("0", trailers.GetValues("grpc.status_code").Single());
            Assert.AreEqual("/Greet.Greeter/SayHello", trailers.GetValues("grpc.method").Single());
        }
コード例 #10
0
        public async Task SentMessageExceedsSize_ThrowError()
        {
            // Arrange
            SetExpectedErrorsFilter(writeContext =>
            {
                return(writeContext.LoggerName == typeof(GreeterService).FullName &&
                       writeContext.EventId.Name == "RpcConnectionError" &&
                       writeContext.State.ToString() == "Error status code 'ResourceExhausted' raised." &&
                       GetRpcExceptionDetail(writeContext.Exception) == "Sending message exceeds the maximum configured message size.");
            });

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

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            await Fixture.Client.PostAsync(
                "Greet.Greeter/SayHelloSendLargeReply",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            Assert.AreEqual(StatusCode.ResourceExhausted.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
            Assert.AreEqual("Sending message exceeds the maximum configured message size.", Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.MessageTrailer].Single());
        }
コード例 #11
0
        public async Task MultipleMessagesThenClose_SuccessResponse()
        {
            // Arrange
            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new CounterRequest
            {
                Count = 1
            });

            var httpRequest = GrpcHttpHelper.Create("Count.Counter/AccumulateCount");

            httpRequest.Content = new PushStreamContent(
                async s =>
            {
                await s.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();
                await s.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();
                await s.WriteAsync(Array.Empty <byte>()).AsTask().DefaultTimeout();
            });

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");


            var response = await responseTask.DefaultTimeout();

            var reply = await response.GetSuccessfulGrpcMessageAsync <CounterReply>().DefaultTimeout();

            Assert.AreEqual(2, reply.Count);
            response.AssertTrailerStatus();
        }
コード例 #12
0
        public async Task CallAuthorizedServiceWithToken_Success()
        {
            // Arrange
            var tokenResponse = await Fixture.Client.GetAsync("generateJwtToken").DefaultTimeout();

            var token = await tokenResponse.Content.ReadAsStringAsync();

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

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Authorize.AuthorizedGreeter/SayHello");

            httpRequest.Headers.Add("Authorization", $"Bearer {token}");
            httpRequest.Content = new GrpcStreamContent(ms);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest);

            // Assert
            var responseMessage = await response.GetSuccessfulGrpcMessageAsync <HelloReply>();

            Assert.AreEqual("Hello World", responseMessage.Message);

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
        }
コード例 #13
0
        public void GlobalSetup()
        {
            var marshaller = Marshallers.Create((arg) => MessageExtensions.ToByteArray(arg), bytes => new ChatMessage());
            var method     = new Method <ChatMessage, ChatMessage>(MethodType.Unary, typeof(TestService).FullName, nameof(TestService.SayHello), marshaller, marshaller);

            _callHandler = new UnaryServerCallHandler <ChatMessage, ChatMessage, TestService>(method);

            _trailers = new HeaderDictionary();

            var messageData = new ChatMessage
            {
                Name = "Joe"
            }.ToByteArray();

            _requestStream = new MemoryStream();
            MessageHelpers.WriteMessage(_requestStream, messageData);

            var services = new ServiceCollection();

            services.TryAddSingleton <IGrpcServiceActivator <TestService> >(new TestGrpcServiceActivator <TestService>(new TestService()));
            _requestServices = services.BuildServiceProvider();

            _httpContext = new DefaultHttpContext();
            _httpContext.RequestServices = _requestServices;
            _httpContext.Request.Body    = _requestStream;

            _httpContext.Features.Set <IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
            {
                Trailers = _trailers
            });
        }
コード例 #14
0
        public async Task ReceivedMessageExceedsSize_ThrowError()
        {
            // Arrange
            SetExpectedErrorsFilter(writeContext =>
            {
                return(writeContext.LoggerName == "SERVER " + typeof(GreeterService).FullName &&
                       writeContext.EventId.Name == "RpcConnectionError" &&
                       writeContext.State.ToString() == "Error status code 'ResourceExhausted' raised." &&
                       GetRpcExceptionDetail(writeContext.Exception) == "Received message exceeds the maximum configured message size.");
            });

            var requestMessage = new HelloRequest
            {
                Name = "World" + new string('!', 64 * 1024)
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                "Greet.Greeter/SayHello",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            response.AssertTrailerStatus(StatusCode.ResourceExhausted, "Received message exceeds the maximum configured message size.");
        }
コード例 #15
0
        public async Task StreamedMessage_SuccessResponseAfterMessageReceived()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            var streamingContent = new StreamingContent();
            var httpRequest      = GrpcHttpHelper.Create("Greet.Greeter/SayHello");

            httpRequest.Content = streamingContent;

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");

            var requestStream = await streamingContent.GetRequestStreamAsync().DefaultTimeout();

            await requestStream.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();

            streamingContent.Complete();

            var response = await responseTask.DefaultTimeout();

            var responseMessage = await response.GetSuccessfulGrpcMessageAsync <HelloReply>().DefaultTimeout();

            Assert.AreEqual("Hello World", responseMessage.Message);
        }
コード例 #16
0
        public async Task StreamedMessage_SuccessResponseAfterMessageReceived()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            var requestStream = new SyncPointMemoryStream();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");

            await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();

            await requestStream.AddDataAndWait(Array.Empty <byte>()).DefaultTimeout();

            var response = await responseTask.DefaultTimeout();

            var responseMessage = await response.GetSuccessfulGrpcMessageAsync <HelloReply>();

            Assert.AreEqual("Hello World", responseMessage.Message);
        }
コード例 #17
0
        public async Task HttpContextAccessor_ReturnContextInTrailer()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHelloWithHttpContextAccessor?query=extra");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].ToString());
            Assert.AreEqual("/Greet.Greeter/SayHelloWithHttpContextAccessor?query=extra", Fixture.TrailersContainer.Trailers["Test-HttpContext-PathAndQueryString"].ToString());
        }
        public async Task SendValidRequest_SuccessResponse()
        {
            // Arrange
            var requestMessage = new EchoRequest
            {
                Message = "test"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var grpcWebClient = CreateGrpcWebClient();
            var response      = await grpcWebClient.PostAsync(
                "grpc.gateway.testing.EchoService/Echo",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            var s = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            var reader = PipeReader.Create(s);

            var message = await MessageHelpers.AssertReadStreamMessageAsync <EchoResponse>(reader).DefaultTimeout();

            Assert.AreEqual("test", message !.Message);

            response.AssertTrailerStatus();
        }
コード例 #19
0
        public async Task UnimplementedContentType_ReturnUnimplementedForAppGrpc(string contentType, string httpMethod, HttpStatusCode httpStatusCode, StatusCode?grpcStatusCode)
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = GrpcHttpHelper.Create("HasMapped/Extra");

            httpRequest.Method  = new HttpMethod(httpMethod);
            httpRequest.Content = new StreamContent(requestStream);
            httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(httpStatusCode, response.StatusCode);
            if (grpcStatusCode != null)
            {
                Assert.AreEqual(grpcStatusCode.Value.ToTrailerString(), response.Headers.GetValues(GrpcProtocolConstants.StatusTrailer).Single());
            }
            else
            {
                Assert.IsFalse(response.Headers.TryGetValues(GrpcProtocolConstants.StatusTrailer, out _));
                Assert.IsFalse(response.TrailingHeaders.TryGetValues(GrpcProtocolConstants.StatusTrailer, out _));
            }
        }
        public async Task SendValidRequest_ServerAbort_AbortResponse()
        {
            // Arrange
            var requestMessage = new EchoRequest
            {
                Message = "test"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var grpcWebClient = CreateGrpcWebClient();
            var response      = await grpcWebClient.PostAsync(
                "grpc.gateway.testing.EchoService/EchoAbort",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            var s = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            var reader = PipeReader.Create(s);

            var readResult = await reader.ReadAsync().AsTask().DefaultTimeout();

            Assert.AreEqual(0, readResult.Buffer.Length);
            Assert.IsTrue(readResult.IsCompleted);

            Assert.AreEqual("10", response.Headers.GetValues("grpc-status").Single());
            Assert.AreEqual("Aborted from server side.", response.Headers.GetValues("grpc-message").Single());

            AssertHasLogRpcConnectionError(StatusCode.Aborted, "Aborted from server side.");
        }
コード例 #21
0
        public async Task SendValidRequest_SuccessResponse()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                "Greet.Greeter/SayHello",
                new StreamContent(ms)).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual("identity", response.Headers.GetValues("grpc-encoding").Single());
            Assert.AreEqual("application/grpc", response.Content.Headers.ContentType.MediaType);

            var responseMessage = MessageHelpers.AssertReadMessage <HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());

            Assert.AreEqual("Hello World", responseMessage.Message);

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
        }
コード例 #22
0
        public async Task CallNestedService_SuccessResponse()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                "Nested.NestedService/SayHello",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var responseMessage = MessageHelpers.AssertReadMessage <HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());

            Assert.AreEqual("Hello Nested: World", responseMessage.Message);
            response.AssertTrailerStatus();
        }
コード例 #23
0
        public async Task InterceptorsExecutedInRegistrationOrder_AndGlobalInterceptorExecutesFirst_ServerStreaming()
        {
            // Arrange
            var url = Fixture.DynamicGrpc.AddServerStreamingMethod <InterceptorOrderTests, Empty, Empty>((request, responseStream, context) =>
            {
                var items = context.GetHttpContext().Items;
                Assert.AreEqual(3, items[OrderedInterceptor.OrderHeaderKey]);
                return(Task.CompletedTask);
            });

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new Empty());

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

            var responseStream = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            var pipeReader = new StreamPipeReader(responseStream);

            // Assert
            await MessageHelpers.AssertReadStreamMessageAsync <Empty>(pipeReader);

            response.AssertTrailerStatus();
        }
コード例 #24
0
        public async Task ServerMethodReturnsNull_FailureResponse()
        {
            // Arrange
            var method = Fixture.DynamicGrpc.AddClientStreamingMethod <Empty, CounterReply>((requestStream, context) => Task.FromResult <CounterReply>(null !));

            var requestMessage = new CounterRequest
            {
                Count = 1
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

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

            // Assert
            response.AssertIsSuccessfulGrpcRequest();
            response.AssertTrailerStatus(StatusCode.Cancelled, "No message returned from method.");

            AssertHasLogRpcConnectionError(StatusCode.Cancelled, "No message returned from method.");
        }
コード例 #25
0
        public async Task HttpContextExtensionMethod_ReturnContextInTrailer()
        {
            // Arrange
            var url = Fixture.DynamicGrpc.AddUnaryMethod <HelloRequest, HelloReply>((request, context) =>
            {
                var httpContext = context.GetHttpContext();
                context.ResponseTrailers.Add("Test-HttpContext-PathAndQueryString", httpContext.Request.Path + httpContext.Request.QueryString);

                return(Task.FromResult(new HelloReply {
                    Message = "Hello " + request.Name
                }));
            });

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

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = GrpcHttpHelper.Create($"{url}?query=extra");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();
            response.AssertTrailerStatus();
            Assert.AreEqual($"{url}?query=extra", response.TrailingHeaders.GetValues("Test-HttpContext-PathAndQueryString").Single());
        }
コード例 #26
0
        public async Task SendUnsupportedEncodingHeaderWithUncompressedMessage_ReturnUncompressedMessage()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");

            httpRequest.Headers.Add(GrpcProtocolConstants.MessageEncodingHeader, "DOES_NOT_EXIST");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].ToString());
        }
コード例 #27
0
        public async Task SendCompressedMessage_ServiceHasNoCompressionConfigured_ResponseIdentityEncoding()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage, "gzip");

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");

            httpRequest.Headers.Add(GrpcProtocolConstants.MessageEncodingHeader, "gzip");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual("identity", response.Headers.GetValues(GrpcProtocolConstants.MessageEncodingHeader).Single());

            var responseMessage = MessageHelpers.AssertReadMessage <HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout());

            Assert.AreEqual("Hello World", responseMessage.Message);
            response.AssertTrailerStatus();
        }
コード例 #28
0
        public async Task SendUncompressedMessageToServiceWithCompression_ResponseCompressed()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Compression.CompressionService/SayHello");

            httpRequest.Headers.Add(GrpcProtocolConstants.MessageAcceptEncodingHeader, "gzip");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual("gzip", response.Headers.GetValues(GrpcProtocolConstants.MessageEncodingHeader).Single());

            var responseMessage = MessageHelpers.AssertReadMessage <HelloReply>(await response.Content.ReadAsByteArrayAsync().DefaultTimeout(), "gzip");

            Assert.AreEqual("Hello World", responseMessage.Message);

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].ToString());
        }
コード例 #29
0
        public async Task ServerMethodReturnsNull_FailureResponse()
        {
            // Arrange
            var method = Fixture.DynamicGrpc.AddClientStreamingMethod <Empty, CounterReply>((requestStream, context) => Task.FromResult <CounterReply>(null !));

            SetExpectedErrorsFilter(writeContext =>
            {
                return(writeContext.LoggerName == TestConstants.ServerCallHandlerTestName &&
                       writeContext.EventId.Name == "RpcConnectionError" &&
                       writeContext.State.ToString() == "Error status code 'Cancelled' raised." &&
                       GetRpcExceptionDetail(writeContext.Exception) == "No message returned from method.");
            });

            var requestMessage = new CounterRequest
            {
                Count = 1
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

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

            // Assert
            response.AssertIsSuccessfulGrpcRequest();
            response.AssertTrailerStatus(StatusCode.Cancelled, "No message returned from method.");
        }
コード例 #30
0
        public async Task SentMessageExceedsSize_ThrowError()
        {
            // Arrange
            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName &&
                    writeContext.EventId.Name == "ErrorSendingMessage" &&
                    writeContext.State.ToString() == "Error sending message." &&
                    GetRpcExceptionDetail(writeContext.Exception) == "Sending message exceeds the maximum configured message size.")
                {
                    return(true);
                }

                return(false);
            });

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

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                "Greet.Greeter/SayHelloSendLargeReply",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            response.AssertTrailerStatus(StatusCode.ResourceExhausted, "Sending message exceeds the maximum configured message size.");

            AssertHasLogRpcConnectionError(StatusCode.ResourceExhausted, "Sending message exceeds the maximum configured message size.");
        }