public async Task StreamingFromClientTest() { // init var server = new GreeterService(NullLoggerFactory.Instance); var callContext = TestServerCallContext.Create(); var requestStream = new TestAsyncStreamReader <ExampleRequest>(callContext); // act using var call = server.StreamingFromClient(requestStream, callContext); requestStream.AddMessage(new ExampleRequest { PageIndex = 1, PageSize = 10, IsDescending = false }); requestStream.AddMessage(new ExampleRequest { PageIndex = 2, PageSize = 10, IsDescending = false }); requestStream.AddMessage(new ExampleRequest { PageIndex = 3, PageSize = 10, IsDescending = false }); requestStream.AddMessage(new ExampleRequest { PageIndex = 4, PageSize = 10, IsDescending = false }); requestStream.Complete(); // Assert var response = await call; Assert.IsTrue(response.Age > 1); }
public async Task OkGetTodoItemsTest() { var fakeServerCallContext = TestServerCallContext.Create("fooMethod", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }); var actual = await implement.GetTodoItems(new Empty(), fakeServerCallContext); Assert.Equal(expectedTodoItems, actual.Todos); }
public async Task StreamingFromServiceTest() { var service = new GreeterService(NullLoggerFactory.Instance); var cts = new CancellationTokenSource(); var callcontext = TestServerCallContext.Create(cancellationToken: cts.Token); var responseStream = new TestServerStreamWriter <ExampleResponse>(callcontext); try { // act using var call = service.StreamingFromService(new ExampleRequest { PageIndex = 1, PageSize = 10, IsDescending = false }, responseStream, callcontext); // assert Assert.IsFalse(call.IsCompletedSuccessfully, "Method should run until cancelled."); _ = Task.Delay(10000); cts.Cancel(); await call; } catch (Exception ex) { Console.WriteLine($"ex {ex.Message}"); } responseStream.Complete(); var allMessage = new List <ExampleResponse>(); await foreach (var message in responseStream.ReadAllAsync()) { allMessage.Add(message); } Assert.IsTrue(allMessage.Count > 0); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken) { var metadata = new Metadata(); foreach (var(key, value) in httpRequest.Headers) { metadata.Add(key, string.Join(",", value.ToArray())); } var context = TestServerCallContext.Create( method: httpRequest.Method.Method, host: httpRequest.RequestUri.Host, deadline: DateTime.UtcNow.AddHours(1), requestHeaders: metadata, cancellationToken: cancellationToken, peer: "127.0.0.1", authContext: null, contextPropagationToken: null, writeHeadersFunc: _ => TaskUtils.CompletedTask, writeOptionsGetter: () => new WriteOptions(), writeOptionsSetter: writeOptions => {}); var grpcRequest = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeServiceRequest>(httpRequest); var grpcResponse = await this.callbackService.OnInvoke(grpcRequest.Message, context); var streamContent = await GrpcUtils.CreateResponseContent(grpcResponse); var httpResponse = GrpcUtils.CreateResponse(HttpStatusCode.OK, streamContent); return(httpResponse); }
public static ServerCallContext CreateFakeCallContext() { return(TestServerCallContext.Create( "", "", DateTime.Now + TimeSpan.FromHours(1), Metadata.Empty, CancellationToken.None, "", null, null, meta => null, () => WriteOptions.Default, writeOptions => { } )); }
public async Task SayHelloClientStreamingTest() { // Arrange var mockGreeter = new Mock <IGreeter>(); mockGreeter.Setup(m => m.Greet(It.IsAny <string>())).Returns((string s) => $"Hello {s}"); var service = new TesterService(mockGreeter.Object); var callContext = TestServerCallContext.Create(); var requestStream = new TestAsyncStreamReader <HelloRequest>(callContext); // Act using var call = service.SayHelloClientStreaming(requestStream, callContext); requestStream.AddMessage(new HelloRequest { Name = "James" }); requestStream.AddMessage(new HelloRequest { Name = "Jo" }); requestStream.AddMessage(new HelloRequest { Name = "Lee" }); requestStream.Complete(); // Assert var response = await call; Assert.Equal("Hello James, Jo, Lee", response.Message); }
public async Task SayHelloClientStreamingTest() { // Arrange var service = new TesterService(NullLoggerFactory.Instance); var callContext = TestServerCallContext.Create(); var requestStream = new TestAsyncStreamReader <HelloRequest>(callContext); // Act var call = service.SayHelloClientStreaming(requestStream, callContext); requestStream.AddMessage(new HelloRequest { Name = "James" }); requestStream.AddMessage(new HelloRequest { Name = "Jo" }); requestStream.AddMessage(new HelloRequest { Name = "Lee" }); requestStream.Complete(); // Assert var response = await call; Assert.AreEqual("Hello James, Jo, Lee", response.Message); }
public async Task SayHelloServerStreamingTest() { // Arrange var mockGreeter = new Mock <IGreeter>(); mockGreeter.Setup(m => m.Greet(It.IsAny <string>())).Returns((string s) => $"Hello {s}"); var service = new TesterService(mockGreeter.Object); var cts = new CancellationTokenSource(); var callContext = TestServerCallContext.Create(cancellationToken: cts.Token); var responseStream = new TestServerStreamWriter <HelloReply>(callContext); // Act using var call = service.SayHelloServerStreaming(new HelloRequest { Name = "Joe" }, responseStream, callContext); // Assert Assert.False(call.IsCompletedSuccessfully, "Method should run until cancelled."); cts.Cancel(); await call; responseStream.Complete(); var allMessages = new List <HelloReply>(); await foreach (var message in responseStream.ReadAllAsync()) { allMessages.Add(message); } Assert.True(allMessages.Count >= 1); Assert.Equal("Hello Joe 1", allMessages[0].Message); }
public async Task GreeterService_SayHelloBidirectionalStreaming_ReturnsCorrectResponse() { // Arrange var service = new GreeterService(new Logger <GreeterService>(new NullLoggerFactory())); var callContext = TestServerCallContext.Create(); var requestStream = new TestAsyncStreamReader <HelloRequest>(callContext); var responseStream = new TestServerStreamWriter <HelloReply>(callContext); // Act var call = service.SayHelloBidirectionalStreaming(requestStream, responseStream, callContext); // Assert requestStream.AddMessage(new HelloRequest { Name = "James" }); Assert.AreEqual("Hello James", (await responseStream.ReadNextAsync()) !.Message); requestStream.AddMessage(new HelloRequest { Name = "Jo" }); Assert.AreEqual("Hello Jo", (await responseStream.ReadNextAsync()) !.Message); requestStream.AddMessage(new HelloRequest { Name = "Lee" }); Assert.AreEqual("Hello Lee", (await responseStream.ReadNextAsync()) !.Message); requestStream.Complete(); await call; responseStream.Complete(); Assert.IsNull(await responseStream.ReadNextAsync()); }
public async Task GreeterService_SayHelloServerStreaming_ReturnsCorrectResponse() { // Arrange var service = new GreeterService(new Logger <GreeterService>(new NullLoggerFactory())); var cts = new CancellationTokenSource(); var callContext = TestServerCallContext.Create(cancellationToken: cts.Token); var responseStream = new TestServerStreamWriter <HelloReply>(callContext); // Act var call = service.SayHelloServerStreaming(new HelloRequest { Name = "Joe" }, responseStream, callContext); // Assert Assert.IsFalse(call.IsCompletedSuccessfully, "Method should run until cancelled."); cts.Cancel(); await call; responseStream.Complete(); var allMessages = new List <HelloReply>(); // ReSharper disable once UseCancellationTokenForIAsyncEnumerable await foreach (var message in responseStream.ReadAllAsync()) { allMessages.Add(message); } Assert.IsTrue(allMessages.Count >= 1); Assert.AreEqual("How are you Joe? 1", allMessages[0].Message); }
private ServerCallContext BuildServerCallContext(Metadata metadata = null) { var meta = metadata ?? new Metadata(); return(TestServerCallContext.Create("mock", null, DateTime.UtcNow.AddHours(1), meta, CancellationToken.None, "127.0.0.1", null, null, m => TaskUtils.CompletedTask, () => new WriteOptions(), writeOptions => { })); }
public async Task SayHelloServerStreamingTest() { // Arrange var service = new TesterService(NullLoggerFactory.Instance); var cts = new CancellationTokenSource(); var callContext = TestServerCallContext.Create(cancellationToken: cts.Token); var responseStream = new TestServerStreamWriter <HelloReply>(callContext); // Act var call = service.SayHelloServerStreaming(new HelloRequest { Name = "Joe" }, responseStream, callContext); // Assert Assert.IsFalse(call.IsCompletedSuccessfully, "Method should run until cancelled."); cts.Cancel(); await call; responseStream.Complete(); var allMessages = new List <HelloReply>(); await foreach (var message in responseStream.ReadAllAsync()) { allMessages.Add(message); } Assert.GreaterOrEqual(allMessages.Count, 1); Assert.AreEqual("How are you Joe? 1", allMessages[0].Message); }
public void GetHttpContext_CustomServerCallContext_Error() { var serverCallContext = new TestServerCallContext(DateTime.MinValue, CancellationToken.None); var ex = Assert.Throws <InvalidOperationException>(() => serverCallContext.GetHttpContext()) !; Assert.AreEqual("Could not get HttpContext from ServerCallContext. HttpContext can only be accessed when gRPC services are hosted by ASP.NET Core.", ex.Message); }
public static ServerCallContext NewContext() { // TODO: populate the context return(TestServerCallContext.Create(null, null, default(DateTime), new Metadata(), CancellationToken.None, null, null, null, null, null, null)); //Create(string method, string host, DateTime deadline, Metadata requestHeaders, CancellationToken cancellationToken, //string peer, AuthContext authContext, ContextPropagationToken contextPropagationToken, //Func<Metadata, Task> writeHeadersFunc, Func<WriteOptions> writeOptionsGetter, Action<WriteOptions> writeOptionsSetter) }
private ServerCallContext BuildServerCallContext(Metadata metadata = null, string peer = null) { var meta = metadata ?? new Metadata(); return(TestServerCallContext.Create("mock", "127.0.0.1", TimestampHelper.GetUtcNow().AddHours(1).ToDateTime(), meta, CancellationToken.None, peer ?? "ipv4:127.0.0.1:2100", null, null, m => TaskUtils.CompletedTask, () => new WriteOptions(), writeOptions => { })); }
private IHttpContextAccessor CreateHttpContextAccessorWithServerCallContext(DateTime deadline = default, CancellationToken cancellationToken = default) { var httpContext = new DefaultHttpContext(); var serverCallContext = new TestServerCallContext(deadline, cancellationToken); var serverCallContextFeature = new TestServerCallContextFeature(serverCallContext); httpContext.Features.Set <IServerCallContextFeature>(serverCallContextFeature); return(CreateHttpContextAccessor(httpContext)); }
public async Task Test1() { var handle = new HandleService(); var id = Guid.NewGuid().ToString(); var fakeServerCallContext = TestServerCallContext.Create("fooMethod", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }); var response = await handle.AddProduct(new Product { Id = id }, fakeServerCallContext); Assert.NotEmpty(response.Value); }
public void GetHttpContext_CustomServerCallContextWithContextInUserState_Success() { var httpContext = new DefaultHttpContext(); var serverCallContext = new TestServerCallContext(DateTime.MinValue, CancellationToken.None); serverCallContext.UserState[ServerCallContextExtensions.HttpContextKey] = httpContext; Assert.AreEqual(httpContext, serverCallContext.GetHttpContext()); }
public async Task PublishAsync_Watch_ChangingStatus() { // Arrange var healthService = new HealthServiceImpl(); var publisher = new GrpcHealthChecksPublisher(healthService); var responseStream = new TestServerStreamWriter <HealthCheckResponse>(); var cts = new CancellationTokenSource(); var serverCallContext = new TestServerCallContext(DateTime.MinValue, cts.Token); // Act 1 var call = healthService.Watch(new HealthCheckRequest { Service = "" }, responseStream, serverCallContext); // Assert 1 await TestHelpers.AssertIsTrueRetryAsync(() => responseStream.Responses.Count == 1, "Unexpected response count."); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.ServiceUnknown, responseStream.Responses.Last().Status); // Act 2 await publisher.PublishAsync(CreateSimpleHealthReport(HealthStatus.Healthy), CancellationToken.None); // Assert 2 await TestHelpers.AssertIsTrueRetryAsync(() => responseStream.Responses.Count == 2, "Unexpected response count."); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.Serving, responseStream.Responses.Last().Status); // Act 3 await publisher.PublishAsync(CreateSimpleHealthReport(HealthStatus.Degraded), CancellationToken.None); // Act 3 await TestHelpers.AssertIsTrueRetryAsync(() => responseStream.Responses.Count == 2, "Unexpected response count."); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.Serving, responseStream.Responses.Last().Status); // Act 4 await publisher.PublishAsync(CreateSimpleHealthReport(HealthStatus.Unhealthy), CancellationToken.None); // Act 4 await TestHelpers.AssertIsTrueRetryAsync(() => responseStream.Responses.Count == 3, "Unexpected response count."); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.NotServing, responseStream.Responses.Last().Status); // End call cts.Cancel(); await call.DefaultTimeout(); // Act 4 await publisher.PublishAsync(CreateSimpleHealthReport(HealthStatus.Healthy), CancellationToken.None); // Act 4 await TestHelpers.AssertIsTrueRetryAsync(() => responseStream.Responses.Count == 3, "Unexpected response count."); Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.NotServing, responseStream.Responses.Last().Status); }
public static ServerCallContext CreateFakeCallContext(string playerId, string pit) { var metadata = new Metadata { { PlayerIdentifierHeader, playerId }, { PlayerIdentityTokenHeader, pit } }; var context = TestServerCallContext.Create( "", "", DateTime.Now + TimeSpan.FromHours(1), metadata, CancellationToken.None, "", null, null, meta => null, () => WriteOptions.Default, writeOptions => { }); return(context); }
public async Task GetUsers_WhenUsersDoNotExist_ShouldReturnEmptyCollection() { // Arrange var service = new UserHandlerV1(this._mockLogger.Object); // Act GetUsersResponse response = await service.GetUsers(new Empty(), TestServerCallContext.Create()); // Asserts response.Users.Should().BeEmpty(); }
public async Task OkDeleteTodoItemTest() { var expectedTodoItem = expectedTodoItems[0]; var request = new DeleteTodoItemRequest { Id = expectedTodoItem.Id }; var fakeServerCallContext = TestServerCallContext.Create("fooMethod", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }); var actual = await implement.DeleteTodoItem(request, fakeServerCallContext); Assert.Equal(2, expectedTodoItems.Count); Assert.DoesNotContain <Todo>(actual.Todo, expectedTodoItems); }
private static ServerCallContext GetServerCallContext(string method) => TestServerCallContext.Create( method, "127.0.0.1", DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, x => TaskUtils.CompletedTask, () => new WriteOptions(), x => { });
public void Initialize() { _callContext = TestServerCallContext.Create(_guid.ToString(), null, DateTime.Now, null, CancellationToken.None, null, null, null, null, null, null); _handler = A.Fake <IHandlerStore>(); _dispatcher = A.Fake <IDispatcher>(); _config = new MapGrpcServiceConfiguration(); _compiler = new DispatcherCompiler(_handler, _config); }
public async Task ServerCallImplIsTestable() { var mathImpl = new MathServiceImpl(); // Use a factory method provided by Grpc.Core.Testing.TestServerCallContext to create an instance of server call context. // This allows testing even those server-side implementations that rely on the contents of ServerCallContext. var fakeServerCallContext = TestServerCallContext.Create("fooMethod", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }); var response = await mathImpl.Div(new DivArgs { Dividend = 10, Divisor = 2 }, fakeServerCallContext); Assert.AreEqual(5, response.Quotient); Assert.AreEqual(0, response.Remainder); }
public async Task SayHelloUnaryTest() { // Arrange var service = new TesterService(NullLoggerFactory.Instance.CreateLogger <TesterService>()); // Act var response = await service.SayHelloUnary(new Test.HelloRequest { Name = "Joe" }, TestServerCallContext.Create()); //Assert Assert.AreEqual("Hello Joe", response.Message); }
public async Task OkPutTodoItemTest() { var updateTodoItem = expectedTodoItems[0]; var todo = new Todo { Id = updateTodoItem.Id, Name = "OkPutPostTodoItemTest", IsComplete = true }; var request = new PutTodoItemRequest { Todo = todo }; var fakeServerCallContext = TestServerCallContext.Create("fooMethod", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }); var actual = await implement.PutTodoItem(request, fakeServerCallContext); Assert.Equal(expectedTodoItems[0], actual.Todo); }
public async Task TestGetScopesSystem1() { // Arrange var service = new AuthenticationService(db, new JwtSettings(), await MockTokenClaimsAccessor(db, "system", "system")); // Act var resp = await service.GetScopes(new GetScopesRequest() { Username = "******", Password = "******" }, TestServerCallContext.Create()); // Assert Assert.True(resp.Success); Assert.True(resp.Scopes[0].System); }
public async Task OkPostTodoItemTest() { var request = new PostTodoItemRequest { Name = "PostTodoTestName" }; var fakeServerCallContext = TestServerCallContext.Create("fooMethod", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }); var actual = await implement.PostTodoItem(request, fakeServerCallContext); // リクエストで受け取ったNameが設定されている Assert.Equal(request.Name, actual.Todo.Name); // IsCompleteの初期値はfalseである Assert.Equal(false, actual.Todo.IsComplete); // 生成されたTodoがDBに登録されている Assert.Contains(actual.Todo, expectedTodoItems); }
public async Task SearchProductByNameTest() { // Arrange var searchRequest = new SearchRequest { Name = "product", PageIndex = 0, PageSize = 10 }; // Act var response = await catalogService.SearchProductByName(searchRequest, TestServerCallContext.Create()); // Assert Assert.True(response.Count == 3); }