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);
        }
示例#3
0
        public async Task SayHelloUnaryTest()
        {
            // 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);

            // Act
            var response = await service.SayHelloUnary(
                new HelloRequest { Name = "Joe" }, TestServerCallContext.Create());

            // Assert
            mockGreeter.Verify(v => v.Greet("Joe"));
            Assert.Equal("Hello Joe", response.Message);
        }
示例#4
0
        public async Task Dispatch_calls_handlers_RunAsync_and_returns_result()
        {
            // arrange
            var callContext = TestServerCallContext.Create(nameof(Dispatch_calls_handlers_RunAsync_and_returns_result),
                                                           null, DateTime.Now, null, CancellationToken.None, null, null, null, null, null, null);

            A.CallTo(() => _serviceProvider.GetService(typeof(IntStringHandler))).Returns(new IntStringHandler());

            // expected
            const string expected = nameof(Dispatch_calls_handlers_RunAsync_and_returns_result) + " 1234";

            // act
            var result = await _dispatcher.Dispatch <int, string, IntStringHandler>(1234, callContext, "IntString").ConfigureAwait(false);

            // assert
            result.Should().Be(expected);
        }
示例#5
0
        public async Task RunAsync()
        {
            var callContext = TestServerCallContext.Create(
                "",
                "",
                DateTime.MaxValue,
                new Metadata(),
                CancellationToken.None,
                "",
                new AuthContext("", new Dictionary <string, List <AuthProperty> >()),
                null,
                (m) => Task.CompletedTask,
                () => WriteOptions.Default,
                (wo) => { });

            await _publisher.Configure(_configureRequest, callContext);

            await _publisher.ReadStream(_readRequest, new TestServerRecordStreamWriter(), callContext);
        }
示例#6
0
        public async Task StreamingBothWaysTest()
        {
            // init
            var server         = new GreeterService(NullLoggerFactory.Instance);
            var callContext    = TestServerCallContext.Create();
            var requstStream   = new TestAsyncStreamReader <ExampleRequest>(callContext);
            var responseStream = new TestServerStreamWriter <ExampleResponse>(callContext);

            // act
            using var call = server.StreamingBothWays(requstStream, responseStream, callContext);
            requstStream.AddMessage(new ExampleRequest {
                PageIndex = 1, PageSize = 10, IsDescending = false
            });
            Assert.IsTrue((await responseStream.ReadNextAsync()).Age > 1);
            requstStream.Complete();
            await call;

            responseStream.Complete();
            Assert.IsNull(await responseStream.ReadNextAsync());
        }
示例#7
0
        public void Chat_WorldIsSet(int id, string expectedWorldName)
        {
            var testMessage = new ChatMessage
            {
                Author          = "Dummy Author",
                Content         = "dummy text",
                AuthorId        = 0,
                AuthorId2       = 0,
                Avatar          = string.Empty,
                Id              = 0,
                World           = string.Empty,
                WorldId         = id,
                AdditionalFlags = 0,
            };
            var fakeServerCallContext = TestServerCallContext.Create("Chat", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { });
            var fakeReader            = new TestAsyncStreamReader <ChatMessage>(testMessage);
            var fakeWriter            = new TestServerStreamWriter <ChatMessage>();

            _ = _connection.Chat(fakeReader, fakeWriter, fakeServerCallContext);
            fakeWriter.ReturnOnWrite().Wait();
            Assert.AreEqual(testMessage.World, expectedWorldName);
        }
示例#8
0
        public void Chat_InputPassesToOutput()
        {
            var testMessage = new ChatMessage
            {
                Author          = "Dummy Author",
                Content         = "dummy text",
                AuthorId        = 0,
                AuthorId2       = 0,
                Avatar          = string.Empty,
                Id              = 0,
                World           = string.Empty,
                WorldId         = (int)PseudoWorld.Discord,
                AdditionalFlags = 0,
            };
            var fakeServerCallContext = TestServerCallContext.Create("Chat", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { });
            var fakeReader            = new TestAsyncStreamReader <ChatMessage>(testMessage);
            var fakeWriter            = new TestServerStreamWriter <ChatMessage>();

            Task.Run(() => _connection.Chat(fakeReader, fakeWriter, fakeServerCallContext));
            fakeWriter.ReturnOnWrite().Wait(); // Internally, the transmitter calls a callback event which writes to this writer.
            Assert.AreEqual(testMessage, fakeWriter.Current);
        }
