Ejemplo n.º 1
0
        public async Task ShouldBeAbleToCancelAtAnyTime(TestDataObject testData)
        {
            // Arrange
            var bookingTestData = testData.GetObject <BookingDialogTestCase>();
            var sut             = new BookingDialog();
            var testClient      = new DialogTestClient(Channels.Test, sut, bookingTestData.InitialBookingDetails, _middlewares);

            // Execute the test case
            Output.WriteLine($"Test Case: {bookingTestData.Name}");
            for (var i = 0; i < bookingTestData.UtterancesAndReplies.GetLength(0); i++)
            {
                var reply = await testClient.SendActivityAsync <IMessageActivity>(bookingTestData.UtterancesAndReplies[i, 0]);

                Assert.Equal(bookingTestData.UtterancesAndReplies[i, 1], reply.Text);
            }

            Assert.Equal(DialogTurnStatus.Complete, testClient.DialogTurnResult.Status);
            Assert.Null(testClient.DialogTurnResult.Result);
        }
Ejemplo n.º 2
0
        public async Task TaskSelector(string utterance, string intent, string invokedDialogResponse, string taskConfirmationMessage)
        {
            // Create a mock recognizer that returns the expected intent.
            var mockLuisRecognizer = SimpleMockFactory.CreateMockLuisRecognizer <FlightBookingRecognizer, FlightBooking>(
                new FlightBooking
            {
                Intents = new Dictionary <FlightBooking.Intent, IntentScore>
                {
                    { Enum.Parse <FlightBooking.Intent>(intent), new IntentScore()
                      {
                          Score = 1
                      } },
                },
                Entities = new FlightBooking._Entities(),
            },
                new Mock <IConfiguration>().Object);

            mockLuisRecognizer.Setup(x => x.IsConfigured).Returns(true);
            var sut        = new MainDialog(mockLuisRecognizer.Object, _mockBookingDialog, _mockLogger.Object);
            var testClient = new DialogTestClient(Channels.Test, sut, middlewares: new[] { new XUnitDialogTestLogger(Output) });

            // Execute the test case
            Output.WriteLine($"Test Case: {intent}");
            var reply = await testClient.SendActivityAsync <IMessageActivity>("hi");

            Assert.Equal("What can I help you with today?", reply.Text);

            reply = await testClient.SendActivityAsync <IMessageActivity>(utterance);

            Assert.Equal(invokedDialogResponse, reply.Text);

            // The Booking dialog displays an additional confirmation message, assert that it is what we expect.
            if (!string.IsNullOrEmpty(taskConfirmationMessage))
            {
                reply = testClient.GetNextReply <IMessageActivity>();
                Assert.StartsWith(taskConfirmationMessage, reply.Text);
            }

            // Validate that the MainDialog starts over once the task is completed.
            reply = testClient.GetNextReply <IMessageActivity>();
            Assert.Equal("What else can I do for you?", reply.Text);
        }
        public async Task EndOfConversationFromExpectRepliesCallsDeleteConversationReferenceAsync()
        {
            Activity activitySent = null;

            // Callback to capture the parameters sent to the skill
            void CaptureAction(string fromBotId, string toBotId, Uri toUri, Uri serviceUrl, string conversationId, Activity activity, CancellationToken cancellationToken)
            {
                // Capture values sent to the skill so we can assert the right parameters were used.
                activitySent = activity;
            }

            // Create a mock skill client to intercept calls and capture what is sent.
            var mockSkillClientx = CreateMockSkillClient(CaptureAction);

            var eoc             = Activity.CreateEndOfConversationActivity() as Activity;
            var expectedReplies = new List <Activity>();

            expectedReplies.Add(eoc);

            // Create a mock skill client to intercept calls and capture what is sent.
            var mockSkillClient = CreateMockSkillClient(CaptureAction, expectedReplies: expectedReplies);

            // Use Memory for conversation state
            var conversationState = new ConversationState(new MemoryStorage());
            var dialogOptions     = CreateSkillDialogOptions(conversationState, mockSkillClient);

            // Create the SkillDialogInstance and the activity to send.
            var sut            = new SkillDialog(dialogOptions);
            var activityToSend = (Activity)Activity.CreateMessageActivity();

            activityToSend.DeliveryMode = DeliveryModes.ExpectReplies;
            activityToSend.Text         = Guid.NewGuid().ToString();
            var client = new DialogTestClient(Channels.Test, sut, new BeginSkillDialogOptions {
                Activity = activityToSend
            }, conversationState: conversationState);

            // Send something to the dialog to start it
            await client.SendActivityAsync <IMessageActivity>("hello");

            Assert.Empty((dialogOptions.ConversationIdFactory as SimpleConversationIdFactory).ConversationRefs);
            Assert.Equal(1, (dialogOptions.ConversationIdFactory as SimpleConversationIdFactory).CreateCount);
        }
        public async Task DialogFlowTests(TestDataObject testData)
        {
            // Arrange
            var testCaseData = testData.GetObject <DateResolverDialogTestCase>();
            var sut          = new DateResolverDialog();
            var testClient   = new DialogTestClient(Channels.Test, sut, testCaseData.InitialData, new[] { new XUnitDialogTestLogger(Output) });

            // Execute the test case
            Output.WriteLine($"Test Case: {testCaseData.Name}");
            Output.WriteLine($"\r\nDialog Input: {testCaseData.InitialData}");
            for (var i = 0; i < testCaseData.UtterancesAndReplies.GetLength(0); i++)
            {
                var reply = await testClient.SendActivityAsync <IMessageActivity>(testCaseData.UtterancesAndReplies[i, 0]);

                Assert.Equal(testCaseData.UtterancesAndReplies[i, 1], reply?.Text);
            }

            Output.WriteLine($"\r\nDialog result: {testClient.DialogTurnResult.Result}");
            Assert.Equal(testCaseData.ExpectedResult, testClient.DialogTurnResult.Result);
        }
        public async Task Test_ValidateCheckoutNoDiscountDialog()
        {
            userState = new UserState(new MemoryStorage());

            var checkoutDialog = new CheckoutDialog(userState);
            //var mainDialog = new MainDialog(checkoutDialog);
            var testClient = new DialogTestClient(Channels.Msteams, checkoutDialog);

            var reply = await testClient.SendActivityAsync <IMessageActivity>("hi");

            Assert.AreEqual("Do you have membership with us?", ((HeroCard)reply.Attachments[0].Content).Text);

            reply = await testClient.SendActivityAsync <IMessageActivity>("no");

            Assert.AreEqual("Do you want to shop and check some offers today?", reply.Text);

            reply = await testClient.SendActivityAsync <IMessageActivity>("Yes");

            Assert.AreEqual("No discount for you at this moment.", ((HeroCard)reply.Attachments[0].Content).Text);
        }
