public TestResponse Respond(string userId, int surveyId, string response, int pageId) { var currentTest = Tests.SingleOrDefault(t => t.UserId.Equals(userId, StringComparison.OrdinalIgnoreCase) && surveyId == t.SurveyId) ?? throw new TestNotFoundException(userId, surveyId); var currentPage = Pages.Find(pageId) ?? throw new PageNotFoundException(pageId); var testResponse = TestResponses.SingleOrDefault(tr => tr.TestId == currentTest.Id && tr.PageId == pageId); var responseExpected = currentPage.GetType().IsAssignableFrom(typeof(IQuestion)); if (testResponse == null) { testResponse = new TestResponse { TestId = currentTest.Id, PageId = pageId, Response = response, Created = DateTime.UtcNow, Responded = responseExpected && string.IsNullOrWhiteSpace(response) ? (DateTime?)null : DateTime.UtcNow }; TestResponses.Add(testResponse); } else { testResponse.Response = response; testResponse.Modified = DateTime.UtcNow; testResponse.Responded = DateTime.UtcNow; } _dbContext.SaveChangesAsync(); return(testResponse); }
public async Task TryGetConnectionIdIsUsedToExtractConnectionIdFromToken() { var manager = new TestTransportManager(); var connection = new TokenValidatingPersistentConnection(); var req = new TestRequest(); var resp = new TestResponse(); req.QueryString["connectionToken"] = TokenValidatingPersistentConnection.ExpectedConnectionToken; req.QueryString["transport"] = TestTransportManager.TestTransportName; req.LocalPath = "/connect"; var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(ITransportManager), () => manager); // Initialize the connection connection.Initialize(resolver); // Run the request var context = new HostContext(req, resp); await connection.ProcessRequest(context); // Check the connection ID and that the transport was called Assert.Equal(TokenValidatingPersistentConnection.ExpectedConnectionId, manager.TestTransport.ConnectionId); Assert.Equal(1, manager.TestTransport.ProcessRequestCalls); }
public async Task TryGetConnectionIdReturningFalseCausesResponseToEndWithProvidedMessageAndStatusCode() { var manager = new TestTransportManager(); var connection = new TokenValidatingPersistentConnection(); var req = new TestRequest(); var resp = new TestResponse(); req.QueryString["connectionToken"] = "wrongToken"; req.QueryString["transport"] = TestTransportManager.TestTransportName; req.LocalPath = "/connect"; var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(ITransportManager), () => manager); // Initialize the connection connection.Initialize(resolver); // Run the request var context = new HostContext(req, resp); await connection.ProcessRequest(context); // Check the connection ID wasn't set and ProcessRequest wasn't called on the transport. Assert.Null(manager.TestTransport.ConnectionId); Assert.Equal(0, manager.TestTransport.ProcessRequestCalls); // Check the response Assert.Equal(TokenValidatingPersistentConnection.ExpectedErrorStatusCode, resp.StatusCode); Assert.Equal(TokenValidatingPersistentConnection.ExpectedErrorMessage, resp.GetBodyAsString()); }
private bool SubmitAllTests(string testId, TestRequestParameter testRequest) { var url = testRequest.Url; //add http protocol if protocol is missing if (!testRequest.Url.StartsWith("http")) { url = $"http://{testRequest.Url}"; } _testResponse = new TestResponse(); _testResponse.TestId = testId; _testResponse.Url = testRequest.Url; try { GetPageStats(testId, url); GetPageScreenshot(testId, url); _testResponse.Success = true; _testResponse.TestCompelted = true; _testResponse.TestStatus = "Completed"; _testResponse.HttpStatusCode = HttpStatusCode.OK; } catch (Exception ex) // if an error occurs return false { _testResponse.Success = false; _testResponse.TestCompelted = false; _testResponse.TestStatus = "Error while processing."; _testResponse.HttpStatusCode = HttpStatusCode.OK; } return(true); }
public async Task Should_send_Rpc_and_receive_response() { IServiceLocator serviceLocator = TestRig.CreateTestServiceLocator(); var config = new ConnectionConfig(TestRig.AuthKey, 100500) {SessionId = 2}; var messageProcessor = serviceLocator.ResolveType<IMessageCodec>(); var request = new TestRequest {TestId = 9}; var expectedResponse = new TestResponse {TestId = 9, TestText = "Number 1"}; var rpcResult = new RpcResult {ReqMsgId = TestMessageIdsGenerator.MessageIds[0], Result = expectedResponse}; byte[] expectedResponseMessageBytes = messageProcessor.EncodeEncryptedMessage( new Message(0x0102030405060708, 3, rpcResult), config.AuthKey, config.Salt, config.SessionId, Sender.Server); SetupMockTransportWhichReturnsBytes(serviceLocator, expectedResponseMessageBytes); using (var connection = serviceLocator.ResolveType<IMTProtoClientConnection>()) { connection.Configure(config); await connection.Connect(); TestResponse response = await connection.RpcAsync<TestResponse>(request); response.Should().NotBeNull(); response.Should().Be(expectedResponse); await connection.Disconnect(); } }
public async Task Should_send_encrypted_message_and_wait_for_response() { IServiceLocator serviceLocator = TestRig.CreateTestServiceLocator(); var config = new ConnectionConfig(TestRig.AuthKey, 100500) {SessionId = 2}; var messageProcessor = serviceLocator.ResolveType<IMessageCodec>(); var request = new TestRequest {TestId = 9}; var expectedResponse = new TestResponse {TestId = 9, TestText = "Number 1"}; byte[] expectedResponseMessageBytes = messageProcessor.EncodeEncryptedMessage( new Message(0x0102030405060708, 3, expectedResponse), config.AuthKey, config.Salt, config.SessionId, Sender.Server); SetupMockTransportWhichReturnsBytes(serviceLocator, expectedResponseMessageBytes); using (var connection = serviceLocator.ResolveType<IMTProtoClientConnection>()) { connection.Configure(config); await connection.Connect(); TestResponse response = await connection.RequestAsync<TestResponse>(request, MessageSendingFlags.EncryptedAndContentRelated, TimeSpan.FromSeconds(5)); response.Should().NotBeNull(); response.Should().Be(expectedResponse); await connection.Disconnect(); } }
public void TestJsonRequestCall() { var route = "route"; var expectedRes = new TestResponse { Attr = "wololo", List = new List <float> { 14.3f, 11.0f, 65.4f } }; var mockBinding = Substitute.For <IPitayaBinding>(); var res = Newtonsoft.Json.JsonConvert.SerializeObject(expectedRes); var client = new PitayaClient(binding: mockBinding, queueDispatcher: new NullPitayaQueueDispatcher()); mockBinding.When(x => x.Request(Arg.Any <IntPtr>(), route, Arg.Any <byte[]>(), Arg.Any <uint>(), Arg.Any <int>())).Do(x => { client.OnRequestResponse(1, Encoding.UTF8.GetBytes(res)); }); var completionSource = new TaskCompletionSource <(TestResponse, PitayaError)>(); client.Request <TestResponse>(route, new TestRequest(), (TestResponse response) => { completionSource.TrySetResult((response, null)); }, (PitayaError error) => { completionSource.TrySetResult((null, error)); });
public void MicroServiceResponseCorrelatesToRequest() { var options = new BusOptions() { QueueName = "CallbackTest02" }; var serviceMock = new CallbackMock(); using (var host = new MicroserviceHost <CallbackMock>(serviceMock, options)) using (var proxy = new MicroserviceProxy(options)) { host.Open(); RequestCommand requestCommand = new RequestCommand { Name = "Marco" }; SlowRequestCommand slowCommand = new SlowRequestCommand { Name = "Slow" }; TestResponse slowResponse = proxy.Execute <TestResponse>(slowCommand); TestResponse response = proxy.Execute <TestResponse>(requestCommand); Assert.Equal("Hello, Marco", response.Greeting); Assert.Equal("Hello, Slow", slowResponse.Greeting); } }
public async Task Then_the_response_is_returned( int id, TestCustomerEngagementApiConfiguration config, TestResponse expectedResponse) { //Arrange config.Url = "https://test.local"; var httpResponse = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(expectedResponse), Encoding.UTF8, "application/json"), StatusCode = HttpStatusCode.OK }; var getTestRequest = new GetTestRequest(config.Url, id) { BaseUrl = config.Url }; var httpMessageHandler = MessageHandler.SetupMessageHandlerMock(httpResponse, getTestRequest.GetUrl); var client = new HttpClient(httpMessageHandler.Object); var hostingEnvironment = new Mock <IWebHostEnvironment>(); var clientFactory = new Mock <IHttpClientFactory>(); clientFactory.Setup(_ => _.CreateClient(It.IsAny <string>())).Returns(client); hostingEnvironment.Setup(x => x.EnvironmentName).Returns("Staging"); var actual = new CustomerEngagementApiClient <TestCustomerEngagementApiConfiguration>(clientFactory.Object, config, hostingEnvironment.Object); //Act var response = await actual.Get <TestResponse>(getTestRequest); //Assert response.Should().BeEquivalentTo(expectedResponse); }
private async Task <TestResponse> GetFromHttp(long?from = null, long?to = null) { var request = new HttpRequestMessage(HttpMethod.Get, videoPath); if (from.HasValue || to.HasValue) { request.Headers.Range = new RangeHeaderValue(from, to); } var response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { var videoStream = await response.Content.ReadAsStreamAsync(); var ms = new MemoryStream(); videoStream.CopyTo(ms); var result = new TestResponse() { StatusCode = response.StatusCode, Length = response.Content.Headers.ContentLength ?? 0, Bytes = ms.ToArray() }; response.Dispose(); return(result); } return(null); }
public IActionResult Index1() { TestResponse <string> testResponse = new TestResponse <string>(); testResponse.Data = "Athar Imam1"; return(new OkObjectResult(testResponse)); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return(null); } else if (reader.TokenType == JsonToken.StartArray) { // A valid response. Populare the Tests array. var tests = serializer.Deserialize <Test[]>(reader); return(new TestResponse { Tests = tests }); } else if (reader.TokenType == JsonToken.StartObject) { // An error response. Populate HasError and Message var response = new TestResponse(); serializer.Populate(reader, response); return(response); } else { throw new JsonSerializationException("Unexpected reader.TokenType: " + reader.TokenType); } }
public void ValidateTest() { var response = new TestResponse(); var e = new ExecutionResult(); e.Status = ExecuteStatus.Failed; e.ExecuteMessages.Add(new ExecutionMessage { Help = "Test Help", Text = "Test Fail", Id = 1, Type = ExecutionMessageType.Error }); response.ExecutionResult = e; try { ServiceExtension.Validate(response); } catch (ServiceValidationException ex) { Assert.IsNotNull(ex); Assert.IsFalse(string.IsNullOrEmpty(ex.Message)); Assert.AreEqual("Test Fail", ex.Message); Assert.IsNotNull(ex.Errors); return; } Assert.Fail(); }
public async Task Should_Amend_Matched_Values_With_Fiddled_Response() { var chaosSettings = new ChaosSettings(); chaosSettings.ResponseFiddles.Add(new ResponseFiddle { Match = "http://some-endpoint.com", ReplaceMatchingWith = "Fiddled!" }); var responseObject = new TestResponse { AnotherField = "This-should-be-left-alone", Resource = "http://some-endpoint.com" }; var responseMessage = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(JsonConvert.SerializeObject(responseObject)), RequestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri("http://some-api-call.com")) }; var result = await _responseFiddler.Fiddle(responseMessage, chaosSettings); var resultContent = await result.Content.ReadAsStringAsync(); var deserialisedResponse = JsonConvert.DeserializeObject <TestResponse>(resultContent); deserialisedResponse.Resource.Should().Be("Fiddled!"); }
public void Should_get_first_or_default(bool includeRpc) { var response = new TestResponse {TestId = 1, TestText = "Test text."}; var exReqMock = new Mock<IRequest>(); exReqMock.Setup(r => r.CanSetResponse(It.IsAny<object>())).Returns((object o) => o is TestResponse); exReqMock.Setup(r => r.Message.MsgId).Returns(0x100500); exReqMock.Setup(r => r.Flags).Returns(MessageSendingFlags.EncryptedAndContentRelatedRPC); var exReq = exReqMock.Object; var requestsManager = new RequestsManager(); requestsManager.Add(exReq); IRequest request = requestsManager.GetFirstOrDefault(response, includeRpc); if (includeRpc) { request.Should().NotBeNull(); request.Should().BeSameAs(exReq); } else { request.Should().BeNull(); } }
public void Deserialize_UsesJsonProperties_True() { // Arrange var testResponse = new TestResponse() { id_str = "123", created_at = "Sun Dec 16 20:56:33 +0000 2018", full_text = "Wello Horld! http://www.Steve.com", truncated = false, }; var serializer = new LambdaRestSerializer(); var stream = new MemoryStream(); TwitterResponse result = null; // Act serializer.Serialize <TestResponse>(testResponse, stream); stream.Position = 0; result = serializer.Deserialize <TwitterResponse>(stream); // Assert Assert.Equal(result.UID, testResponse.id_str); Assert.Equal(result.CreatedAt, new DateTimeOffset(2018, 12, 16, 20, 56, 33, new TimeSpan(0))); Assert.Equal(result.FullText, testResponse.full_text); Assert.Equal(result.Truncated, testResponse.truncated); }
public override TestResponse VerifyFirstStep(List <CreditCardTransactionData> creditCardTransactionDataCollection, TestRequest testRequest) { TestResponse response = new TestResponse(); CreditCardTransactionData creditCardTransactionData = creditCardTransactionDataCollection.LastOrDefault(); if (testRequest.TransactionReference != creditCardTransactionData.TransactionReference) { AddErrorReport(this.ErrorReportColllection, "TransactionReference", "TransactionReference está errado."); } else if (testRequest.AmountInCents != creditCardTransactionData.AmountInCents.ToString()) { AddErrorReport(this.ErrorReportColllection, "AmountInCents", "AmountInCents está errado."); } else if (testRequest.CreditCardTransactionStatusEnum != creditCardTransactionData.CreditCardTransactionStatusEnum) { AddErrorReport(this.ErrorReportColllection, "CreditCardTransactionStatusEnum", "CreditCardTransactionStatusEnum errado."); } if (this.ErrorReportColllection.Any() == true) { response.Success = false; } else { response.Success = true; } response.ErrorReportCollection = this.ErrorReportColllection; return(response); }
protected override void Given() { this.testResponse = new TestResponse(); this.pipelineContext = new PipelineContext(new TestRequest(), this.testResponse); this.subject = new JsonResultExecutor(new NoopTempDataMechanism()); this.result = new JsonResult(new { foo = "bar" }); }
public TestResponse TestProcessor(TestRequest testRequest) { ITest test = IocFactory.ResolveByName <ITest>(testRequest.TestId); TestResponse response = new TestResponse(); return(test.Execute(testRequest)); }
protected override void Given() { this.testResponse = new TestResponse(); this.pipelineContext = new PipelineContext(new TestRequest(), this.testResponse); this.subject = new JsonResultExecutor(new NoopTempDataMechanism()); this.json = "{ \"json\": \"i am\" }"; this.result = new JsonResult(this.json); }
public IHttpActionResult Get(string id, string text) { var dateList = new List <DateTime>(); var response = new TestResponse(ResultEnum.OperationSucces, dateList); return(Ok(response)); }
public static TestResponse WriteToDb(HSEContestDbContext _db, TestingResult res, bool recheck) { bool ok = false; if (recheck) { var existing = _db.TestingResults.FirstOrDefault(r => r.SolutionId == res.SolutionId && r.TestId == res.TestId); if (existing != null) { existing.Commentary = res.Commentary; existing.ResultCode = res.ResultCode; existing.Score = res.Score; existing.TestData = res.TestData; _db.SaveChanges(); ok = true; } } else { var x = _db.TestingResults.Add(res); var beforeState = x.State; int r = _db.SaveChanges(); var afterState = x.State; ok = beforeState == EntityState.Added && afterState == EntityState.Unchanged && r == 1; } TestResponse response; if (ok) { response = new TestResponse { OK = true, Message = "success", Result = res.ResultCode, Score = res.Score, TestResultId = res.Id, TestId = res.TestId, }; } else { response = new TestResponse { OK = false, Message = "can't write result to db", Result = ResultCode.IE, Score = res.Score, TestId = res.TestId, }; } return(response); }
public async Task Test_test_success() { TestResponse testresponse = await deribit.Supporting.Test(new TestRequest() { expected_result = null, }); Assert.That(testresponse.version, Is.Not.Null); }
public override Task <TestResponse> Test(TestRequest request, ServerCallContext context) { var response = new TestResponse { Message = $"{request.Message}_tested" }; return(Task.FromResult(response)); }
public override async Task <TestResponse> TestWithEmpty(EmptyMsg request, ServerCallContext context) { var returnMsg = new TestResponse { Values = { 1, 2, 3, 4 } }; return(returnMsg); }
public void Request() { var response = new TestResponse(); var client = TestHttpClient.CreateSuccessClientWithResponse("api/services/test", JsonConvert.SerializeObject(response)); var syncResult = client.Request <TestRequest, TestResponse>(new TestRequest(), "test"); syncResult.Should().BeEquivalentTo(response); }
public override async Task <TestResponse> Hello(TestRequest request, ServerCallContext context) { TestResponse response = new TestResponse() { Message = await mediator.Send <string>(request) }; return(response); }
public void Should_be_able_to_send_and_receive_via_rpc() { TestRequest request = new TestRequest(); TestResponse response = _rpcBus.GetResponseTo <TestResponse>(request, TimeSpan.FromSeconds(5)); Assert.That(response, Is.Not.Null, "RPC Response not received within timeout period."); Assert.That(response.Id, Is.EqualTo(request.Id), "The RPC Response did not match the request."); }
public async Task Test_test_error() { Assert.ThrowsAsync <RemoteInvocationException>(async() => { TestResponse testresponse = await deribit.Supporting.Test(new TestRequest() { expected_result = "exception", }); }); }
public TestResponse DoSomething(TestRequest request) { TestResponse response = new TestResponse() { Request = request , Information = string.Format("Request received to do something at [{0}] in class [{1}]", DateTime.UtcNow.ToString(), typeof(TestReference).FullName) }; return(response); }
public static TestResponse Unmarshall(UnmarshallerContext context) { TestResponse testResponse = new TestResponse(); testResponse.HttpResponse = context.HttpResponse; testResponse.RequestId = context.StringValue("Test.RequestId"); testResponse.ResponseId = context.StringValue("Test.ResponseId"); testResponse.Message = context.StringValue("Test.Message"); return(testResponse); }
public void UT_When_HandleMove_Then_Success() { var sessionName = "player1-vs-player2"; var player1 = new TestSessionPlayer() { SessionName = sessionName, PendingToMove = false, Information = new User { DisplayName = "Player 1", Name = "player1" } }; var player2 = new TestSessionPlayer() { SessionName = sessionName, PendingToMove = true, Information = new User { DisplayName = "Player 2", Name = "player2" } }; var session = new GameSession(player1, player2); var testMoveObject = new TestMoveObject { Answer = "Test Answer" }; var testMove = new TestMove(testMoveObject); var moveResponse = new TestResponse(new TestResponseObject { IsCorrect = true }) { IsWin = false }; var sessionServiceMock = new Mock<ISessionService>(); sessionServiceMock .Setup(s => s.GetByName(It.Is<string>(x => x == sessionName))) .Returns(session) .Verifiable(); var moveProcessorMock = new Mock<IMoveProcessor<TestMoveObject, TestResponseObject>>(); moveProcessorMock .Setup(p => p.Process(It.Is<SessionGamePlayer>(x => x == player2), It.Is<IGameMove<TestMoveObject>>(m => m == testMove))) .Returns(moveResponse) .Verifiable(); this.moveService = new MoveService<TestMoveObject, TestResponseObject>(sessionServiceMock.Object, moveProcessorMock.Object); var response = this.moveService.Handle(sessionName, player1.Information.Name, testMove); sessionServiceMock.VerifyAll(); moveProcessorMock.VerifyAll(); Assert.IsNotNull(response); Assert.AreEqual(moveResponse, response); }
TestResponse WriteTestResponseToDb(TestResponse resp, int solutionId, int testId) { var testResult = _db.TestingResults.FirstOrDefault(t => t.SolutionId == solutionId && t.TestId == testId); if (testResult is null) { var res = new TestingResult { Score = resp.Score, Commentary = resp.Message, SolutionId = solutionId, TestId = testId, ResultCode = resp.Result, }; var x = _db.TestingResults.Add(res); var beforeState = x.State; int r = _db.SaveChanges(); var afterState = x.State; bool ok = beforeState == EntityState.Added && afterState == EntityState.Unchanged && r == 1; TestResponse response; if (ok) { response = new TestResponse { OK = true, Message = "success", Result = ResultCode.OK, Score = res.Score, TestResultId = res.Id, TestId = testId, }; } else { response = new TestResponse { OK = false, Message = "can't write result to db", Result = ResultCode.IE, Score = res.Score, TestId = testId, }; } return response; } else { return resp; } }
public void GetRetryAfterReturnsDefaultValueIfResponseKeyDoesNotExist() { // given var target = new TestResponse(mockLogger, 429, new Dictionary <string, List <string> >()); // when var obtained = target.GetRetryAfterInMilliseconds(); // then Assert.That(obtained, Is.EqualTo(Response.DefaultRetryAfterInMilliseconds)); }
public async Task Should_set_response_to_request() { var request = new Mock<IRequest>(); request.SetupGet(request1 => request1.Message).Returns(() => new Message(1, 1, new TestRequest {TestId = 1})); var response = new TestResponse {TestId = 1, TestText = "Simple test text."}; var responseMessage = new Message(1, 1, response); var requestsManager = new Mock<IRequestsManager>(); requestsManager.Setup(manager => manager.GetFirstOrDefault(response, It.IsAny<bool>())).Returns(request.Object).Verifiable(); var handler = new FirstRequestResponseHandler(requestsManager.Object); await handler.HandleAsync(responseMessage); requestsManager.Verify(); request.Verify(request1 => request1.SetResponse(response), Times.Once()); }
public void UT_When_HandleWinnerGameMove_Then_Success() { var testMoveObject = new TestMoveObject { Answer = "Test Answer" }; var testMove = new TestMove(testMoveObject); var moveResponse = new TestResponse(new TestResponseObject { IsCorrect = true }) { IsWin = true }; var moveResultNotificationObject = Mock.Of<IMoveResultReceivedServerMessage>(o => o.SessionName == this.sessionName && o.PlayerName == this.requestPlayer); this.sessionServiceMock .Setup(s => s.GetByName(It.Is<string>(x => x == this.session.Name))) .Returns(this.session) .Verifiable(); this.moveFactoryMock .Setup(f => f.Create(It.Is<string>(s => s == this.moveInformation))) .Returns(testMove) .Verifiable(); this.moveServiceMock .Setup(s => s.Handle(It.Is<string>(x => x == this.session.Name), It.Is<string>(x => x == this.requestPlayer), It.Is<IGameMove<TestMoveObject>>(m => m == testMove))) .Returns(moveResponse) .Verifiable(); this.sessionHistoryServiceMock .Setup(x => x.Add(It.Is<string>(s => s == this.sessionName), It.Is<string>(s => s == this.requestPlayer), It.Is<ISessionHistoryItem<TestMoveObject, TestResponseObject>>(i => i.Move == testMove.MoveObject && i.Response == moveResponse.MoveResponseObject))) .Verifiable(); this.sessionServiceMock .Setup(s => s.Finish(It.Is<string>(x => x == this.sessionName))) .Verifiable(); var gameProgressPluginComponent = this.GetGameProgressPluginComponent(); var gameMoveRequest = new SendMoveClientMessage { SessionName = this.sessionName, UserName = this.requestPlayer, MoveInformation = "Test" }; var clientContract = new ClientContract { Type = GamifyClientMessageType.SendMove, Sender = this.requestPlayer, SerializedClientMessage = this.serializer.Serialize(gameMoveRequest) }; var canHandle = gameProgressPluginComponent.CanHandleClientMessage(clientContract); gameProgressPluginComponent.HandleClientMessage(clientContract); this.moveServiceMock.VerifyAll(); this.sessionServiceMock.VerifyAll(); this.sessionHistoryServiceMock.VerifyAll(); this.moveFactoryMock.VerifyAll(); this.notificationServiceMock.Verify(s => s.SendBroadcast(It.Is<int>(t => t == GamifyServerMessageType.GameFinished), It.Is<object>(o => ((GameFinishedServerMessage)o).SessionName == this.session.Name && ((GameFinishedServerMessage)o).WinnerPlayerName == this.requestPlayer), It.Is<string>(x => x == this.session.Player2Name), It.Is<string>(x => x == this.session.Player1Name))); Assert.IsTrue(canHandle); }
public async Task Should_send_plain_message_and_wait_for_response() { IServiceLocator serviceLocator = TestRig.CreateTestServiceLocator(); var messageProcessor = serviceLocator.ResolveType<IMessageCodec>(); var request = new TestRequest {TestId = 9}; var expectedResponse = new TestResponse {TestId = 9, TestText = "Number 1"}; var expectedResponseMessage = new Message(0x0102030405060708, 0, expectedResponse); byte[] expectedResponseMessageBytes = messageProcessor.EncodePlainMessage(expectedResponseMessage); SetupMockTransportWhichReturnsBytes(serviceLocator, expectedResponseMessageBytes); using (var connection = serviceLocator.ResolveType<IMTProtoClientConnection>()) { await connection.Connect(); // Testing sending a plain message. TestResponse response = await connection.RequestAsync<TestResponse>(request, MessageSendingFlags.None, TimeSpan.FromSeconds(5)); response.Should().NotBeNull(); response.Should().Be(expectedResponse); await connection.Disconnect(); } }
public void When_a_query_is_sent() { var request = new TestRequest {CorrelationTag = "this is a query"}; _response = Bus.Send (request); }