Example #1
0
        /// <inheritdoc/>
        public override async Task SendActivityAsync(BotActivity activity, CancellationToken cancellationToken)
        {
            if (_conversation == null)
            {
                await CreateConversationAsync().ConfigureAwait(false);

                if (activity.Type == ActivityTypes.ConversationUpdate)
                {
                    // CreateConversationAsync sends a ConversationUpdate automatically.
                    // Ignore the activity sent if it is the first one we are sending to the bot and it is a ConversationUpdate.
                    // This can happen with recorded scripts where we get a conversation update from the transcript that we don't
                    // want to use.
                    return;
                }
            }

            var activityPost = new Activity
            {
                From = new ChannelAccount(_user),
                Text = activity.Text,
                Type = activity.Type
            };

            await _dlClient.Conversations.PostActivityAsync(_conversation.ConversationId, activityPost, cancellationToken).ConfigureAwait(false);
        }
Example #2
0
        private async Task <DialogTurnResult> WelcomeStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var card = CardUtils.CreateCardFromJson("gretaWelcomeCard");

            var activity = new Microsoft.Bot.Schema.Activity
            {
                Attachments = new List <Attachment>()
                {
                    new Attachment()
                    {
                        Content     = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(card)),
                        ContentType = "application/vnd.microsoft.card.adaptive"
                    }
                },
                Type = ActivityTypes.Message
            };

            var promptOptions = new PromptOptions
            {
                Prompt      = MessageFactory.Text(registeredMsg),
                RetryPrompt = MessageFactory.Text(registeredMsg + " (Yes/No)")
            };

            await stepContext.Context.SendActivityAsync(activity);

            return(await stepContext.PromptAsync(nameof(ConfirmPrompt), promptOptions, cancellationToken));
        }
Example #3
0
        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);
        }
