public async Task MessageActivityWithHttpClient() { // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); var httpResponseMock = new Mock <HttpResponse>(); var mockHttpMessageHandler = new Mock <HttpMessageHandler>(); mockHttpMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(CreateInternalHttpResponse())); var httpClient = new HttpClient(mockHttpMessageHandler.Object); var bot = new MessageBot(); // Act var cloudEnvironment = BotFrameworkAuthenticationFactory.Create(null, false, null, null, null, null, null, null, null, new PasswordServiceClientCredentialFactory(), new AuthenticationConfiguration(), httpClient, null); var adapter = new CloudAdapter(cloudEnvironment); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot); // Assert mockHttpMessageHandler.Protected().Verify <Task <HttpResponseMessage> >("SendAsync", Times.Once(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); }
public async Task InvokeActivity() { // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Body).Returns(CreateInvokeActivityStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); var response = new MemoryStream(); var httpResponseMock = new Mock <HttpResponse>(); httpResponseMock.Setup(r => r.Body).Returns(response); var bot = new InvokeResponseBot(); // Act var adapter = new CloudAdapter(); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot); // Assert using (var stream = new MemoryStream(response.GetBuffer())) using (var reader = new StreamReader(stream)) { var s = reader.ReadToEnd(); var json = JObject.Parse(s); Assert.Equal("im.feeling.really.attacked.right.now", json["quite.honestly"]); } }
public async Task BasicMessageActivity() { // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); var httpResponseMock = new Mock <HttpResponse>(); var botMock = new Mock <IBot>(); botMock.Setup(b => b.OnTurnAsync(It.IsAny <TurnContext>(), It.IsAny <CancellationToken>())).Returns(Task.CompletedTask); // Act var adapter = new CloudAdapter(); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, botMock.Object); // Assert botMock.Verify(m => m.OnTurnAsync(It.Is <TurnContext>(tc => true), It.Is <CancellationToken>(ct => true)), Times.Once()); }
public async Task BadRequest() { // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Method).Returns(HttpMethods.Post); httpRequestMock.Setup(r => r.Body).Returns(CreateBadRequestStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); var httpResponseMock = new Mock <HttpResponse>(); httpResponseMock.SetupProperty(x => x.StatusCode); var botMock = new Mock <IBot>(); botMock.Setup(b => b.OnTurnAsync(It.IsAny <TurnContext>(), It.IsAny <CancellationToken>())).Returns(Task.CompletedTask); // Act var adapter = new CloudAdapter(); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, botMock.Object); // Assert botMock.Verify(m => m.OnTurnAsync(It.Is <TurnContext>(tc => true), It.Is <CancellationToken>(ct => true)), Times.Never()); Assert.Equal((int)HttpStatusCode.BadRequest, httpResponseMock.Object.StatusCode); }
public void NamedPipeActivityTest() { const string pipeName = "test.pipe"; var logger = XUnitLogger.CreateLogger(_testOutput); // Arrange var activity = new Activity { Id = Guid.NewGuid().ToString("N"), Type = ActivityTypes.Message, From = new ChannelAccount { Id = "testUser" }, Conversation = new ConversationAccount { Id = Guid.NewGuid().ToString("N") }, Recipient = new ChannelAccount { Id = "testBot" }, ServiceUrl = "unknown", ChannelId = "test", Text = "hi" }; var bot = new StreamingTestBot((turnContext, cancellationToken) => { var activityClone = JsonConvert.DeserializeObject <Activity>(JsonConvert.SerializeObject(turnContext.Activity)); activityClone.Text = $"Echo: {turnContext.Activity.Text}"; return(turnContext.SendActivityAsync(activityClone, cancellationToken)); }); var verifiedResponse = false; var clientRequestHandler = new Mock <RequestHandler>(); clientRequestHandler .Setup(h => h.ProcessRequestAsync(It.IsAny <ReceiveRequest>(), It.IsAny <ILogger <RequestHandler> >(), It.IsAny <object>(), It.IsAny <CancellationToken>())) .Returns <ReceiveRequest, ILogger <RequestHandler>, object, CancellationToken>((request, anonLogger, context, cancellationToken) => { var body = request.ReadBodyAsString(); var response = JsonConvert.DeserializeObject <Activity>(body, SerializationSettings.DefaultDeserializationSettings); Assert.NotNull(response); Assert.Equal("Echo: hi", response.Text); verifiedResponse = true; return(Task.FromResult(StreamingResponse.OK())); }); // Act var server = new CloudAdapter(new StreamingTestBotFrameworkAuthentication(), logger); var serverRunning = server.ConnectNamedPipeAsync(pipeName, bot, "testAppId", "testAudience", "testCallerId"); var client = new NamedPipeClient(pipeName, ".", clientRequestHandler.Object, logger: logger); var clientRunning = client.ConnectAsync(); SimulateMultiTurnConversation(1, new[] { activity }, client, logger); // Assert Assert.True(verifiedResponse); }
private void RunStreamingCrashTest(Action <WebSocket, TestWebSocketConnectionFeature.WebSocketChannel, WebSocketClient, CancellationTokenSource, CancellationTokenSource> induceCrash) { var logger = XUnitLogger.CreateLogger(_testOutput); var serverCts = new CancellationTokenSource(); var clientCts = new CancellationTokenSource(); using (var connection = new TestWebSocketConnectionFeature()) { var webSocket = connection.AcceptAsync().Result; var clientWebSocket = connection.Client; var bot = new StreamingTestBot((turnContext, cancellationToken) => Task.CompletedTask); var server = new CloudAdapter(new StreamingTestBotFrameworkAuthentication(), logger); var serverRunning = server.ProcessAsync(CreateWebSocketUpgradeRequest(webSocket), new Mock <HttpResponse>().Object, bot, serverCts.Token); var clientRequestHandler = new Mock <RequestHandler>(); clientRequestHandler .Setup(h => h.ProcessRequestAsync(It.IsAny <ReceiveRequest>(), It.IsAny <ILogger <RequestHandler> >(), It.IsAny <object>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(StreamingResponse.OK())); using (var client = new WebSocketClient("wss://test", clientRequestHandler.Object, logger: logger)) { var clientRunning = client.ConnectInternalAsync(clientWebSocket, clientCts.Token); var activity = new Activity { Id = Guid.NewGuid().ToString("N"), Type = ActivityTypes.Message, From = new ChannelAccount { Id = "testUser" }, Conversation = new ConversationAccount { Id = Guid.NewGuid().ToString("N") }, Recipient = new ChannelAccount { Id = "testBot" }, ServiceUrl = "wss://InvalidServiceUrl/api/messages", ChannelId = "test", Text = "hi" }; var content = new StringContent(JsonConvert.SerializeObject(activity), Encoding.UTF8, "application/json"); var response = client.SendAsync(StreamingRequest.CreatePost("/api/messages", content)).Result; Assert.Equal(200, response.StatusCode); induceCrash(webSocket, clientWebSocket, client, serverCts, clientCts); clientRunning.Wait(); Assert.True(clientRunning.IsCompletedSuccessfully); } serverRunning.Wait(); Assert.True(serverRunning.IsCompletedSuccessfully); } }
public async Task WebSocketRequestShouldCallAuthenticateStreamingRequestAsync() { // Note this test only checks that a GET request will result in an auth call and a socket accept // it doesn't valid that activities over that socket get to the bot or back // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var webSocketReceiveResult = new Mock <WebSocketReceiveResult>(MockBehavior.Strict, new object[] { 1, WebSocketMessageType.Binary, false }); var webSocketMock = new Mock <WebSocket>(); webSocketMock.Setup(ws => ws.State).Returns(WebSocketState.Open); webSocketMock.Setup(ws => ws.ReceiveAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(webSocketReceiveResult.Object)); webSocketMock.Setup(ws => ws.SendAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <WebSocketMessageType>(), It.IsAny <bool>(), It.IsAny <CancellationToken>())).Returns(Task.CompletedTask); webSocketMock.Setup(ws => ws.CloseAsync(It.IsAny <WebSocketCloseStatus>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.CompletedTask); webSocketMock.Setup(ws => ws.Dispose()); var webSocketManagerMock = new Mock <WebSocketManager>(); webSocketManagerMock.Setup(w => w.IsWebSocketRequest).Returns(true); webSocketManagerMock.Setup(w => w.AcceptWebSocketAsync()).Returns(Task.FromResult(webSocketMock.Object)); var httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(c => c.WebSockets).Returns(webSocketManagerMock.Object); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Method).Returns("GET"); httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); httpRequestMock.Setup(r => r.HttpContext).Returns(httpContextMock.Object); var httpResponseMock = new Mock <HttpResponse>().SetupAllProperties(); var authenticateRequestResult = new AuthenticateRequestResult { Audience = "audience", }; var botFrameworkAuthenticationMock = new Mock <BotFrameworkAuthentication>(); botFrameworkAuthenticationMock.Setup( x => x.AuthenticateStreamingRequestAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(authenticateRequestResult); var bot = new MessageBot(); // Act var adapter = new CloudAdapter(botFrameworkAuthenticationMock.Object); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot); // Assert botFrameworkAuthenticationMock.Verify(x => x.AuthenticateStreamingRequestAsync(It.Is <string>(v => true), It.Is <string>(v => true), It.Is <CancellationToken>(ct => true)), Times.Once()); }
public async Task CloudAdapterConnectorFactory() { // this is just a basic test to verify the wire-up of a ConnectorFactory in the CloudAdapter // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Method).Returns(HttpMethods.Post); httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); var httpResponseMock = new Mock <HttpResponse>(); var claimsIdentity = new ClaimsIdentity(); var authenticateRequestResult = new AuthenticateRequestResult { ClaimsIdentity = claimsIdentity, ConnectorFactory = new TestConnectorFactory(), Audience = "audience", CallerId = "callerId" }; var userTokenClient = new TestUserTokenClient("appId"); var cloudEnvironmentMock = new Mock <BotFrameworkAuthentication>(); cloudEnvironmentMock.Setup(ce => ce.AuthenticateRequestAsync(It.IsAny <Activity>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authenticateRequestResult)); cloudEnvironmentMock.Setup(ce => ce.CreateConnectorFactory(It.IsAny <ClaimsIdentity>())).Returns(new TestConnectorFactory()); cloudEnvironmentMock.Setup(ce => ce.CreateUserTokenClientAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <UserTokenClient>(userTokenClient)); var bot = new ConnectorFactoryBot(); // Act var adapter = new CloudAdapter(cloudEnvironmentMock.Object); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot); // Assert Assert.Equal("audience", bot.Authorization.Parameter); Assert.Equal(claimsIdentity, bot.Identity); Assert.Equal(userTokenClient, bot.UserTokenClient); Assert.True(bot.ConnectorClient != null); Assert.True(bot.BotCallbackHandler != null); }
private async Task <bool> DownloadTool(UserIdentity identity, string payloadId, string hashCode, DeviceToolPayloadMode mode) { bool result = false; if (identity == null) { throw new Exception("Identity not defined!"); } try { var assemblyPath = GetPluginFilePath(GetPluginFileName(Guid.NewGuid().ToString())); var query = HttpUtility.ParseQueryString(string.Empty); query["uniqueId"] = payloadId; query["hashCode"] = hashCode; query["mode"] = $"{(int)mode}"; var url = UrlHelper.BuildUrl(CloudAdapter.Url, "api/description/payload-download", query); var json = await CloudAdapter.Get(identity, url); if (!string.IsNullOrEmpty(json)) { var payload = json.TryDeserializeObject <DeviceToolPayload>(); if (payload != null) { var base64EncodedBytes = Convert.FromBase64String(payload.Content); File.WriteAllBytes(assemblyPath, base64EncodedBytes); PluginStore.Add(payloadId, assemblyPath); PluginStore.Serialize(); result = true; } } } catch (Exception e) { MsgLogger.Exception($"{GetType().Name} - DownloadTool", e); } return(result); }
public async Task MethodNotAllowed(string httpMethod) { // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var webSocketManagerMock = new Mock <WebSocketManager>(); webSocketManagerMock.Setup(w => w.IsWebSocketRequest).Returns(false); var httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(c => c.WebSockets).Returns(webSocketManagerMock.Object); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Method).Returns(httpMethod); httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); httpRequestMock.Setup(r => r.HttpContext).Returns(httpContextMock.Object); var httpResponseMock = new Mock <HttpResponse>().SetupAllProperties(); var mockHttpMessageHandler = new Mock <HttpMessageHandler>(); mockHttpMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(CreateInternalHttpResponse())); var httpClient = new HttpClient(mockHttpMessageHandler.Object); var httpClientFactoryMock = new Mock <IHttpClientFactory>(); httpClientFactoryMock.Setup(cf => cf.CreateClient(It.IsAny <string>())).Returns(httpClient); var bot = new MessageBot(); // Act var cloudEnvironment = BotFrameworkAuthenticationFactory.Create(null, false, null, null, null, null, null, null, null, new PasswordServiceClientCredentialFactory(), new AuthenticationConfiguration(), httpClientFactoryMock.Object, null); var adapter = new CloudAdapter(cloudEnvironment); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot); // Assert Assert.Equal((int)HttpStatusCode.MethodNotAllowed, httpResponseMock.Object.StatusCode); mockHttpMessageHandler.Protected().Verify <Task <HttpResponseMessage> >("SendAsync", Times.Never(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); }
public async Task InjectCloudEnvironment() { // Arrange var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Method).Returns(HttpMethods.Post); httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream()); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); var httpResponseMock = new Mock <HttpResponse>(); var botMock = new Mock <IBot>(); botMock.Setup(b => b.OnTurnAsync(It.IsAny <TurnContext>(), It.IsAny <CancellationToken>())).Returns(Task.CompletedTask); var authenticateRequestResult = new AuthenticateRequestResult { ClaimsIdentity = new ClaimsIdentity(), ConnectorFactory = new TestConnectorFactory(), Audience = "audience", CallerId = "callerId" }; var userTokenClient = new TestUserTokenClient("appId"); var cloudEnvironmentMock = new Mock <BotFrameworkAuthentication>(); cloudEnvironmentMock.Setup(ce => ce.AuthenticateRequestAsync(It.IsAny <Activity>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authenticateRequestResult)); cloudEnvironmentMock.Setup(ce => ce.CreateUserTokenClientAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <UserTokenClient>(userTokenClient)); var httpClient = new Mock <HttpClient>(); // Act var adapter = new CloudAdapter(cloudEnvironmentMock.Object); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, botMock.Object); // Assert botMock.Verify(m => m.OnTurnAsync(It.Is <TurnContext>(tc => true), It.Is <CancellationToken>(ct => true)), Times.Once()); cloudEnvironmentMock.Verify(ce => ce.AuthenticateRequestAsync(It.Is <Activity>(tc => true), It.Is <string>(tc => true), It.Is <CancellationToken>(ct => true)), Times.Once()); }
public void ConstructorWithConfiguration() { // Arrange var appSettings = new Dictionary <string, string> { { "MicrosoftAppId", "appId" }, { "MicrosoftAppPassword", "appPassword" }, { "ChannelService", GovernmentAuthenticationConstants.ChannelService } }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(appSettings) .Build(); // Act _ = new CloudAdapter(configuration); // Assert // TODO: work out what might be a reasonable side effect }
public async Task CloudAdapterContinueConversation() { // Arrange var claimsIdentity = new ClaimsIdentity(); var authenticateRequestResult = new AuthenticateRequestResult { ClaimsIdentity = claimsIdentity, ConnectorFactory = new TestConnectorFactory(), Scope = "scope", CallerId = "callerId" }; var userTokenClient = new TestUserTokenClient("appId"); var cloudEnvironmentMock = new Mock <BotFrameworkAuthentication>(); cloudEnvironmentMock.Setup(ce => ce.AuthenticateRequestAsync(It.IsAny <Activity>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authenticateRequestResult)); cloudEnvironmentMock.Setup(ce => ce.CreateConnectorFactory(It.IsAny <ClaimsIdentity>())).Returns(new TestConnectorFactory()); cloudEnvironmentMock.Setup(ce => ce.CreateUserTokenClientAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <UserTokenClient>(userTokenClient)); var bot = new ConnectorFactoryBot(); var expectedServiceUrl = "http://serviceUrl"; var conversationAccount = new ConversationAccount { Id = "conversation Id" }; var continuationActivity = new Activity { Type = ActivityTypes.Event, ServiceUrl = expectedServiceUrl, Conversation = conversationAccount }; var conversationReference = new ConversationReference { ServiceUrl = expectedServiceUrl, Conversation = conversationAccount }; var actualServiceUrl1 = string.Empty; var actualServiceUrl2 = string.Empty; var actualServiceUrl3 = string.Empty; var actualServiceUrl4 = string.Empty; var actualServiceUrl5 = string.Empty; var actualServiceUrl6 = string.Empty; BotCallbackHandler callback1 = (t, c) => { actualServiceUrl1 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback2 = (t, c) => { actualServiceUrl2 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback3 = (t, c) => { actualServiceUrl3 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback4 = (t, c) => { actualServiceUrl4 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback5 = (t, c) => { actualServiceUrl5 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback6 = (t, c) => { actualServiceUrl6 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; // Act var adapter = new CloudAdapter(cloudEnvironmentMock.Object); await adapter.ContinueConversationAsync("botAppId", continuationActivity, callback1, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, continuationActivity, callback2, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, continuationActivity, "audience", callback3, CancellationToken.None); await adapter.ContinueConversationAsync("botAppId", conversationReference, callback4, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, conversationReference, callback5, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, conversationReference, "audience", callback6, CancellationToken.None); // Assert Assert.Equal(expectedServiceUrl, actualServiceUrl1); Assert.Equal(expectedServiceUrl, actualServiceUrl2); Assert.Equal(expectedServiceUrl, actualServiceUrl3); Assert.Equal(expectedServiceUrl, actualServiceUrl4); Assert.Equal(expectedServiceUrl, actualServiceUrl5); Assert.Equal(expectedServiceUrl, actualServiceUrl6); }
public async Task CloudAdapterProvidesUserTokenClient() { // this is just a basic test to verify the wire-up of a UserTokenClient in the CloudAdapter // there is also some coverage for the internal code that creates the TokenExchangeState string // Arrange string appId = "appId"; string userId = "userId"; string channelId = "channelId"; string conversationId = "conversationId"; string recipientId = "botId"; string relatesToActivityId = "relatesToActivityId"; string connectionName = "connectionName"; var headerDictionaryMock = new Mock <IHeaderDictionary>(); headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null); var httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream(userId, channelId, conversationId, recipientId, relatesToActivityId)); httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object); var httpResponseMock = new Mock <HttpResponse>(); var authenticateRequestResult = new AuthenticateRequestResult { ClaimsIdentity = new ClaimsIdentity(), ConnectorFactory = new TestConnectorFactory(), Scope = "scope", CallerId = "callerId" }; var userTokenClient = new TestUserTokenClient(appId); var cloudEnvironmentMock = new Mock <BotFrameworkAuthentication>(); cloudEnvironmentMock.Setup(ce => ce.AuthenticateRequestAsync(It.IsAny <Activity>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authenticateRequestResult)); cloudEnvironmentMock.Setup(ce => ce.CreateUserTokenClientAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <UserTokenClient>(userTokenClient)); var bot = new UserTokenClientBot(connectionName); // Act var adapter = new CloudAdapter(cloudEnvironmentMock.Object); await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot); // Assert var args_ExchangeTokenAsync = userTokenClient.Record["ExchangeTokenAsync"]; Assert.Equal(userId, (string)args_ExchangeTokenAsync[0]); Assert.Equal(connectionName, (string)args_ExchangeTokenAsync[1]); Assert.Equal(channelId, (string)args_ExchangeTokenAsync[2]); Assert.Equal("TokenExchangeRequest", args_ExchangeTokenAsync[3].GetType().Name); var args_GetAadTokensAsync = userTokenClient.Record["GetAadTokensAsync"]; Assert.Equal(userId, (string)args_GetAadTokensAsync[0]); Assert.Equal(connectionName, (string)args_GetAadTokensAsync[1]); Assert.Equal("x", ((string[])args_GetAadTokensAsync[2])[0]); Assert.Equal("y", ((string[])args_GetAadTokensAsync[2])[1]); Assert.Equal(channelId, (string)args_GetAadTokensAsync[3]); var args_GetSignInResourceAsync = userTokenClient.Record["GetSignInResourceAsync"]; // this code is testing the internal CreateTokenExchangeState function by doing the work in reverse var state = (string)args_GetSignInResourceAsync[0]; var json = Encoding.UTF8.GetString(Convert.FromBase64String(state)); var tokenExchangeState = JsonConvert.DeserializeObject <TokenExchangeState>(json); Assert.Equal(connectionName, tokenExchangeState.ConnectionName); Assert.Equal(appId, tokenExchangeState.MsAppId); Assert.Equal(conversationId, tokenExchangeState.Conversation.Conversation.Id); Assert.Equal(recipientId, tokenExchangeState.Conversation.Bot.Id); Assert.Equal(relatesToActivityId, tokenExchangeState.RelatesTo.ActivityId); Assert.Equal("finalRedirect", (string)args_GetSignInResourceAsync[1]); var args_GetTokenStatusAsync = userTokenClient.Record["GetTokenStatusAsync"]; Assert.Equal(userId, (string)args_GetTokenStatusAsync[0]); Assert.Equal(channelId, (string)args_GetTokenStatusAsync[1]); Assert.Equal("includeFilter", (string)args_GetTokenStatusAsync[2]); var args_GetUserTokenAsync = userTokenClient.Record["GetUserTokenAsync"]; Assert.Equal(userId, (string)args_GetUserTokenAsync[0]); Assert.Equal(connectionName, (string)args_GetUserTokenAsync[1]); Assert.Equal(channelId, (string)args_GetUserTokenAsync[2]); Assert.Equal("magicCode", (string)args_GetUserTokenAsync[3]); var args_SignOutUserAsync = userTokenClient.Record["SignOutUserAsync"]; Assert.Equal(userId, (string)args_SignOutUserAsync[0]); Assert.Equal(connectionName, (string)args_SignOutUserAsync[1]); Assert.Equal(channelId, (string)args_SignOutUserAsync[2]); }
public async Task CloudAdapterCreateConversation() { // Arrange var claimsIdentity = new ClaimsIdentity(); var authenticateRequestResult = new AuthenticateRequestResult { ClaimsIdentity = claimsIdentity, ConnectorFactory = new TestConnectorFactory(), Audience = "audience", CallerId = "callerId" }; var userTokenClient = new TestUserTokenClient("appId"); var conversationResourceResponse = new ConversationResourceResponse(); var createResponse = new HttpOperationResponse <ConversationResourceResponse> { Body = conversationResourceResponse }; // note Moq doesn't support extension methods used in the implementation so we are actually mocking the underlying CreateConversationWithHttpMessagesAsync method var conversationsMock = new Mock <IConversations>(); conversationsMock.Setup(cm => cm.CreateConversationWithHttpMessagesAsync(It.IsAny <ConversationParameters>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(createResponse)); var connectorMock = new Mock <IConnectorClient>(); connectorMock.SetupGet(m => m.Conversations).Returns(conversationsMock.Object); var expectedServiceUrl = "http://serviceUrl"; var expectedAudience = "audience"; var connectorFactoryMock = new Mock <ConnectorFactory>(); connectorFactoryMock.Setup(cf => cf.CreateAsync(It.Is <string>(serviceUrl => serviceUrl == expectedServiceUrl), It.Is <string>(audience => audience == expectedAudience), It.IsAny <CancellationToken>())).Returns(Task.FromResult(connectorMock.Object)); var cloudEnvironmentMock = new Mock <BotFrameworkAuthentication>(); cloudEnvironmentMock.Setup(ce => ce.AuthenticateRequestAsync(It.IsAny <Activity>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authenticateRequestResult)); cloudEnvironmentMock.Setup(ce => ce.CreateConnectorFactory(It.IsAny <ClaimsIdentity>())).Returns(connectorFactoryMock.Object); cloudEnvironmentMock.Setup(ce => ce.CreateUserTokenClientAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <UserTokenClient>(userTokenClient)); var expectedChannelId = "expected-channel-id"; var actualChannelId = string.Empty; BotCallbackHandler callback1 = (t, c) => { actualChannelId = t.Activity.ChannelId; return(Task.CompletedTask); }; var conversationParameters = new ConversationParameters { IsGroup = false, Bot = new ChannelAccount { }, Members = new ChannelAccount[] { }, TenantId = "tenantId", }; // Act var adapter = new CloudAdapter(cloudEnvironmentMock.Object); await adapter.CreateConversationAsync("botAppId", expectedChannelId, expectedServiceUrl, expectedAudience, conversationParameters, callback1, CancellationToken.None); // Assert Assert.Equal(expectedChannelId, actualChannelId); }