Ejemplo n.º 6
0
        public async Task ShouldThrowHttpExceptionOnPostFailure()
        {
            // Create a mock skill client to intercept calls and capture what is sent.
            var mockSkillClient = CreateMockSkillClient(null, 500);

            // Use Memory for conversation state
            var conversationState = new ConversationState(new MemoryStorage());
            var dialogOptions     = CreateSkillDialogOptions(conversationState, mockSkillClient);

            // Create the SkillDialogInstance and the activity to send.
            var sut            = new SkillDialog(dialogOptions);
            var activityToSend = (Activity)Activity.CreateMessageActivity();

            activityToSend.Text = Guid.NewGuid().ToString();
            var client = new DialogTestClient(Channels.Test, sut, new BeginSkillDialogOptions {
                Activity = activityToSend
            }, conversationState: conversationState);

            // Send something to the dialog
            await Assert.ThrowsExceptionAsync <HttpRequestException>(async() => await client.SendActivityAsync <IMessageActivity>("irrelevant"));
        }
Ejemplo n.º 7
0
        public async Task ShouldSendActivityToDialogAndReceiveReply()
        {
            IActivity    receivedActivity = null;
            const string testUtterance    = "test";
            const string testReply        = "I got your message";

            _mockDialog
            .Setup(x => x.BeginDialogAsync(It.IsAny <DialogContext>(), It.IsAny <object>(), It.IsAny <CancellationToken>()))
            .Returns(async(DialogContext dc, object options, CancellationToken cancellationToken) =>
            {
                receivedActivity = dc.Context.Activity;
                await dc.Context.SendActivityAsync(testReply, cancellationToken: cancellationToken);
                return(new DialogTurnResult(DialogTurnStatus.Complete));
            });
            var sut = new DialogTestClient(_mockDialog.Object);

            var reply = await sut.SendActivityAsync <IMessageActivity>(testUtterance);

            Assert.Equal(testUtterance, receivedActivity.AsMessageActivity().Text);
            Assert.Equal(testReply, reply.Text);
        }
        public async Task DialogFlowUseCases(TestDataObject testData)
        {
            // Arrange
            var bookingTestData = testData.GetObject <BookingDialogTestCase>();
            var sut             = new BookingDialog();
            var testClient      = new DialogTestClient(Channels.Test, sut, bookingTestData.InitialBookingDetails, _middlewares);

            // Execute the test case
            Output.WriteLine($"Test Case: {bookingTestData.Name}");
            for (var i = 0; i < bookingTestData.UtterancesAndReplies.GetLength(0); i++)
            {
                var reply = await testClient.SendActivityAsync <IMessageActivity>(bookingTestData.UtterancesAndReplies[i, 0]);

                Assert.Equal(bookingTestData.UtterancesAndReplies[i, 1], reply?.Text);
            }

            var bookingResults = (BookingDetails)testClient.DialogTurnResult.Result;

            Assert.Equal(bookingTestData.ExpectedBookingDetails?.Origin, bookingResults?.Origin);
            Assert.Equal(bookingTestData.ExpectedBookingDetails?.Destination, bookingResults?.Destination);
            Assert.Equal(bookingTestData.ExpectedBookingDetails?.TravelDate, bookingResults?.TravelDate);
        }
        public async Task Test_CheckoutWithDiscountDialog()
        {
            userState = new UserState(new MemoryStorage());

            var checkoutDialog = new CheckoutDialog(userState);
            //var mainDialog= new MainDialog(checkoutDialog);
            var testClient = new DialogTestClient(Channels.Msteams, checkoutDialog);

            var reply = await testClient.SendActivityAsync <IMessageActivity>("hi");

            Assert.AreEqual("Do you have membership with us?", ((HeroCard)reply.Attachments[0].Content).Text);

            reply = await testClient.SendActivityAsync <IMessageActivity>("yes");

            Assert.AreEqual("Great! we have special offers for you.", reply.Text);
            reply = testClient.GetNextReply <IMessageActivity>();
            Assert.AreEqual("Do you want to shop and check some offers today?", ((HeroCard)reply.Attachments[0].Content).Text);

            reply = await testClient.SendActivityAsync <IMessageActivity>("Yes");

            Assert.AreEqual("You will receive a coupon shortly.", ((HeroCard)reply.Attachments[0].Content).Text);
        }
        public async Task TaskSelector(string utterance, string intent, string invokedDialogResponse, string taskConfirmationMessage)
        {
            // Create a mock recognizer that returns the expected intent.
            var mockLuisRecognizer = SimpleMockFactory.CreateMockLuisRecognizer <FlightBookingRecognizer, FlightBooking>(
                new FlightBooking
            {
                Intents = new Dictionary <FlightBooking.Intent, IntentScore>
                {
                    { Enum.Parse <FlightBooking.Intent>(intent), new IntentScore()
                      {
                          Score = 1
                      } },
                },
                Entities = new FlightBooking._Entities(),
            },
                new Mock <IConfiguration>().Object);

            mockLuisRecognizer.Setup(x => x.IsConfigured).Returns(true);
            var sut        = new MainDialog(mockLuisRecognizer.Object, _mockBookingDialog, _mockLogger.Object);
            var testClient = new DialogTestClient(Channels.Test, sut, middlewares: new[] { new XUnitDialogTestLogger(Output) });

            // Execute the test case
            Output.WriteLine($"Test Case: {intent}");
            var reply = await testClient.SendActivityAsync <IMessageActivity>("hi");

            Assert.Equal("Are you experiencing any of the following: severe difficulty breathing, chest pain, very hard time waking up, confusion, lost consciousness?", reply.Text);



            reply = await testClient.SendActivityAsync <IMessageActivity>(utterance);

            Assert.Equal("Please call 911 or go directly to your nearest emergency department.", reply.Text);



            // Validate that the MainDialog starts over once the task is completed.
            reply = testClient.GetNextReply <IMessageActivity>();
            //Assert.Equal("What else can I do for you?", reply.Text);
        }