Example #4
0
        /// <inheritdoc/>
        public override async Task SendActivityAsync(BotActivity activity, CancellationToken cancellationToken)
        {
            if (_conversation == null)
            {
                await StartConversationAsync().ConfigureAwait(false);

                if (activity.Type == ActivityTypes.ConversationUpdate)
                {
                    // StartConversationAsync sends a ConversationUpdate automatically.
                    // Ignore the activity sent if it is the first one we are sending to the bot and it is a ConversationUpdate.
                    // This can happen with recorded scripts where we get a conversation update from the transcript that we don't
                    // want to use.
                    return;
                }
            }

            var activityPost = new Activity
            {
                From = new ChannelAccount(_user),
                Text = activity.Text,
                Type = activity.Type
            };

            _logger.LogDebug($"{DateTime.Now} Sending activity to conversation {_conversation.ConversationId}");
            _logger.LogDebug(JsonConvert.SerializeObject(activityPost, Formatting.Indented));

            await _dlClient.Conversations.PostActivityAsync(_conversation.ConversationId, activityPost, cancellationToken).ConfigureAwait(false);
        }
        public async Task TestAdapter_GetTokenStatusWithFilter()
        {
            TestAdapter adapter   = new TestAdapter();
            string      channelId = "directline";
            string      userId    = "testUser";
            string      token     = "abc123";
            Activity    activity  = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId,
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            adapter.AddUserToken("ABC", channelId, userId, token);
            adapter.AddUserToken("DEF", channelId, userId, token);

            var status = await adapter.GetTokenStatusAsync(turnContext, userId, "DEF");

            Assert.NotNull(status);
            Assert.Single(status);

            var oAuthAppCredentials = MicrosoftAppCredentials.Empty;

            status = await adapter.GetTokenStatusAsync(turnContext, oAuthAppCredentials, userId, "DEF");

            Assert.NotNull(status);
            Assert.Single(status);
        }
        public async Task TestAdapter_GetUserTokenAsyncReturnsToken()
        {
            TestAdapter adapter        = new TestAdapter();
            string      connectionName = "myConnection";
            string      channelId      = "directline";
            string      userId         = "testUser";
            string      token          = "abc123";
            Activity    activity       = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId,
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            adapter.AddUserToken(connectionName, channelId, userId, token);

            var tokenResponse = await adapter.GetUserTokenAsync(turnContext, connectionName, null, CancellationToken.None);

            Assert.NotNull(tokenResponse);
            Assert.Equal(token, tokenResponse.Token);
            Assert.Equal(connectionName, tokenResponse.ConnectionName);

            var oAuthAppCredentials = MicrosoftAppCredentials.Empty;

            tokenResponse = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, connectionName, null, CancellationToken.None);

            Assert.NotNull(tokenResponse);
            Assert.Equal(token, tokenResponse.Token);
            Assert.Equal(connectionName, tokenResponse.ConnectionName);
        }
        public async Task TestAdapter_SignOutNoop()
        {
            TestAdapter adapter        = new TestAdapter();
            string      connectionName = "myConnection";
            string      channelId      = "directline";
            string      userId         = "testUser";
            Activity    activity       = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId,
                },
            };
            TurnContext turnContext         = new TurnContext(adapter, activity);
            var         oAuthAppCredentials = MicrosoftAppCredentials.Empty;

            await adapter.SignOutUserAsync(turnContext);

            await adapter.SignOutUserAsync(turnContext, connectionName);

            await adapter.SignOutUserAsync(turnContext, connectionName, userId);

            await adapter.SignOutUserAsync(turnContext, connectionName : null, userId);

            await adapter.SignOutUserAsync(turnContext, oAuthAppCredentials, connectionName, userId);
        }
        public async Task TestAdapter_GetSignInLinkWithNoUserId()
        {
            TestAdapter adapter        = new TestAdapter();
            string      connectionName = "myConnection";
            string      channelId      = "directline";
            string      userId         = "testUser";
            Activity    activity       = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId,
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            var link = await adapter.GetOauthSignInLinkAsync(turnContext, connectionName, CancellationToken.None);

            Assert.NotNull(link);
            Assert.True(link.Length > 0);

            var oAuthAppCredentials = MicrosoftAppCredentials.Empty;

            link = await adapter.GetOauthSignInLinkAsync(turnContext, oAuthAppCredentials, connectionName, CancellationToken.None);

            Assert.NotNull(link);
            Assert.True(link.Length > 0);
        }
        /// <summary>
        /// Adds a message (an activity) to the log associated with the given user.
        /// </summary>
        /// <param name="activity">The activity to add.</param>
        /// <param name="user">The user associated with the message.</param>
        public async Task AddMessageLog(Microsoft.Bot.Schema.Activity activity, ConversationReference user, bool replace = false)
        {
            if (_messageLogsTable != null)
            {
                // Add to AzureTable
                var body = new MessageLog(user);
                body.AddMessage(activity);

                var msg = new MessageLogEntity
                {
                    PartitionKey = PartitionKey,
                    RowKey       = activity.Conversation.Id,
                    Body         = body.ToJson()
                };

                if (!replace)
                {
                    await AzureStorageHelper.InsertAsync(_messageLogsTable, msg);
                }
                else
                {
                    await AzureStorageHelper.ReplaceAsync(_messageLogsTable, msg);
                }
            }

            else
            {
                // Add to InMemory storage
            }
        }
