private TurnContext GetTurnContext(string text, string locale = "en-us") { return(new TurnContext(new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName)), new Schema.Activity(type: Schema.ActivityTypes.Message, text: text, locale: locale))); }
public async Task Telemetry_AdditionalProps() { var mockTelemetryClient = new Mock <IBotTelemetryClient>(); TestAdapter adapter = new TestAdapter() .Use(new OverrideFillLogger(mockTelemetryClient.Object, logPersonalInformation: true)); string conversationId = null; Activity activityToUpdate = null; await new TestFlow(adapter, async(context, cancellationToken) => { conversationId = context.Activity.Conversation.Id; if (context.Activity.Text == "update") { activityToUpdate.Text = "new response"; // Perform Update Delete await context.UpdateActivityAsync(activityToUpdate); await context.DeleteActivityAsync(context.Activity.Id); } else { // Perform Send/Receive 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(); Assert.Equal(mockTelemetryClient.Invocations[0].Arguments[0], TelemetryLoggerConstants.BotMsgReceiveEvent); // Check Receive message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("fromId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("recipientName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("fromName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1])["text"] == "foo"); Assert.Equal(mockTelemetryClient.Invocations[1].Arguments[0], TelemetryLoggerConstants.BotMsgSendEvent); // Check Send message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).Count == 8); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("replyActivityId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("recipientName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("foo")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1])["text"] == "response"); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1])["foo"] == "bar"); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1])["ImportantProperty"] == "ImportantValue"); Assert.Equal(mockTelemetryClient.Invocations[3].Arguments[0], TelemetryLoggerConstants.BotMsgUpdateEvent); // Check Update message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).Count == 7); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("conversationId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("foo")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1])["text"] == "new response"); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1])["foo"] == "bar"); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1])["ImportantProperty"] == "ImportantValue"); Assert.Equal(mockTelemetryClient.Invocations[4].Arguments[0], TelemetryLoggerConstants.BotMsgDeleteEvent); // Check Delete message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[4].Arguments[1]).Count == 5); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[4].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[4].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[4].Arguments[1]).ContainsKey("conversationId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[4].Arguments[1]).ContainsKey("foo")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[4].Arguments[1])["foo"] == "bar"); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[4].Arguments[1])["ImportantProperty"] == "ImportantValue"); }
public async Task WaterfallCosmos() { var convoState = new ConversationState(_storage); var adapter = new TestAdapter() .Use(new AutoSaveStateMiddleware(convoState)); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var dialogs = new DialogSet(dialogState); dialogs.Add(new TextPrompt(nameof(TextPrompt), async(promptContext, cancellationToken) => { var result = promptContext.Recognized.Value; if (result.Length > 3) { var succeededMessage = MessageFactory.Text($"You got it at the {promptContext.AttemptCount}th try!"); await promptContext.Context.SendActivityAsync(succeededMessage, cancellationToken); return(true); } var reply = MessageFactory.Text($"Please send a name that is longer than 3 characters. {promptContext.AttemptCount}"); await promptContext.Context.SendActivityAsync(reply, cancellationToken); return(false); })); var steps = new WaterfallStep[] { async(stepContext, ct) => { Assert.Equal(typeof(int), stepContext.ActiveDialog.State["stepIndex"].GetType()); await stepContext.Context.SendActivityAsync("step1"); return(Dialog.EndOfTurn); }, async(stepContext, ct) => { Assert.Equal(typeof(int), stepContext.ActiveDialog.State["stepIndex"].GetType()); return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please type your name.") }, ct)); }, async(stepContext, ct) => { Assert.Equal(typeof(int), stepContext.ActiveDialog.State["stepIndex"].GetType()); await stepContext.Context.SendActivityAsync("step3"); return(Dialog.EndOfTurn); }, }; dialogs.Add(new WaterfallDialog(nameof(WaterfallDialog), steps)); await new TestFlow(adapter, async(turnContext, cancellationToken) => { var dc = await dialogs.CreateContextAsync(turnContext); await dc.ContinueDialogAsync(); if (!turnContext.Responded) { await dc.BeginDialogAsync(nameof(WaterfallDialog)); } }) .Send("hello") .AssertReply("step1") .Send("hello") .AssertReply("Please type your name.") .Send("hi") .AssertReply("Please send a name that is longer than 3 characters. 1") .Send("hi") .AssertReply("Please send a name that is longer than 3 characters. 2") .Send("hi") .AssertReply("Please send a name that is longer than 3 characters. 3") .Send("Kyle") .AssertReply("You got it at the 4th try!") .AssertReply("step3") .StartTestAsync(); }
public async Task ShouldAcceptAndRecognizeCustomLocaleDict() { var convoState = new ConversationState(new MemoryStorage()); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var adapter = new TestAdapter() .Use(new AutoSaveStateMiddleware(convoState)); // Create new DialogSet. var dialogs = new DialogSet(dialogState); var culture = new PromptCultureModel() { InlineOr = " customOr ", InlineOrMore = " customOrMore ", Locale = "custom-custom", Separator = "customSeparator", NoInLanguage = "customNo", YesInLanguage = "customYes", }; var customDict = new Dictionary <string, ChoiceFactoryOptions>() { { culture.Locale, new ChoiceFactoryOptions(culture.Separator, culture.InlineOr, culture.InlineOrMore, true) }, }; dialogs.Add(new ChoicePrompt("ChoicePrompt", customDict, null, culture.Locale)); var helloLocale = MessageFactory.Text("hello"); helloLocale.Locale = culture.Locale; await new TestFlow(adapter, async(turnContext, cancellationToken) => { var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken); var results = await dc.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { await dc.PromptAsync( "ChoicePrompt", new PromptOptions { Prompt = new Activity { Type = ActivityTypes.Message, Text = "favorite color?", Locale = culture.Locale }, Choices = _colorChoices, }, cancellationToken); } }) .Send(helloLocale) .AssertReply((activity) => { // Use ChoiceFactory to build the expected answer, manually var expectedChoices = ChoiceFactory.Inline(_colorChoices, null, null, new ChoiceFactoryOptions() { InlineOr = culture.InlineOr, InlineOrMore = culture.InlineOrMore, InlineSeparator = culture.Separator, }).Text; Assert.AreEqual($"favorite color?{expectedChoices}", activity.AsMessageActivity().Text); }) .StartTestAsync(); }
public async Task Telemetry_OverrideReceive() { // Arrange var mockTelemetryClient = new Mock <IBotTelemetryClient>(); TestAdapter adapter = new TestAdapter() .Use(new OverrideReceiveLogger(mockTelemetryClient.Object, logPersonalInformation: true)); string conversationId = null; // Act // Override the TelemetryMiddleware component and override the Receive event. await new TestFlow(adapter, async(context, cancellationToken) => { conversationId = context.Activity.Conversation.Id; 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.Equal(activity.Type, ActivityTypes.Typing)) .AssertReply("echo:foo") .Send("bar") .AssertReply((activity) => Assert.Equal(activity.Type, ActivityTypes.Typing)) .AssertReply("echo:bar") .StartTestAsync(); // Assert Assert.Equal(8, mockTelemetryClient.Invocations.Count); Assert.Equal(mockTelemetryClient.Invocations[0].Arguments[0], TelemetryLoggerConstants.BotMsgReceiveEvent); // Check initial message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).Count == 2); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("foo")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1])["foo"] == "bar"); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("ImportantProperty")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1])["ImportantProperty"] == "ImportantValue"); Assert.Equal("MyReceive", mockTelemetryClient.Invocations[1].Arguments[0]); // Check my message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("fromId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("recipientName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("fromName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1])["text"] == "foo"); Assert.Equal("BotMessageSend", mockTelemetryClient.Invocations[2].Arguments[0]); // Check Typing message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).Count == 5); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("replyActivityId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("recipientName")); Assert.Equal("BotMessageSend", mockTelemetryClient.Invocations[3].Arguments[0]); // Check message reply Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).Count == 6); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("replyActivityId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("recipientName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1])["text"] == "echo:foo"); }
public void RespondedIsFalse() { var c = new TurnContext(new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName)), new Activity()); Assert.IsFalse(c.Responded); }
public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback) { await Task.Delay((int)Timespan).ConfigureAwait(false); Trace.TraceInformation($"[Turn Ended => {Timespan} ms processing UserDelay[{Timespan}]"); }
public async Task OAuthPromptWithTokenExchangeWrongConnectionNameFail() { var convoState = new ConversationState(new MemoryStorage()); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var adapter = new TestAdapter() .Use(new AutoSaveStateMiddleware(convoState)); var connectionName = "myConnection"; var exchangeToken = "exch123"; // Create new DialogSet. var dialogs = new DialogSet(dialogState); dialogs.Add(new OAuthPrompt("OAuthPrompt", new OAuthPromptSettings() { Text = "Please sign in", ConnectionName = connectionName, Title = "Sign in" })); BotCallbackHandler botCallbackHandler = async(turnContext, cancellationToken) => { var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken); var results = await dc.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { await dc.PromptAsync("OAuthPrompt", new PromptOptions(), cancellationToken : cancellationToken); } else if (results.Status == DialogTurnStatus.Complete) { if (results.Result is TokenResponse) { await turnContext.SendActivityAsync(MessageFactory.Text("Logged in."), cancellationToken); } else { await turnContext.SendActivityAsync(MessageFactory.Text("Failed."), cancellationToken); } } }; await new TestFlow(adapter, botCallbackHandler) .Send("hello") .AssertReply(activity => { Assert.Single(((Activity)activity).Attachments); Assert.Equal(OAuthCard.ContentType, ((Activity)activity).Attachments[0].ContentType); Assert.Equal(InputHints.AcceptingInput, ((Activity)activity).InputHint); // No exchangable token is added to the adapter }) .Send(new Activity() { Type = ActivityTypes.Invoke, Name = SignInConstants.TokenExchangeOperationName, Value = JObject.FromObject(new TokenExchangeInvokeRequest() { ConnectionName = "beepboop", Token = exchangeToken }) }) .AssertReply(a => { Assert.Equal("invokeResponse", a.Type); var response = ((Activity)a).Value as InvokeResponse; Assert.NotNull(response); Assert.Equal(400, response.Status); var body = response.Body as TokenExchangeInvokeResponse; Assert.Equal(connectionName, body.ConnectionName); Assert.NotNull(body.FailureDetail); }) .StartTestAsync(); }
private async Task PromptTimeoutEndsDialogTest(IActivity oauthPromptActivity) { var convoState = new ConversationState(new MemoryStorage()); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var adapter = new TestAdapter() .Use(new AutoSaveStateMiddleware(convoState)); var connectionName = "myConnection"; var exchangeToken = "exch123"; var magicCode = "888999"; var token = "abc123"; // Create new DialogSet. var dialogs = new DialogSet(dialogState); // Set timeout to zero, so the prompt will end immediately. dialogs.Add(new OAuthPrompt("OAuthPrompt", new OAuthPromptSettings() { Text = "Please sign in", ConnectionName = connectionName, Title = "Sign in", Timeout = 0 })); BotCallbackHandler botCallbackHandler = async(turnContext, cancellationToken) => { var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken); var results = await dc.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { await dc.PromptAsync("OAuthPrompt", new PromptOptions(), cancellationToken : cancellationToken); } else if (results.Status == DialogTurnStatus.Complete) { // If the TokenResponse comes back, the timeout did not occur. if (results.Result is TokenResponse) { await turnContext.SendActivityAsync("failed", cancellationToken : cancellationToken); } else { await turnContext.SendActivityAsync("ended", cancellationToken : cancellationToken); } } }; await new TestFlow(adapter, botCallbackHandler) .Send("hello") .AssertReply(activity => { Assert.Single(((Activity)activity).Attachments); Assert.Equal(OAuthCard.ContentType, ((Activity)activity).Attachments[0].ContentType); // Add a magic code to the adapter adapter.AddUserToken(connectionName, activity.ChannelId, activity.Recipient.Id, token, magicCode); // Add an exchangable token to the adapter adapter.AddExchangeableToken(connectionName, activity.ChannelId, activity.Recipient.Id, exchangeToken, token); }) .Send(oauthPromptActivity) .AssertReply("ended") .StartTestAsync(); }
public static async Task RecordScript(ILifetimeScope container, bool proactive, StreamWriter stream, Func <string> extraInfo, params string[] inputs) { var toBot = MakeTestMessage(); var adapter = new TestAdapter(); await adapter.ProcessActivityAsync((Activity)toBot, async (ctx, cancellationToken) => { using (var containerScope = DialogModule.BeginLifetimeScope(container, ctx)) { var task = containerScope.Resolve <IPostToBot>(); var queue = adapter.ActiveQueue; Action drain = () => { stream.WriteLine($"{queue.Count()}"); while (queue.Count > 0) { var toUser = queue.Dequeue(); if (!string.IsNullOrEmpty(toUser.Text)) { stream.WriteLine($"ToUserText:{JsonConvert.SerializeObject(toUser.Text)}"); } else { stream.WriteLine($"ToUserButtons:{JsonConvert.SerializeObject(toUser.Attachments)}"); } } }; string result = null; var root = containerScope.Resolve <IDialog <object> >().Do(async(context, value) => result = JsonConvert.SerializeObject(await value)); using (var innerScope = containerScope.BeginLifetimeScope( async(builder) => { if (proactive) { var loop = root.Loop(); var data = containerScope.Resolve <IBotData>(); await data.LoadAsync(CancellationToken.None); var stack = containerScope.Resolve <IDialogTask>(); stack.Call(loop, null); await stack.PollAsync(CancellationToken.None); drain(); } else { builder .RegisterInstance(root) .AsSelf() .As <IDialog <object> >(); } })) { foreach (var input in inputs) { stream.WriteLine($"FromUser:{JsonConvert.SerializeObject(input)}"); toBot.Text = input; try { await task.PostAsync(toBot, CancellationToken.None); drain(); if (extraInfo != null) { var extra = extraInfo(); stream.WriteLine(extra); } } catch (Exception e) { stream.WriteLine($"Exception:{e.Message}"); } } if (result != null) { stream.WriteLine($"Result: {result}"); } } } }); }
public async Task Action_HttpRequest() { var handler = new MockHttpMessageHandler(); handler .When(HttpMethod.Post, "http://foo.com/") .WithContent("Joe is 52") .Respond("plain/text", "string"); handler .When(HttpMethod.Post, "http://foo.com/") .WithContent("{\r\n \"text\": \"Joe is 52\",\r\n \"age\": 52\r\n}".Replace("\r\n", Environment.NewLine)) .Respond("plain/text", "object"); handler .When(HttpMethod.Post, "http://foo.com/") .WithHeaders(new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("bound", "52"), new KeyValuePair <string, string>("unbound", "dialog.age") }) .WithContent("[\r\n {\r\n \"text\": \"Joe is 52\",\r\n \"age\": 52\r\n },\r\n {\r\n \"text\": \"text\",\r\n \"age\": 11\r\n }\r\n]".Replace("\r\n", Environment.NewLine)) .Respond("plain/text", "array"); // Reply with a bytes array and this bytes array would be base64encoded by the sdk handler .When(HttpMethod.Get, "http://foo.com/image") .Respond("image/jpeg", new MemoryStream(System.Text.Encoding.ASCII.GetBytes("TestImage"))); handler .When(HttpMethod.Get, "http://foo.com/json") .Respond("application/json", "{\"test\": \"test\"}"); var messageActivityWithText = Activity.CreateMessageActivity(); messageActivityWithText.Text = "testtest"; handler .When(HttpMethod.Get, "http://foo.com/activity") .Respond("application/vnd.microsoft.activity", JsonConvert.SerializeObject(messageActivityWithText)); var message1 = Activity.CreateMessageActivity(); message1.Text = "test1"; var message2 = Activity.CreateMessageActivity(); message2.Text = "test2"; var message3 = Activity.CreateMessageActivity(); message3.Text = "test3"; var listOfActivites = new Activity[] { (Activity)message1, (Activity)message2, (Activity)message3 }; handler .When(HttpMethod.Get, "http://foo.com/activities") .Respond("application/vnd.microsoft.activities", JsonConvert.SerializeObject(listOfActivites)); var testAdapter = new TestAdapter() .UseStorage(new MemoryStorage()) .UseBotState(new ConversationState(new MemoryStorage()), new UserState(new MemoryStorage())); var rootDialog = new AdaptiveDialog() { Triggers = new List <Conditions.OnCondition>() { new OnBeginDialog() { Actions = new List <Dialog>() { new SetProperties() { Assignments = new List <PropertyAssignment>() { new PropertyAssignment() { Property = "dialog.name", Value = "Joe" }, new PropertyAssignment() { Property = "dialog.age", Value = 52 }, } }, new HttpRequest() { Url = "http://foo.com/", Method = HttpRequest.HttpMethod.POST, ContentType = "plain/text", Body = "${dialog.name} is ${dialog.age}" }, new SendActivity("${turn.lastresult.content}"), new HttpRequest() { Url = "http://foo.com/", Method = HttpRequest.HttpMethod.POST, ContentType = "application/json", Body = JToken.FromObject(new { text = "${dialog.name} is ${dialog.age}", age = "=dialog.age" }) }, new SendActivity("${turn.lastresult.content}"), new HttpRequest() { Url = "http://foo.com/", Method = HttpRequest.HttpMethod.POST, ContentType = "application/json", Headers = new Dictionary <string, AdaptiveExpressions.Properties.StringExpression>() { { "bound", "=dialog.age" }, { "unbound", "dialog.age" } }, Body = JToken.FromObject(new object[] { new { text = "${dialog.name} is ${dialog.age}", age = "=dialog.age" }, new { text = "text", age = 11 } }) }, new SendActivity("${turn.lastresult.content}"), new HttpRequest() { Url = "http://foo.com/image", Method = HttpRequest.HttpMethod.GET, ResponseType = HttpRequest.ResponseTypes.Binary }, new SendActivity("${turn.lastresult.content}"), new HttpRequest() { Url = "http://foo.com/json", Method = HttpRequest.HttpMethod.GET, ResponseType = HttpRequest.ResponseTypes.Json }, new SendActivity("${turn.lastresult.content.test}"), new HttpRequest() { Url = "http://foo.com/activity", Method = HttpRequest.HttpMethod.GET, ResponseType = HttpRequest.ResponseTypes.Activity }, new HttpRequest() { Url = "http://foo.com/activities", Method = HttpRequest.HttpMethod.GET, ResponseType = HttpRequest.ResponseTypes.Activities }, new SendActivity("done") } } } }; DialogManager dm = new DialogManager(rootDialog) .UseResourceExplorer(new ResourceExplorer()) .UseLanguageGeneration(); dm.InitialTurnState.Set <HttpClient>(handler.ToHttpClient()); await new TestFlow((TestAdapter)testAdapter, dm.OnTurnAsync) .SendConversationUpdate() .AssertReply("string") .AssertReply("object") .AssertReply("array") .AssertReply("VGVzdEltYWdl") .AssertReply("test") .AssertReply("testtest") .AssertReply("test1") .AssertReply("test2") .AssertReply("test3") .AssertReply("done") .StartTestAsync(); }
public static async Task VerifyScript(ILifetimeScope container, Func <IDialog <object> > makeRoot, bool proactive, StreamReader stream, Action <IDialogStack, string> extraCheck, string[] expected, string locale) { var toBot = DialogTestBase.MakeTestMessage(); if (!string.IsNullOrEmpty(locale)) { toBot.Locale = locale; } string input, label; int current = 0; while ((input = ReadLine(stream, out label)) != null) { var adapter = new TestAdapter(); await adapter.ProcessActivityAsync((Activity)toBot, async (ctx, cancellationToken) => { using (var scope = DialogModule.BeginLifetimeScope(container, ctx)) { var task = scope.Resolve <IPostToBot>(); var queue = adapter.ActiveQueue; Action <IDialogStack> check = (stack) => { var count = int.Parse((proactive && current == 0) ? input : stream.ReadLine()); Assert.AreEqual(count, queue.Count); for (var i = 0; i < count; ++i) { var toUser = queue.Dequeue(); var expectedOut = ReadLine(stream, out label); if (label == "ToUserText") { Assert.AreEqual(expectedOut, JsonConvert.SerializeObject(toUser.Text)); } else { Assert.AreEqual(expectedOut, JsonConvert.SerializeObject(toUser.Attachments)); } } extraCheck?.Invoke(stack, ReadLine(stream, out label)); }; Func <IDialog <object> > scriptMakeRoot = () => { return(makeRoot().Do(async(context, value) => context.PrivateConversationData.SetValue("result", JsonConvert.SerializeObject(await value)))); }; scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(scriptMakeRoot)); if (proactive && current == 0) { var loop = scriptMakeRoot().Loop(); var data = scope.Resolve <IBotData>(); await data.LoadAsync(CancellationToken.None); var stack = scope.Resolve <IDialogTask>(); stack.Call(loop, null); await stack.PollAsync(CancellationToken.None); check(stack); input = ReadLine(stream, out label); } if (input.StartsWith("\"")) { try { toBot.Text = input.Substring(1, input.Length - 2); Assert.IsTrue(current < expected.Length && toBot.Text == expected[current++]); await task.PostAsync(toBot, CancellationToken.None); var data = scope.Resolve <IBotData>(); await data.LoadAsync(CancellationToken.None); var stack = scope.Resolve <IDialogStack>(); check(stack); } catch (Exception e) { Assert.AreEqual(ReadLine(stream, out label), e.Message); } } else if (label.ToLower().StartsWith("result")) { var data = scope.Resolve <IBotData>(); await data.LoadAsync(CancellationToken.None); string result; Assert.IsTrue(data.PrivateConversationData.TryGetValue("result", out result)); Assert.AreEqual(input.Trim(), result); } } }); } }
public async Task TextPromptValidatorWithMessageShouldNotSendRetryPrompt() { var convoState = new ConversationState(new MemoryStorage()); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName)) .Use(new AutoSaveStateMiddleware(convoState)) .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger())); var dialogs = new DialogSet(dialogState); PromptValidator <string> validator = async(promptContext, cancellationToken) => { var value = promptContext.Recognized.Value; if (value.Length <= 3) { await promptContext.Context.SendActivityAsync(MessageFactory.Text("The text should be greater than 3 chars."), cancellationToken); return(false); } else { return(true); } }; var textPrompt = new TextPrompt("TextPrompt", validator); dialogs.Add(textPrompt); await new TestFlow(adapter, async(turnContext, cancellationToken) => { var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken); var results = await dc.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { var options = new PromptOptions { Prompt = new Activity { Type = ActivityTypes.Message, Text = "Enter some text." }, RetryPrompt = new Activity { Type = ActivityTypes.Message, Text = "Make sure the text is greater than three characters." }, }; await dc.PromptAsync("TextPrompt", options); } else if (results.Status == DialogTurnStatus.Complete) { var textResult = (string)results.Result; await turnContext.SendActivityAsync(MessageFactory.Text($"Bot received the text '{textResult}'."), cancellationToken); } }) .Send("hello") .AssertReply("Enter some text.") .Send("hi") .AssertReply("The text should be greater than 3 chars.") .Send("hello") .AssertReply("Bot received the text 'hello'.") .StartTestAsync(); }
/// <summary> /// Creates a TestFlow instance with state data to recreate and assert the different test case. /// </summary> private TestFlow CreateTestFlow(Dialog dialog, FlowTestCase testCase, string locale = null) { var conversationId = Guid.NewGuid().ToString(); var storage = new MemoryStorage(); var convoState = new ConversationState(storage); var userState = new UserState(storage); var adapter = new TestAdapter(TestAdapter.CreateConversation(conversationId)); adapter .UseStorage(storage) .UseBotState(userState, convoState) .Use(new AutoSaveStateMiddleware(userState, convoState)) .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false))); if (!string.IsNullOrEmpty(locale)) { adapter.Locale = locale; } return(new TestFlow(adapter, async(turnContext, cancellationToken) => { if (testCase != FlowTestCase.RootBotOnly) { // Create a skill ClaimsIdentity and put it in TurnState so SkillValidation.IsSkillClaim() returns true. var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(AuthenticationConstants.VersionClaim, "2.0")); claimsIdentity.AddClaim(new Claim(AuthenticationConstants.AudienceClaim, _skillBotId)); claimsIdentity.AddClaim(new Claim(AuthenticationConstants.AuthorizedParty, _parentBotId)); turnContext.TurnState.Add(BotAdapter.BotIdentityKey, claimsIdentity); if (testCase == FlowTestCase.RootBotConsumingSkill) { // Simulate the SkillConversationReference with a channel OAuthScope stored in TurnState. // This emulates a response coming to a root bot through SkillHandler. turnContext.TurnState.Add(SkillHandler.SkillConversationReferenceKey, new SkillConversationReference { OAuthScope = AuthenticationConstants.ToChannelFromBotOAuthScope }); } if (testCase == FlowTestCase.MiddleSkill) { // Simulate the SkillConversationReference with a parent Bot ID stored in TurnState. // This emulates a response coming to a skill from another skill through SkillHandler. turnContext.TurnState.Add(SkillHandler.SkillConversationReferenceKey, new SkillConversationReference { OAuthScope = _parentBotId }); } } // Interceptor to capture the EoC activity if it was sent so we can assert it in the tests. turnContext.OnSendActivities(async(tc, activities, next) => { _eocSent = activities.FirstOrDefault(activity => activity.Type == ActivityTypes.EndOfConversation); return await next().ConfigureAwait(false); }); // Invoke RunAsync on the dialog. await dialog.RunAsync(turnContext, convoState.CreateProperty <DialogState>("DialogState"), cancellationToken); })); }
/// <summary> /// Starts the execution of the test sequence. /// </summary> /// <remarks>This methods sends the activities from the user to the bot and /// checks the responses from the bot based on the TestActions.</remarks> /// <param name="resourceExplorer">The resource explorer to use.</param> /// <param name="testName">Name of the test.</param> /// <param name="callback">The bot logic.</param> /// <param name="adapter">optional test adapter.</param> /// <returns>Runs the exchange between the user and the bot.</returns> public async Task ExecuteAsync(ResourceExplorer resourceExplorer, [CallerMemberName] string testName = null, BotCallbackHandler callback = null, TestAdapter adapter = null) { if (adapter == null) { adapter = DefaultTestAdapter(resourceExplorer, testName); } adapter.EnableTrace = this.EnableTrace; adapter.Locale = this.Locale; adapter.Use(new MockHttpRequestMiddleware(HttpRequestMocks)); adapter.Use(new MockSettingsMiddleware(PropertyMocks)); foreach (var userToken in UserTokenMocks) { userToken.Setup(adapter); } if (callback != null) { foreach (var testAction in this.Script) { await testAction.ExecuteAsync(adapter, callback).ConfigureAwait(false); } } else { var dm = new DialogManager(WrapDialogForPropertyMocks(this.Dialog)) .UseResourceExplorer(resourceExplorer) .UseLanguageGeneration(); foreach (var testAction in this.Script) { await testAction.ExecuteAsync(adapter, dm.OnTurnAsync).ConfigureAwait(false); } } }
public static void Cleanup() { #if INTEGRATION TestAdapter.Run($"run AdoNetTests {nameof(DropDatabase)}"); #endif }
public void Constructor() { var c = new TurnContext(new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName)), new Activity()); Assert.IsNotNull(c); }
public void StoredProcedureAdoNetDbReaderTest() { TestAdapter.Run($"run AdoNetTests {nameof(StoredProcedureAdoNetDbReaderTests)}"); }
/// <summary> /// Execute the test. /// </summary> /// <param name="adapter">adapter to execute against.</param> /// <param name="callback">logic for the bot to use.</param> /// <returns>async task.</returns> public abstract Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback);
public void LoadThenInsertCountriesTest() { TestAdapter.Run($"run AdoNetTests {nameof(LoadThenInsertCountries)}"); }
public async Task ShouldSendPromptUsingAppendedHeroCard() { var convoState = new ConversationState(new MemoryStorage()); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var adapter = new TestAdapter() .Use(new AutoSaveStateMiddleware(convoState)); var dialogs = new DialogSet(dialogState); var listPrompt = new ChoicePrompt("ChoicePrompt", defaultLocale: Culture.English) { Style = ListStyle.HeroCard, }; dialogs.Add(listPrompt); await new TestFlow(adapter, async(turnContext, cancellationToken) => { var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken); var results = await dc.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { // Create mock attachment for testing. var attachment = new Attachment { Content = "some content", ContentType = "text/plain" }; await dc.PromptAsync( "ChoicePrompt", new PromptOptions { Prompt = new Activity { Type = ActivityTypes.Message, Text = "favorite color?", Attachments = new List <Attachment> { attachment } }, Choices = _colorChoices, }, cancellationToken); } }) .Send("hello") .AssertReply(HeroCardValidator( new HeroCard { Text = "favorite color?", Buttons = new List <CardAction> { new CardAction { Type = "imBack", Value = "red", Title = "red" }, new CardAction { Type = "imBack", Value = "green", Title = "green" }, new CardAction { Type = "imBack", Value = "blue", Title = "blue" }, }, }, 1)) .StartTestAsync(); }
public void MergeCountriesTest() { TestAdapter.Run($"run AdoNetTests {nameof(MergeOnlyInsertCountries)}"); }
public async Task TestAdapter_SignOutAll() { 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 tokenResponse = await adapter.GetUserTokenAsync(turnContext, "ABC", null, CancellationToken.None); Assert.NotNull(tokenResponse); Assert.Equal(token, tokenResponse.Token); Assert.Equal("ABC", tokenResponse.ConnectionName); tokenResponse = await adapter.GetUserTokenAsync(turnContext, "DEF", null, CancellationToken.None); Assert.NotNull(tokenResponse); Assert.Equal(token, tokenResponse.Token); Assert.Equal("DEF", tokenResponse.ConnectionName); await adapter.SignOutUserAsync(turnContext, connectionName : null, userId); tokenResponse = await adapter.GetUserTokenAsync(turnContext, "ABC", null, CancellationToken.None); Assert.Null(tokenResponse); tokenResponse = await adapter.GetUserTokenAsync(turnContext, "DEF", null, CancellationToken.None); Assert.Null(tokenResponse); adapter.AddUserToken("ABC", channelId, userId, token); adapter.AddUserToken("DEF", channelId, userId, token); var oAuthAppCredentials = MicrosoftAppCredentials.Empty; tokenResponse = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, "ABC", null, CancellationToken.None); Assert.NotNull(tokenResponse); Assert.Equal(token, tokenResponse.Token); Assert.Equal("ABC", tokenResponse.ConnectionName); tokenResponse = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, "DEF", null, CancellationToken.None); Assert.NotNull(tokenResponse); Assert.Equal(token, tokenResponse.Token); Assert.Equal("DEF", tokenResponse.ConnectionName); await adapter.SignOutUserAsync(turnContext, connectionName : null, userId); tokenResponse = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, "ABC", null, CancellationToken.None); Assert.Null(tokenResponse); tokenResponse = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, "DEF", null, CancellationToken.None); Assert.Null(tokenResponse); }
public void MergeUpdateCountriesTest() { TestAdapter.Run($"run AdoNetTests {nameof(MergeUpdateCountries)}"); }
public async Task Telemetry_LogActivities() { // Arrange var mockTelemetryClient = new Mock <IBotTelemetryClient>(); TestAdapter adapter = new TestAdapter() .Use(new TelemetryLoggerMiddleware(mockTelemetryClient.Object, logPersonalInformation: true)); string conversationId = null; // Act // Default case logging Send/Receive Activities await new TestFlow(adapter, async(context, cancellationToken) => { conversationId = context.Activity.Conversation.Id; 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.Equal(activity.Type, ActivityTypes.Typing)) .AssertReply("echo:foo") .Send("bar") .AssertReply((activity) => Assert.Equal(activity.Type, ActivityTypes.Typing)) .AssertReply("echo:bar") .StartTestAsync(); // Assert Assert.Equal(6, mockTelemetryClient.Invocations.Count); Assert.Equal("BotMessageReceived", mockTelemetryClient.Invocations[0].Arguments[0]); // Check initial message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).Count == 7); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("fromId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("recipientName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("fromName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[0].Arguments[1])["text"] == "foo"); Assert.Equal("BotMessageSend", mockTelemetryClient.Invocations[1].Arguments[0]); // Check Typing message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).Count == 5); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("replyActivityId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[1].Arguments[1]).ContainsKey("recipientName")); Assert.Equal("BotMessageSend", mockTelemetryClient.Invocations[2].Arguments[0]); // Check message reply Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).Count == 6); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("replyActivityId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("recipientName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[2].Arguments[1])["text"] == "echo:foo"); Assert.Equal("BotMessageReceived", mockTelemetryClient.Invocations[3].Arguments[0]); // Check bar message Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).Count == 7); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("fromId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("conversationName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("locale")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("recipientId")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("recipientName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("fromName")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1]).ContainsKey("text")); Assert.True(((Dictionary <string, string>)mockTelemetryClient.Invocations[3].Arguments[1])["text"] == "bar"); }
public static void Initialize(TestContext context) { #if INTEGRATION TestAdapter.Run($"run AdoNetTests {nameof(CreateDatabase)}"); #endif }
public async Task SingleParameterConstructor() { var adapter = new TestAdapter(); // If this compiles, the test has passed. :) }
public async Task CallDialogInParentComponent() { var convoState = new ConversationState(new MemoryStorage()); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var adapter = new TestAdapter(TestAdapter.CreateConversation(nameof(CallDialogDefinedInParentComponent))) .Use(new AutoSaveStateMiddleware(convoState)) .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false))); await new TestFlow(adapter, async(turnContext, cancellationToken) => { var state = await dialogState.GetAsync(turnContext, () => new DialogState()); var dialogs = new DialogSet(dialogState); var childComponent = new ComponentDialog("childComponent"); var childStep = new WaterfallStep[] { async(step, token) => { await step.Context.SendActivityAsync("Child started."); return(await step.BeginDialogAsync("parentDialog", "test")); }, async(step, token) => { await step.Context.SendActivityAsync($"Child finished. Value: {step.Result}"); return(await step.EndDialogAsync()); } }; childComponent.AddDialog(new WaterfallDialog("childDialog", childStep)); var parentComponent = new ComponentDialog("parentComponent"); parentComponent.AddDialog(childComponent); var parentStep = new WaterfallStep[] { async(step, token) => { await step.Context.SendActivityAsync("Parent called."); return(await step.EndDialogAsync(step.Options)); } }; parentComponent.AddDialog(new WaterfallDialog("parentDialog", parentStep)); dialogs.Add(parentComponent); var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken); var results = await dc.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { await dc.BeginDialogAsync("parentComponent", null, cancellationToken); } else if (results.Status == DialogTurnStatus.Complete) { var value = (int)results.Result; await turnContext.SendActivityAsync(MessageFactory.Text($"Bot received the number '{value}'."), cancellationToken); } }) .Send("Hi") .AssertReply("Child started.") .AssertReply("Parent called.") .AssertReply("Child finished. Value: test") .StartTestAsync(); }
private TestFlow CreateFlow(ITriggerSelector selector) { TypeFactory.Configuration = new ConfigurationBuilder().Build(); var storage = new MemoryStorage(); var convoState = new ConversationState(storage); var userState = new UserState(storage); var resourceExplorer = new ResourceExplorer(); var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName)); adapter .UseStorage(storage) .UseState(userState, convoState) .UseResourceExplorer(resourceExplorer) .UseAdaptiveDialogs() .UseLanguageGeneration(resourceExplorer) .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger())); var dialog = new AdaptiveDialog() { Selector = selector }; dialog.Recognizer = new RegexRecognizer { Intents = new List <IntentPattern>() { new IntentPattern("a", "a"), new IntentPattern("b", "b"), new IntentPattern("trigger", "trigger"), } }; dialog.Triggers.AddRange(new List <OnCondition>() { new OnIntent("a", actions: new List <Dialog> { new SetProperty { Property = "user.a", Value = "1" } }), new OnIntent("b", actions: new List <Dialog> { new SetProperty { Property = "user.b", Value = "1" } }), new OnIntent("trigger", constraint: "user.a == 1", actions: new List <Dialog> { new SendActivity("ruleA1") }), new OnIntent("trigger", constraint: "user.a == 1", actions: new List <Dialog> { new SendActivity("ruleA2") }), new OnIntent("trigger", constraint: "user.b == 1 || user.c == 1", actions: new List <Dialog> { new SendActivity("ruleBorC") }), new OnIntent("trigger", constraint: "user.a == 1 && user.b == 1", actions: new List <Dialog> { new SendActivity("ruleAandB") }), new OnIntent("trigger", constraint: "user.a == 1 && user.c == 1", actions: new List <Dialog> { new SendActivity("ruleAandC") }), new OnIntent("trigger", constraint: string.Empty, actions: new List <Dialog> { new SendActivity("default") }) }); dialog.AutoEndDialog = false; DialogManager dm = new DialogManager(dialog); return(new TestFlow(adapter, async(turnContext, cancellationToken) => { await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false); })); }
public async Task CallDialogDefinedInParentComponent() { var convoState = new ConversationState(new MemoryStorage()); var dialogState = convoState.CreateProperty <DialogState>("dialogState"); var adapter = new TestAdapter() .Use(new AutoSaveStateMiddleware(convoState)); var options = new Dictionary <string, string> { { "value", "test" } }; var childComponent = new ComponentDialog("childComponent"); var childActions = new WaterfallStep[] { async(step, ct) => { await step.Context.SendActivityAsync("Child started."); return(await step.BeginDialogAsync("parentDialog", options)); }, async(step, ct) => { Assert.Equal("test", (string)step.Result); await step.Context.SendActivityAsync("Child finished."); return(await step.EndDialogAsync()); }, }; childComponent.AddDialog(new WaterfallDialog( "childDialog", childActions)); var parentComponent = new ComponentDialog("parentComponent"); parentComponent.AddDialog(childComponent); var parentActions = new WaterfallStep[] { async(step, dc) => { var stepOptions = step.Options as IDictionary <string, string>; Assert.NotNull(stepOptions); Assert.True(stepOptions.ContainsKey("value")); await step.Context.SendActivityAsync($"Parent called with: {stepOptions["value"]}"); return(await step.EndDialogAsync(stepOptions["value"])); }, }; parentComponent.AddDialog(new WaterfallDialog( "parentDialog", parentActions)); await new TestFlow(adapter, async(turnContext, cancellationToken) => { var dialogs = new DialogSet(dialogState); dialogs.Add(parentComponent); var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken); var results = await dc.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { await dc.BeginDialogAsync("parentComponent", null, cancellationToken); } else if (results.Status == DialogTurnStatus.Complete) { var value = (int)results.Result; await turnContext.SendActivityAsync(MessageFactory.Text("Done"), cancellationToken); } }) .Send("Hi") .AssertReply("Child started.") .AssertReply("Parent called with: test") .AssertReply("Child finished.") .StartTestAsync(); }
public UserProxyTests() { adapter = new TestAdapter(); proxy = new UserProxy(adapter); }
protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); var fixture = Assembly.GetExecutingAssembly ().GetType (Intent.GetStringExtra ("FixtureFullName")); Title = fixture.Name; ListAdapter = new TestAdapter ( this, from t in fixture.GetMethods () where t.GetCustomAttributes (typeof (global::NUnit.Framework.TestAttribute), true).Length > 0 orderby t.Name select t); ListView.ItemClick += (s, e) => { RunTest (((TestAdapter)ListAdapter)[e.Position]); }; }