Ejemplo n.º 11
0
        public async Task ShowsUnsupportedCitiesWarning(string jsonFile, string expectedMessage)
        {
            // Load the LUIS result json and create a mock recognizer that returns the expected result.
            var luisResultJson     = GetEmbeddedTestData($"{GetType().Namespace}.TestData.{jsonFile}");
            var mockLuisResult     = JsonConvert.DeserializeObject <FlightBooking>(luisResultJson);
            var mockLuisRecognizer = SimpleMockFactory.CreateMockLuisRecognizer <FlightBookingRecognizer, FlightBooking>(
                mockLuisResult,
                new Mock <IConfiguration>().Object);

            mockLuisRecognizer.Setup(x => x.IsConfigured).Returns(true);

            var sut        = new MainDialog(mockLuisRecognizer.Object, _mockBookingDialog, _mockLogger.Object);
            var testClient = new DialogTestClient(Channels.Test, sut, middlewares: new[] { new XUnitDialogTestLogger(Output) });

            // Execute the test case
            Output.WriteLine($"Test Case: {mockLuisResult.Text}");
            var reply = await testClient.SendActivityAsync <IMessageActivity>("hi");

            Assert.Equal("What can I help you with today?", reply.Text);

            reply = await testClient.SendActivityAsync <IMessageActivity>(mockLuisResult.Text);

            Assert.Equal(expectedMessage, reply.Text);
        }