Example #10
0
        private void StatusBox_KeyUp(object sender, KeyEventArgs e)
        {
            this.StopAnyTTSPlayback();
            if (e.Key != Key.Enter)
            {
                return;
            }

            e.Handled = true;

            if (this.connector == null)
            {
                this.InitSpeechConnector();
            }

            var bfActivity = Activity.CreateMessageActivity();

            bfActivity.Text = this.statusBox.Text;
            if (!string.IsNullOrEmpty(this.settings.RuntimeSettings.Profile.FromId))
            {
                bfActivity.From = new ChannelAccount(this.settings.RuntimeSettings.Profile.FromId);
            }

            this.statusBox.Clear();
            var jsonConnectorActivity = JsonConvert.SerializeObject(bfActivity);

            this.Messages.Add(new MessageDisplay(bfActivity.Text, Sender.User));
            this.Activities.Add(new ActivityDisplay(jsonConnectorActivity, bfActivity, Sender.User));
            string id = this.connector.SendActivityAsync(jsonConnectorActivity).Result;

            Debug.WriteLine($"SendActivityAsync called, id = {id}");
        }
        /// <summary>
        /// Validates an <see cref="Activity"/> according to an expected activity <see cref="TestScriptItem"/>.
        /// </summary>
        /// <param name="expectedActivity">The expected activity of type <see cref="TestScriptItem"/>.</param>
        /// <param name="actualActivity">The actual response <see cref="Activity"/> received.</param>
        /// <param name="cancellationToken">Optional. A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        protected virtual Task AssertActivityAsync(TestScriptItem expectedActivity, Activity actualActivity, CancellationToken cancellationToken = default)
        {
            var templateRegex = new Regex(@"\{\{[\w\s]*\}\}");

            foreach (var assertion in expectedActivity.Assertions)
            {
                var template = templateRegex.Match(assertion);

                if (template.Success)
                {
                    ValidateVariable(template.Value, actualActivity);
                }

                var(result, error) = Expression.Parse(assertion).TryEvaluate <bool>(actualActivity);

                if (!result)
                {
                    throw new InvalidOperationException($"Assertion failed: {assertion}.");
                }

                if (error != null)
                {
                    throw new InvalidOperationException(error);
                }
            }

            return(Task.CompletedTask);
        }
        public async Task TestDateLogUpdateActivities()
        {
            if (StorageEmulatorHelper.CheckEmulator())
            {
                ContainerInit();

                var         dateTimeStartOffset1 = new DateTimeOffset(DateTime.Now);
                var         dateTimeStartOffset2 = new DateTimeOffset(DateTime.UtcNow);
                var         conversation         = TestAdapter.CreateConversation(Guid.NewGuid().ToString("n"));
                TestAdapter adapter = new TestAdapter(conversation)
                                      .Use(new TranscriptLoggerMiddleware(TranscriptStore));
                Activity activityToUpdate = null;
                await new TestFlow(adapter, async(context, cancellationToken) =>
                {
                    if (context.Activity.Text == "update")
                    {
                        activityToUpdate.Text = "new response";
                        await context.UpdateActivityAsync(activityToUpdate);
                    }
                    else
                    {
                        var activity = context.Activity.CreateReply("response");

                        var response = await context.SendActivityAsync(activity);
                        activity.Id  = response.Id;

                        // clone the activity, so we can use it to do an update
                        activityToUpdate = JsonConvert.DeserializeObject <Activity>(JsonConvert.SerializeObject(activity));
                    }
                })
                .Send("foo")
                .Send("update")
                .AssertReply("new response")
                .StartTestAsync();

                await Task.Delay(5000);

                // Perform some queries
                var pagedResult = await TranscriptStore.GetTranscriptActivitiesAsync(conversation.ChannelId, conversation.Conversation.Id, null, dateTimeStartOffset1.DateTime);

                Assert.AreEqual(3, pagedResult.Items.Length);
                Assert.AreEqual("foo", pagedResult.Items[0].AsMessageActivity().Text);
                Assert.AreEqual("new response", pagedResult.Items[1].AsMessageActivity().Text);
                Assert.AreEqual("update", pagedResult.Items[2].AsMessageActivity().Text);

                // Perform some queries
                pagedResult = await TranscriptStore.GetTranscriptActivitiesAsync(conversation.ChannelId, conversation.Conversation.Id, null, DateTimeOffset.MinValue);

                Assert.AreEqual(3, pagedResult.Items.Length);
                Assert.AreEqual("foo", pagedResult.Items[0].AsMessageActivity().Text);
                Assert.AreEqual("new response", pagedResult.Items[1].AsMessageActivity().Text);
                Assert.AreEqual("update", pagedResult.Items[2].AsMessageActivity().Text);

                // Perform some queries
                pagedResult = await TranscriptStore.GetTranscriptActivitiesAsync(conversation.ChannelId, conversation.Conversation.Id, null, DateTimeOffset.MaxValue);

                Assert.AreEqual(0, pagedResult.Items.Length);
            }
        }
        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);
            }
        }
Example #14
0
        private Microsoft.Bot.Schema.Activity CreateResponse(Microsoft.Bot.Schema.Activity activity, Attachment attachment)
        {
            var response = activity.CreateReply();

            response.Attachments = new List <Attachment>()
            {
                attachment
            };
            return(response);
        }
Example #15
0
 protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
 {
     foreach (var member in membersAdded)
     {
         if (member.Id != turnContext.Activity.Recipient.Id)
         {
             Activity reply = MostrarMenuInicial();
             await turnContext.SendActivityAsync(reply, cancellationToken);
         }
     }
 }
        private void ProcessActivity(BotActivity botActivity, int activitySeq)
        {
            if (botActivity.From.Id.StartsWith(_options.BotId, StringComparison.CurrentCultureIgnoreCase))
            {
                botActivity.From.Role = RoleTypes.Bot;
                botActivity.Recipient = new BotChannelAccount(role: RoleTypes.User);

                _activityQueue.Add(activitySeq, botActivity);
                _logger.LogDebug($"{DateTime.Now} Added activity to queue (key is {activitySeq} activity ID is {botActivity.Id}. Activity queue length: {_activityQueue.Count} - Future activities queue length: {_futureQueue.Count}");
            }
        }