示例#9
0
        public async Task SayHelloBidirectionStreamingTest()
        {
            // 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);
            var responseStream = new TestServerStreamWriter <HelloReply>(callContext);

            // Act
            using var call = service.SayHelloBidirectionalStreaming(requestStream, responseStream, callContext);

            // Assert
            requestStream.AddMessage(new HelloRequest {
                Name = "James"
            });
            Assert.Equal("Hello James", (await responseStream.ReadNextAsync()) !.Message);

            requestStream.AddMessage(new HelloRequest {
                Name = "Jo"
            });
            Assert.Equal("Hello Jo", (await responseStream.ReadNextAsync()) !.Message);

            requestStream.AddMessage(new HelloRequest {
                Name = "Lee"
            });
            Assert.Equal("Hello Lee", (await responseStream.ReadNextAsync()) !.Message);

            requestStream.Complete();

            await call;

            responseStream.Complete();

            Assert.Null(await responseStream.ReadNextAsync());
        }
示例#10
0
        public void GetTest()
        {
            var implement = new WeatherImpl(weatherMoq.Object);

            var fakeServerCallContext = TestServerCallContext.Create(
                "fooMethod",
                null,
                DateTime.UtcNow.AddHours(1),
                new Metadata(),
                CancellationToken.None,
                "127.0.0.1",
                null,
                null,
                (metadate) => TaskUtils.CompletedTask,
                () => new WriteOptions(),
                (writeOptions) => { }
                );

            var result = implement.Get(new GetRequest(), fakeServerCallContext);

            Assert.Equal(result.Result.WeatherList, weatherList);
        }
        protected static GrpcCore.ServerCallContext CreateServerCallContext(CancellationToken cancellationToken)
        {
            return(TestServerCallContext.Create("TestMethod",
                                                "host",
                                                DateTime.MaxValue,
                                                new Metadata(),
                                                cancellationToken,
                                                "peer",
                                                null,
                                                null,
                                                null,
                                                null,
                                                null));

            //var constructors = typeof(GrpcCore.ServerCallContext).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);

            //var ctor = constructors.FirstOrDefault(c => c.GetParameters().Any(p => p.ParameterType == typeof(CancellationToken)));
            //Assert.NotNull(ctor);

            //var ctorParams = ctor.GetParameters();

            //object[] ctorArgs = new object[ctorParams.Length];
            //int di = 0;
            //foreach (var param in ctorParams)
            //{
            //    if (param.ParameterType == typeof(CancellationToken))
            //    {
            //        ctorArgs[di] = cancellationToken;
            //    }
            //    else
            //    {
            //        ctorArgs[di] = null;
            //    }
            //    di++;
            //}

            //return (GrpcCore.ServerCallContext)ctor.Invoke(ctorArgs);
        }
示例#12
0
        public void LoginTest()
        {
            var implement = new UserImpl(userRepoMoq.Object);

            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 result = implement.Login(new LoginRequest(), fakeServerCallContext);

            //Assert.IsType<LoginResponse>(result);
            Assert.Equal(result.Result.CityName, actualCityName);
        }
示例#13
0
        public void Initialize()
        {
            _callContext = TestServerCallContext.Create(_guid.ToString(),
                                                        null, DateTime.Now, null, CancellationToken.None, null, null, null, null, null, null);

            _methodOneAttributes = new[]
            {
                new AuthorizeAttribute("my.policy.1")
                {
                    Roles = "my.role.1", AuthenticationSchemes = "my.scheme.1"
                },
                new AuthorizeAttribute("my.policy.2")
                {
                    Roles = "my.role.2", AuthenticationSchemes = "my.scheme.2"
                },
            };

            _methodTwoAttributes = new[]
            {
                new AuthorizeAttribute("my.policy.3")
                {
                    Roles = "my.role.3", AuthenticationSchemes = "my.scheme.3"
                },
                new AuthorizeAttribute("my.policy.4")
                {
                    Roles = "my.role.4", AuthenticationSchemes = "my.scheme.4"
                },
            };

            _handler    = A.Fake <IHandlerStore>();
            _dispatcher = A.Fake <IDispatcher>();

            _config = new MapGrpcServiceConfiguration();

            _compiler = new DispatcherCompiler(_handler, _config);
        }
示例#14
0
        public async Task SayHelloBidirectionStreamingTest()
        {
            // Arrange
            var service = new TesterService(NullLoggerFactory.Instance);

            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());
        }