Ejemplo n.º 12
0
        public async Task ShouldSendInitialParameters()
        {
            var optionsSent = new TestOptions
            {
                SomeText   = "Text",
                SomeNumber = 42,
            };
            object optionsReceived = null;

            _mockDialog
            .Setup(x => x.BeginDialogAsync(It.IsAny <DialogContext>(), It.IsAny <object>(), It.IsAny <CancellationToken>()))
            .Returns((DialogContext dc, object options, CancellationToken cancellationToken) =>
            {
                optionsReceived = options;
                return(Task.FromResult(new DialogTurnResult(DialogTurnStatus.Complete)));
            });
            var sut = new DialogTestClient(_mockDialog.Object, optionsSent);

            await sut.SendActivityAsync <IMessageActivity>("test");

            Assert.NotNull(optionsReceived);
            Assert.Equal(optionsSent.SomeText, ((TestOptions)optionsReceived).SomeText);
            Assert.Equal(optionsSent.SomeNumber, ((TestOptions)optionsReceived).SomeNumber);
        }
Ejemplo n.º 13
0
        public async Task DialogFlowUseCases(TestDataObject testData)
        {
            // Arrange
            var bookingTestData = testData.GetObject <GetBookingDetailsDialogTestCase>();
            var sut             = new GetBookingDetailsDialog();
            var testClient      = new DialogTestClient(Channels.Test, sut, bookingTestData.InitialBookingDetails, new[] { new XUnitDialogTestLogger(Output) });

            // Act/Assert
            Output.WriteLine($"Test Case: {bookingTestData.Name}");
            for (var i = 0; i < bookingTestData.UtterancesAndReplies.GetLength(0); i++)
            {
                var reply = await testClient.SendActivityAsync <IMessageActivity>(bookingTestData.UtterancesAndReplies[i, 0]);

                Assert.Equal(bookingTestData.UtterancesAndReplies[i, 1], reply?.Text);
            }

            if (testClient.DialogTurnResult.Result != null)
            {
                var bookingResults = (BookingDetails)testClient.DialogTurnResult.Result;
                Assert.Equal(bookingTestData.ExpectedBookingDetails.Origin, bookingResults.Origin);
                Assert.Equal(bookingTestData.ExpectedBookingDetails.Destination, bookingResults.Destination);
                Assert.Equal(bookingTestData.ExpectedBookingDetails.TravelDate, bookingResults.TravelDate);
            }
        }
        public async Task ShouldNotInterceptOAuthCardsForBadRequest()
        {
            var connectionName = "connectionName";
            var firstResponse  = new ExpectedReplies(new List <Activity> {
                CreateOAuthCardAttachmentActivity("https://test")
            });
            var mockSkillClient = new Mock <BotFrameworkClient>();

            mockSkillClient
            .SetupSequence(x => x.PostActivityAsync <ExpectedReplies>(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Uri>(), It.IsAny <Uri>(), It.IsAny <string>(), It.IsAny <Activity>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new InvokeResponse <ExpectedReplies>
            {
                Status = 200,
                Body   = firstResponse
            }))
            .Returns(Task.FromResult(new InvokeResponse <ExpectedReplies> {
                Status = 409
            }));

            var conversationState = new ConversationState(new MemoryStorage());
            var dialogOptions     = CreateSkillDialogOptions(conversationState, mockSkillClient, connectionName);

            var sut            = new SkillDialog(dialogOptions);
            var activityToSend = CreateSendActivity();
            var testAdapter    = new TestAdapter(Channels.Test)
                                 .Use(new AutoSaveStateMiddleware(conversationState));
            var client = new DialogTestClient(testAdapter, sut, new BeginSkillDialogOptions {
                Activity = activityToSend
            }, conversationState: conversationState);

            testAdapter.AddExchangeableToken(connectionName, Channels.Test, "user1", "https://test", "https://test1");
            var finalActivity = await client.SendActivityAsync <IMessageActivity>("irrelevant");

            Assert.IsNotNull(finalActivity);
            Assert.IsTrue(finalActivity.Attachments.Count == 1);
        }
        public async Task BeginDialogCallsSkill(string deliveryMode)
        {
            Activity activitySent  = null;
            string   fromBotIdSent = null;
            string   toBotIdSent   = null;
            Uri      toUriSent     = null;

            // Callback to capture the parameters sent to the skill
            void CaptureAction(string fromBotId, string toBotId, Uri toUri, Uri serviceUrl, string conversationId, Activity activity, CancellationToken cancellationToken)
            {
                // Capture values sent to the skill so we can assert the right parameters were used.
                fromBotIdSent = fromBotId;
                toBotIdSent   = toBotId;
                toUriSent     = toUri;
                activitySent  = activity;
            }

            // Create a mock skill client to intercept calls and capture what is sent.
            var mockSkillClient = CreateMockSkillClient(CaptureAction);

            // Use Memory for conversation state
            var conversationState = new ConversationState(new MemoryStorage());
            var dialogOptions     = CreateSkillDialogOptions(conversationState, mockSkillClient);

            // Create the SkillDialogInstance and the activity to send.
            var sut            = new SkillDialog(dialogOptions);
            var activityToSend = (Activity)Activity.CreateMessageActivity();

            activityToSend.DeliveryMode = deliveryMode;
            activityToSend.Text         = Guid.NewGuid().ToString();
            var client = new DialogTestClient(Channels.Test, sut, new BeginSkillDialogOptions {
                Activity = activityToSend
            }, conversationState: conversationState);

            Assert.AreEqual(0, ((SimpleConversationIdFactory)dialogOptions.ConversationIdFactory).CreateCount);

            // Send something to the dialog to start it
            await client.SendActivityAsync <Activity>("irrelevant");

            // Assert results and data sent to the SkillClient for fist turn
            Assert.AreEqual(1, ((SimpleConversationIdFactory)dialogOptions.ConversationIdFactory).CreateCount);
            Assert.AreEqual(dialogOptions.BotId, fromBotIdSent);
            Assert.AreEqual(dialogOptions.Skill.AppId, toBotIdSent);
            Assert.AreEqual(dialogOptions.Skill.SkillEndpoint.ToString(), toUriSent.ToString());
            Assert.AreEqual(activityToSend.Text, activitySent.Text);
            Assert.AreEqual(DialogTurnStatus.Waiting, client.DialogTurnResult.Status);

            // Send a second message to continue the dialog
            await client.SendActivityAsync <Activity>("Second message");

            Assert.AreEqual(1, ((SimpleConversationIdFactory)dialogOptions.ConversationIdFactory).CreateCount);

            // Assert results for second turn
            Assert.AreEqual("Second message", activitySent.Text);
            Assert.AreEqual(DialogTurnStatus.Waiting, client.DialogTurnResult.Status);

            // Send EndOfConversation to the dialog
            await client.SendActivityAsync <IEndOfConversationActivity>((Activity)Activity.CreateEndOfConversationActivity());

            // Assert we are done.
            Assert.AreEqual(DialogTurnStatus.Complete, client.DialogTurnResult.Status);
        }