Example #17
0
        /// <summary>
        /// Adds a message (an activity) to the log associated with the given user.
        /// </summary>
        /// <param name="activity">The activity to add.</param>
        /// <param name="user">The user associated with the message.</param>
        public void AddMessageLog(Microsoft.Bot.Schema.Activity activity, ConversationReference user)
        {
            if (_messageLogsTable != null)
            {
                // Add to AzureTable
            }

            else
            {
                // Add to InMemory storage
            }
        }
        private async Task ExecuteTestScriptAsync(string callerName, CancellationToken cancellationToken, Dictionary <string, string> scriptParams = null)
        {
            _logger.LogInformation($"\n------ Starting test {callerName} ----------");

            using var reader = new StreamReader(_testScriptPath);
            var plainTestScript = await reader.ReadToEndAsync().ConfigureAwait(false);

            if (scriptParams != null && scriptParams.Any())
            {
                var replacement = string.Join("|", scriptParams.Keys.Select(k => $@"\$\{{\s?{k}\s?\}}").ToArray());
                plainTestScript = Regex.Replace(plainTestScript, replacement, m => scriptParams[m.Value.Trim(new char[] { '$', '{', '}' })]);
            }

            var testScript = JsonConvert.DeserializeObject <TestScript>(plainTestScript);

            foreach (var scriptActivity in testScript.Items)
            {
                switch (scriptActivity.Role)
                {
                case RoleTypes.User:
                    // Send the activity.
                    var sendActivity = new Activity
                    {
                        Type = scriptActivity.Type,
                        Text = scriptActivity.Text
                    };

                    // Think time
                    await Task.Delay(TimeSpan.FromMilliseconds(_thinkTime), cancellationToken).ConfigureAwait(false);

                    await SendActivityAsync(sendActivity, cancellationToken).ConfigureAwait(false);

                    break;

                case RoleTypes.Bot:
                    if (IgnoreScriptActivity(scriptActivity))
                    {
                        break;
                    }

                    var nextReply = await GetNextReplyAsync(cancellationToken).ConfigureAwait(false);
                    await AssertActivityAsync(scriptActivity, nextReply, cancellationToken).ConfigureAwait(false);

                    break;

                default:
                    throw new InvalidOperationException($"Invalid script activity type {scriptActivity.Role}.");
                }
            }

            _logger.LogInformation($"======== Finished running script: {Stopwatch.Elapsed} =============\n");
        }
 private void ShowException(Exception e)
 {
     this.RunOnUiThread(() =>
     {
         Debug.WriteLine(e);
         this.Messages.Add(new MessageDisplay($"App Error (see log for details): {Environment.NewLine} {e.Source} : {e.Message}", Sender.Channel));
         var trace = new Microsoft.Bot.Schema.Activity
         {
             Type  = "Exception",
             Value = e,
         };
         this.Activities.Add(new ActivityDisplay(JsonConvert.SerializeObject(trace), trace, Sender.Channel));
     });
 }
        public async Task TestAdapter_GetUserTokenAsyncReturnsTokenWithMagicCode()
        {
            TestAdapter adapter        = new TestAdapter();
            string      connectionName = "myConnection";
            string      channelId      = "directline";
            string      userId         = "testUser";
            string      token          = "abc123";
            string      magicCode      = "888999";
            Activity    activity       = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId,
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            adapter.AddUserToken(connectionName, channelId, userId, token, magicCode);

            // First it's null
            var tokenResponse = await adapter.GetUserTokenAsync(turnContext, connectionName, null, CancellationToken.None);

            Assert.Null(tokenResponse);

            // Can be retrieved with magic code
            tokenResponse = await adapter.GetUserTokenAsync(turnContext, connectionName, magicCode, CancellationToken.None);

            Assert.NotNull(tokenResponse);
            Assert.Equal(token, tokenResponse.Token);
            Assert.Equal(connectionName, tokenResponse.ConnectionName);

            // Then can be retrieved without magic code
            tokenResponse = await adapter.GetUserTokenAsync(turnContext, connectionName, null, CancellationToken.None);

            Assert.NotNull(tokenResponse);
            Assert.Equal(token, tokenResponse.Token);
            Assert.Equal(connectionName, tokenResponse.ConnectionName);

            // Then can be retrieved using customized AppCredentials
            var oAuthAppCredentials = MicrosoftAppCredentials.Empty;

            tokenResponse = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, connectionName, null, CancellationToken.None);

            Assert.NotNull(tokenResponse);
            Assert.Equal(token, tokenResponse.Token);
            Assert.Equal(connectionName, tokenResponse.ConnectionName);
        }