示例#15
0
        public async Task Connect_Invalid()
        {
            //invalid handshake
            {
                var handshake = new Handshake();
                var metadata  = new Metadata
                {
                    { GrpcConsts.PubkeyMetadataKey, "0454dcd0afc20d015e328666d8d25f3f28b13ccd9744eb6b153e4a69709aab399" }
                };
                var context = BuildServerCallContext(metadata);

                var connectReply = await _service.Connect(handshake, context);

                connectReply.Err.ShouldBe(AuthError.InvalidHandshake);
            }

            //wrong sig
            {
                var handshake = await _peerPool.GetHandshakeAsync();

                handshake.HskData.PublicKey = ByteString.CopyFrom(CryptoHelpers.GenerateKeyPair().PublicKey);
                var metadata = new Metadata
                {
                    { GrpcConsts.PubkeyMetadataKey, "0454dcd0afc20d015e328666d8d25f3f28b13ccd9744eb6b153e4a69709aab399" }
                };
                var context = TestServerCallContext.Create("mock", "127.0.0.1", DateTime.UtcNow.AddHours(1), metadata, CancellationToken.None,
                                                           "ipv4:127.0.0.1:2000", null, null, m => TaskUtils.CompletedTask, () => new WriteOptions(), writeOptions => { });

                var connectReply = await _service.Connect(handshake, context);

                connectReply.Err.ShouldBe(AuthError.WrongSig);
            }

            //invalid peer
            {
                var handshake = await _peerPool.GetHandshakeAsync();

                var metadata = new Metadata
                {
                    { GrpcConsts.PubkeyMetadataKey, "0454dcd0afc20d015e328666d8d25f3f28b13ccd9744eb6b153e4a69709aab399" }
                };
                var context = BuildServerCallContext(metadata);

                var connectReply = await _service.Connect(handshake, context);

                connectReply.Err.ShouldBe(AuthError.InvalidPeer);
            }

            //wrong auth
            {
                var handshake = await _peerPool.GetHandshakeAsync();

                var metadata = new Metadata
                {
                    { GrpcConsts.PubkeyMetadataKey, "0454dcd0afc20d015e328666d8d25f3f28b13ccd9744eb6b153e4a69709aab399" }
                };
                var context = TestServerCallContext.Create("mock", "127.0.0.1", DateTime.UtcNow.AddHours(1), metadata, CancellationToken.None,
                                                           "ipv4:127.0.0.1:2000", null, null, m => TaskUtils.CompletedTask, () => new WriteOptions(), writeOptions => { });

                var connectReply = await _service.Connect(handshake, context);

                connectReply.Err.ShouldBe(AuthError.WrongAuth);
            }
        }
示例#16
0
        public async Task GreeterService_SayHelloUnary_ReturnsCorrectResponse()
        {
            // Arrange
            var service = new GreeterService(new Logger <GreeterService>(new NullLoggerFactory()));

            // Act
            var response = await service.SayHelloUnary(new HelloRequest { Name = "Joe" }, TestServerCallContext.Create());

            // Assert
            Assert.AreEqual("Hello Joe", response.Message);
        }
示例#17
0
        public async Task SearchUser()
        {
            using (var transaction = Fixture.Connection.BeginTransaction())
            {
                using (var context = Fixture.CreateContext(transaction))
                {
                    TypeaheadService typeaheadService = new TypeaheadService(context);

                    SearchUserRequest request = new SearchUserRequest
                    {
                        SearchParameter = "Test User",
                    };

                    SearchUserReply actualReply = await typeaheadService.SearchUser(request, TestServerCallContext.Create("fooMethod", "test.example.com", DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }));

                    Assert.Equal(2, actualReply.Entries.Count);
                }
            }
        }
        public async Task Users_get_informed_if_a_new_character_spawns()
        {
            // Arrange
            var userId  = Guid.NewGuid();
            var userId2 = Guid.NewGuid();

            var mediator = Services.GetService <IMediator>();

            Assert.IsNotNull(mediator);

            var character = await mediator.Send(new CreateCharacterCommand(
                                                    userId,
                                                    "FirstName",
                                                    "LastName",
                                                    SexType.Male));

            var character2 = await mediator.Send(new CreateCharacterCommand(
                                                     userId2,
                                                     "FirstName",
                                                     "LastName",
                                                     SexType.Male));

            await mediator.Send(new SpawnCharacterCommand(character.Id));

            var locationService = new LocationService(Services.GetService <ILogger <LocationService> >(),
                                                      Services.GetService <IMediator>());

            var responseStream  = new Mock <IServerStreamWriter <LocationUpdateResponse> >();
            var locationUpdates = new List <LocationUpdate>();

            responseStream.Setup(r => r.WriteAsync(It.IsAny <LocationUpdateResponse>()))
            .Callback <LocationUpdateResponse>((locationUpdateResponse) =>
            {
                locationUpdates.AddRange(locationUpdateResponse.LocationUpdates);
            });

            var cancellationToken = new CancellationTokenSource();
            var context           = TestServerCallContext.Create(null, null, new DateTime(),
                                                                 null, cancellationToken.Token, null, null,
                                                                 null, null, null, null);
            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(c => c.User)
            .Returns(new ClaimsPrincipal(new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userId.ToString())
            })));
            context.UserState["__HttpContext"] = httpContext.Object;
            _ = locationService.Subscribe(new Empty(), responseStream.Object, context);
            locationUpdates.Clear(); // clear initial updates

            // Act
            await mediator.Send(new SpawnCharacterCommand(character2.Id), cancellationToken.Token);

            cancellationToken.Cancel();

            // Assert
            Assert.IsNotNull(locationUpdates);
            Assert.AreEqual(1, locationUpdates.Count);
            Assert.AreEqual(character2.Id.ToString(), locationUpdates[0].CharacterId);
        }
        public async Task SearchProductByEmptyNameTest()
        {
            // Act
            var response = await catalogService.SearchProductByName(new SearchRequest(), TestServerCallContext.Create());

            // Assert
            Assert.True(response.Count == 0);
            Assert.False(response.Data.Any());
        }
        public async Task GetUserById_WhenUserDoesNotExist_ShouldThrowRpcException()
        {
            // Arrange
            var service = new UserHandlerV1(this._mockLogger.Object);

            string userId  = Guid.NewGuid().ToString();
            var    request = new GetUserByIdRequest
            {
                Uuid = userId
            };

            // Act
            RpcException thrownException = await Assert.ThrowsAsync <RpcException>(() => service.GetUserById(request, TestServerCallContext.Create()));

            // Assert
            thrownException.Status.StatusCode.Should().Be(StatusCode.NotFound);
            thrownException.Status.Detail.Should().Be($"User with id {userId} was not found");
        }