Example #21
0
        public static ConversationReference GetConversationReference(Microsoft.Bot.Schema.Activity activity)
        {
            BotAssert.ActivityNotNull(activity);

            ConversationReference r = new ConversationReference
            {
                ActivityId   = activity.Id,
                User         = activity.From,
                Bot          = activity.Recipient,
                Conversation = activity.Conversation,
                ChannelId    = activity.ChannelId,
                ServiceUrl   = activity.ServiceUrl
            };

            return(r);
        }
        public async Task LogActivities()
        {
            if (StorageEmulatorHelper.CheckEmulator())
            {
                ContainerInit();

                var         conversation = TestAdapter.CreateConversation(Guid.NewGuid().ToString("n"));
                TestAdapter adapter      = new TestAdapter(conversation)
                                           .Use(new TranscriptLoggerMiddleware(TranscriptStore));

                await new TestFlow(adapter, async(context, cancellationToken) =>
                {
                    var typingActivity = new Activity
                    {
                        Type      = ActivityTypes.Typing,
                        RelatesTo = context.Activity.RelatesTo
                    };
                    await context.SendActivityAsync(typingActivity);
                    await Task.Delay(500);
                    await context.SendActivityAsync("echo:" + context.Activity.Text);
                })
                .Send("foo")
                .AssertReply((activity) => Assert.AreEqual(activity.Type, ActivityTypes.Typing))
                .AssertReply("echo:foo")
                .Send("bar")
                .AssertReply((activity) => Assert.AreEqual(activity.Type, ActivityTypes.Typing))
                .AssertReply("echo:bar")
                .StartTestAsync();

                await Task.Delay(1000);

                var pagedResult = await TranscriptStore.GetTranscriptActivitiesAsync(conversation.ChannelId, conversation.Conversation.Id);

                Assert.AreEqual(6, pagedResult.Items.Length);
                Assert.AreEqual("foo", pagedResult.Items[0].AsMessageActivity().Text);
                Assert.IsNotNull(pagedResult.Items[1].AsTypingActivity());
                Assert.AreEqual("echo:foo", pagedResult.Items[2].AsMessageActivity().Text);
                Assert.AreEqual("bar", pagedResult.Items[3].AsMessageActivity().Text);
                Assert.IsNotNull(pagedResult.Items[4].AsTypingActivity());
                Assert.AreEqual("echo:bar", pagedResult.Items[5].AsMessageActivity().Text);
                foreach (var activity in pagedResult.Items)
                {
                    Assert.IsTrue(!string.IsNullOrWhiteSpace(activity.Id));
                    Assert.IsTrue(activity.Timestamp > default(DateTimeOffset));
                }
            }
        }
Example #23
0
        /// <summary>
        /// Validates an <see cref="Activity"/> according to an expected activity <see cref="TestScriptItem"/>.
        /// </summary>
        /// <param name="expectedActivity">The expected activity of type <see cref="TestScriptItem"/>.</param>
        /// <param name="actualActivity">The actual response <see cref="Activity"/> received.</param>
        /// <param name="cancellationToken">Optional. A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        protected virtual Task AssertActivityAsync(TestScriptItem expectedActivity, Activity actualActivity, CancellationToken cancellationToken = default)
        {
            foreach (var assertion in expectedActivity.Assertions)
            {
                var(result, error) = Expression.Parse(assertion).TryEvaluate <bool>(actualActivity);

                if (!result)
                {
                    throw new Exception($"Assertion failed: {assertion}.");
                }

                if (error != null)
                {
                    throw new Exception(error);
                }
            }

            return(Task.CompletedTask);
        }
Example #24
0
        private async Task ExecuteTestScriptAsync(string callerName, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"\n------ Starting test {callerName} ----------");

            using var reader = new StreamReader(_testScriptPath);

            var testScript = JsonConvert.DeserializeObject <TestScript>(await reader.ReadToEndAsync().ConfigureAwait(false));

            foreach (var scriptActivity in testScript.Items)
            {
                switch (scriptActivity.Role)
                {
                case RoleTypes.User:
                    // Send the activity.
                    var sendActivity = new Activity
                    {
                        Type = scriptActivity.Type,
                        Text = scriptActivity.Text
                    };

                    await SendActivityAsync(sendActivity, cancellationToken).ConfigureAwait(false);

                    break;

                case RoleTypes.Bot:
                    if (IgnoreScriptActivity(scriptActivity))
                    {
                        break;
                    }

                    var nextReply = await GetNextReplyAsync(cancellationToken).ConfigureAwait(false);
                    await AssertActivityAsync(scriptActivity, nextReply, cancellationToken).ConfigureAwait(false);

                    break;

                default:
                    throw new InvalidOperationException($"Invalid script activity type {scriptActivity.Role}.");
                }
            }

            _logger.LogInformation($"======== Finished running script: {Stopwatch.Elapsed} =============\n");
        }
Example #25
0
        public async Task LogUpdateActivities()
        {
            if (CheckEmulator())
            {
                var         conversation = TestAdapter.CreateConversation(Guid.NewGuid().ToString("n"));
                TestAdapter adapter      = new TestAdapter(conversation)
                                           .Use(new TranscriptLoggerMiddleware(TranscriptStore));
                Activity activityToUpdate = null;
                await new TestFlow(adapter, async(context, cancellationToken) =>
                {
                    if (context.Activity.Text == "update")
                    {
                        activityToUpdate.Text = "new response";
                        await context.UpdateActivityAsync(activityToUpdate);
                    }
                    else
                    {
                        var activity = context.Activity.CreateReply("response");
                        var response = await context.SendActivityAsync(activity);
                        activity.Id  = response.Id;

                        // clone the activity, so we can use it to do an update
                        activityToUpdate = JsonConvert.DeserializeObject <Activity>(JsonConvert.SerializeObject(activity));
                    }
                })
                .Send("foo")
                .Send("update")
                .AssertReply("new response")
                .StartTestAsync();

                await Task.Delay(1000);

                var pagedResult = await TranscriptStore.GetTranscriptActivitiesAsync(conversation.ChannelId, conversation.Conversation.Id);

                Assert.AreEqual(3, pagedResult.Items.Length);
                Assert.AreEqual("foo", pagedResult.Items[0].AsMessageActivity().Text);
                Assert.AreEqual("new response", pagedResult.Items[1].AsMessageActivity().Text);
                Assert.AreEqual("update", pagedResult.Items[2].AsMessageActivity().Text);
            }
        }
        public async Task TestAdapter_GetUserTokenAsyncReturnsNullWithCode()
        {
            TestAdapter adapter  = new TestAdapter();
            Activity    activity = new Activity()
            {
                ChannelId = "directline",
                From      = new ChannelAccount()
                {
                    Id = "testUser",
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            var token = await adapter.GetUserTokenAsync(turnContext, "myConnection", "abc123", CancellationToken.None);

            Assert.Null(token);

            var oAuthAppCredentials = MicrosoftAppCredentials.Empty;

            token = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, "myConnection", "abc123", CancellationToken.None);

            Assert.Null(token);
        }
        /// <summary>
        /// Validates the variable date in the bots message with the value between double curly braces.
        /// </summary>
        /// <param name="value">The assertion containing the variable.</param>
        /// <param name="actualActivity">The activity with the message containing the date.</param>
        protected void ValidateVariable(string value, Activity actualActivity)
        {
            var dateRegex = new Regex(@"(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})");
            var wordRegex = new Regex(@"[\w]+");

            var dateMatch          = dateRegex.Match(actualActivity.Text);
            var resultExpression   = string.Empty;
            var expectedExpression = wordRegex.Match(value).Value;
            var dateValue          = string.Empty;

            if (dateMatch.Success)
            {
                dateValue = dateMatch.Value;
                var date = Convert.ToDateTime(dateMatch.Value, CultureInfo.InvariantCulture);
                resultExpression = EvaluateDate(date);
            }

            if (resultExpression != expectedExpression)
            {
                throw new InvalidOperationException($"Assertion failed. The variable '{expectedExpression}' does not match with the value {dateValue}.");
            }

            actualActivity.Text = actualActivity.Text.Replace(dateMatch.Value, value);
        }
 public override Task <SignInResource> GetSignInResourceAsync(string connectionName, Activity activity, string finalRedirect, CancellationToken cancellationToken)
 {
     return(Task.FromResult(new SignInResource()));
 }
 public override Task <AuthenticateRequestResult> AuthenticateRequestAsync(Activity activity, string authHeader, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
Example #30
0
 public override Task <ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Schema.Activity activity, CancellationToken cancellationToken)
 {
     throw new NotSupportedException("Github API doesn't support UpdateActivity semantics, use ((GithubAdapter)turncontext.Adapter).Client to make API calls.");
 }