示例#21
0
        public async Task SayHelloTest()
        {
            // arrange
            var service = new GreeterService(NullLoggerFactory.Instance);

            // act
            var response = await service.SayHello(new HelloRequest { Name = "test" }, TestServerCallContext.Create());

            // Assert
            Assert.AreEqual("Hello test", response.Message);
        }
示例#22
0
 public static ServerCallContext Create()
 {
     return(TestServerCallContext.Create("method", "host", DateTime.Now, new Metadata(), default, "peer", null, null, m => Task.CompletedTask, () => default, wo => { }));
示例#23
0
        public async Task SayHelloUnaryTest()
        {
            // Arrange
            var service = new TesterService(NullLoggerFactory.Instance);

            // Act
            var response = await service.SayHelloUnary(new HelloRequest { Name = "Joe" }, TestServerCallContext.Create());

            // Assert
            Assert.AreEqual("Hello Joe", response.Message);
        }
示例#24
0
        public async Task ListUsersAsync()
        {
            var userManagerMock = new Mock <UserManager>((new Mock <IUserStore <AppUser> >()).Object, null, null, null, null, null, null, null, null, null);

            userManagerMock.Setup(m => m.GetAllUsers()).Returns(new List <AppUser> {
                new AppUser {
                    Id = new Guid("68cfbe00-8e8d-4015-8bb5-6ce82ff4d64d"), UserName = "******"
                },
                new AppUser {
                    Id = new Guid("917cf76f-a076-4cd0-93ef-6c26025f21c0"), UserName = "******"
                }
            });

            UsersService  service     = new UsersService(userManagerMock.Object);
            UserListReply actualReply = await service.ListUsers(new Google.Protobuf.WellKnownTypes.Empty(), TestServerCallContext.Create("fooMethod", null, DateTime.UtcNow.AddHours(1), new Metadata(), CancellationToken.None, "127.0.0.1", null, null, (metadata) => TaskUtils.CompletedTask, () => new WriteOptions(), (writeOptions) => { }));

            UserListReply expectedReply = new UserListReply();

            expectedReply.Users.Add(new User {
                Id = "68cfbe00-8e8d-4015-8bb5-6ce82ff4d64d", Name = "User 1"
            });
            expectedReply.Users.Add(new User {
                Id = "917cf76f-a076-4cd0-93ef-6c26025f21c0", Name = "User 2"
            });

            Assert.Equal(expectedReply, actualReply);
        }
示例#25
0
 private ServerCallContext BuildServerCallContext(Metadata metadata = null, string address = null)
 {
     return(TestServerCallContext.Create("mock", null, TimestampHelper.GetUtcNow().AddHours(1).ToDateTime(), metadata ?? new Metadata(), CancellationToken.None,
                                         address ?? "ipv4:127.0.0.1:5555", null, null, m => TaskUtils.CompletedTask, () => new WriteOptions(), writeOptions => { }));
 }
示例#26
0
        public async Task SayHelloUnaryTest()
        {
            // Arrange
            var mockGreeter = CreateGreeterMock();
            var service     = new TesterService(mockGreeter.Object);

            // Act
            var response = await service.SayHelloUnary(new HelloRequest { Name = "Joe" }, TestServerCallContext.Create());

            // Assert
            mockGreeter.Verify(v => v.Greet("Joe"));
            Assert.AreEqual("Hello Joe", response.Message);
        }