예제 #1
0
        public async Task EnforceETagConsistency()
        {
            Func <IDialog <object> > MakeRoot = () => chain;

            using (new FiberTestBase.ResolveMoqAssembly(chain))
                using (var container = Build(Options.MockConnectorFactory, chain))
                {
                    var msg = DialogTestBase.MakeTestMessage();
                    msg.Text = "test";
                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
                        try
                        {
                            await Conversation.SendAsync(scope, msg);

                            Assert.Fail();
                        }
                        catch (HttpOperationException e)
                        {
                            Assert.AreEqual(e.Response.StatusCode, HttpStatusCode.PreconditionFailed);
                            var data = await mockConnectorFactory.StateClient.BotState.GetPrivateConversationDataAsync(msg.ChannelId, msg.Conversation.Id, msg.From.Id);

                            Assert.AreEqual(10, data.GetProperty <int>("mycount"));
                        }
                        catch (Exception)
                        {
                            Assert.Fail();
                        }
                    }
                }
        }
예제 #2
0
        public async Task LastWriteWinsConsistency()
        {
            Func <IDialog <object> > MakeRoot = () => chain;

            using (new FiberTestBase.ResolveMoqAssembly(chain))
                using (var container = Build(Options.MockConnectorFactory | Options.LastWriteWinsCachingBotDataStore, chain))
                {
                    var msg = DialogTestBase.MakeTestMessage();
                    msg.Text = "test";
                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        connectorFactory = scope.Resolve <IConnectorClientFactory>();

                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
                        await Conversation.SendAsync(scope, msg);

                        var reply = scope.Resolve <Queue <IMessageActivity> >().Dequeue();
                        Assert.AreEqual("1:test", reply.Text);
                        var stateClient = connectorFactory.MakeStateClient();
                        var data        = await stateClient.BotState.GetPrivateConversationDataAsync(msg.ChannelId, msg.Conversation.Id, msg.From.Id);

                        Assert.AreEqual(1, data.GetProperty <int>("count"));
                        Assert.AreEqual(0, data.GetProperty <int>("mycount")); // The overwritten data should be 0
                    }
                }
        }
예제 #3
0
        public void HasContent_Test()
        {
            IMessageActivity activity = DialogTestBase.MakeTestMessage();

            Assert.IsFalse(activity.HasContent());
            activity.Text = "test";
            Assert.IsTrue(activity.HasContent());
        }
예제 #4
0
        public async Task InMemoryBotDataStoreTest()
        {
            var chain = Chain.PostToChain().Select(m => m.Text).ContinueWith <string, string>(async(context, result) =>
            {
                int t = 0;
                context.UserData.TryGetValue("count", out t);
                if (t > 0)
                {
                    int value;
                    Assert.IsTrue(context.ConversationData.TryGetValue("conversation", out value));
                    Assert.AreEqual(t - 1, value);
                    Assert.IsTrue(context.UserData.TryGetValue("user", out value));
                    Assert.AreEqual(t + 1, value);
                    Assert.IsTrue(context.PrivateConversationData.TryGetValue("PrivateConversationData", out value));
                    Assert.AreEqual(t + 2, value);
                }

                context.ConversationData.SetValue("conversation", t);
                context.UserData.SetValue("user", t + 2);
                context.PrivateConversationData.SetValue("PrivateConversationData", t + 3);
                context.UserData.SetValue("count", ++t);
                return(Chain.Return($"{t}:{await result}"));
            }).PostToUser();
            Func <IDialog <object> > MakeRoot = () => chain;

            using (new FiberTestBase.ResolveMoqAssembly(chain))
                using (var container = Build(Options.InMemoryBotDataStore, chain))
                {
                    var msg = DialogTestBase.MakeTestMessage();
                    msg.Text = "test";
                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));

                        await Conversation.SendAsync(scope, msg);

                        var reply = scope.Resolve <Queue <IMessageActivity> >().Dequeue();
                        Assert.AreEqual("1:test", reply.Text);
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                        {
                            scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
                            await Conversation.SendAsync(scope, msg);

                            var reply = scope.Resolve <Queue <IMessageActivity> >().Dequeue();
                            Assert.AreEqual($"{i + 2}:test", reply.Text);
                            var    store     = scope.Resolve <CachingBotDataStore>();
                            var    dataStore = scope.Resolve <InMemoryDataStore>();
                            string val       = string.Empty;
                            Assert.IsTrue(scope.Resolve <IBotData>().PrivateConversationData.TryGetValue(DialogModule.BlobKey, out val));
                            Assert.AreNotEqual(string.Empty, val);
                        }
                    }
                }
        }
예제 #5
0
        public async Task SendResumeAsyncTest()
        {
            var chain = Chain.PostToChain().Select(m => m.Text).Switch(
                new RegexCase <IDialog <string> >(new Regex("^resume"), (context, data) => { context.UserData.SetValue("resume", true); return(Chain.Return("resumed!")); }),
                new DefaultCase <string, IDialog <string> >((context, data) => { return(Chain.Return(data)); })).Unwrap().PostToUser();

            using (new FiberTestBase.ResolveMoqAssembly(chain))
                using (var container = Build(Options.InMemoryBotDataStore, chain))
                {
                    var msg = DialogTestBase.MakeTestMessage();
                    msg.Text = "testMsg";

                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        Func <IDialog <object> > MakeRoot = () => chain;
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));

                        await Conversation.SendAsync(scope, msg);

                        var reply = scope.Resolve <Queue <IMessageActivity> >().Dequeue();

                        var botData = scope.Resolve <IBotData>();
                        await botData.LoadAsync(default(CancellationToken));

                        var dataBag = scope.Resolve <Func <IBotDataBag> >()();
                        Assert.IsTrue(dataBag.ContainsKey(ResumptionContext.RESUMPTION_CONTEXT_KEY));
                        Assert.IsNotNull(scope.Resolve <ConversationReference>());
                    }

                    var conversationReference = msg.ToConversationReference();
                    var continuationMessage   = conversationReference.GetPostToBotMessage();
                    using (var scope = DialogModule.BeginLifetimeScope(container, continuationMessage))
                    {
                        Func <IDialog <object> > MakeRoot = () => { throw new InvalidOperationException(); };
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));

                        await scope.Resolve <IPostToBot>().PostAsync(new Activity {
                            Text = "resume"
                        }, CancellationToken.None);

                        var reply = scope.Resolve <Queue <IMessageActivity> >().Dequeue();
                        Assert.AreEqual("resumed!", reply.Text);

                        var botData = scope.Resolve <IBotData>();
                        await botData.LoadAsync(default(CancellationToken));

                        Assert.IsTrue(botData.UserData.GetValue <bool>("resume"));
                    }
                }
        }
예제 #6
0
        public void GetMentions_Test()
        {
            IMessageActivity activity = DialogTestBase.MakeTestMessage();

            Assert.IsFalse(activity.GetMentions().Any());
            activity.Entities = new List <Entity> {
                new Mention()
                {
                    Text = "testMention"
                }
            };
            // Cloning activity to resemble the incoming activity to bot
            var clonedActivity = JsonConvert.DeserializeObject <Activity>(JsonConvert.SerializeObject(activity));

            Assert.IsTrue(clonedActivity.GetMentions().Any());
            Assert.AreEqual("testMention", clonedActivity.GetMentions()[0].Text);
        }
        public DispatchDialogTests()
        {
            this.container = DialogTestBase.Build(
                DialogTestBase.Options.None | DialogTestBase.Options.ResolveDialogFromContainer,
                this.methods.Object, this.luisOne.Object, this.luisTwo.Object);
            var builder = new ContainerBuilder();

            builder
            .RegisterInstance(this.methods.Object)
            .As <IMethods>();
            builder
            .RegisterInstance <Func <ILuisModel, ILuisService> >(MakeLuisService)
            .AsSelf();
            builder
            .RegisterType <TestDispatchDialog>()
            .As <IDialog <object> >()
            .InstancePerLifetimeScope();
            builder.Update(this.container);
        }
예제 #8
0
        public async Task SendResumeAsyncTest()
        {
            var chain = Chain.PostToChain().Select(m => m.Text).Switch(
                new RegexCase <IDialog <string> >(new Regex("^resume"), (context, data) => { context.UserData.SetValue("resume", true); return(Chain.Return("resumed!")); }),
                new DefaultCase <string, IDialog <string> >((context, data) => { return(Chain.Return(data)); })).Unwrap().PostToUser();

            using (new FiberTestBase.ResolveMoqAssembly(chain))
                using (var container = Build(Options.None, new MockConnectorFactory(), chain))
                {
                    var msg = DialogTestBase.MakeTestMessage();
                    msg.Text = "testMsg";

                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        Func <IDialog <object> > MakeRoot = () => chain;
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));

                        var reply = await Conversation.SendAsync(scope, msg);

                        // storing data in mocked connector client
                        var client = scope.Resolve <IConnectorClient>();
                        await PersistMessageData(client, msg.To.Id, msg.From.Id, msg.ConversationId, reply);
                    }

                    var resumptionCookie    = new ResumptionCookie(msg);
                    var continuationMessage = resumptionCookie.GetMessage();
                    using (var scope = DialogModule.BeginLifetimeScope(container, continuationMessage))
                    {
                        Func <IDialog <object> > MakeRoot = () => { throw new InvalidOperationException(); };
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));

                        var reply = await Conversation.ResumeAsync(scope, continuationMessage, new Message { Text = "resume" });

                        Assert.AreEqual("resumed!", reply.Text);

                        var client = scope.Resolve <IConnectorClient>();
                        await PersistMessageData(client, msg.To.Id, msg.From.Id, msg.ConversationId, reply);

                        Assert.IsTrue(client.Bots.GetUserData(msg.To.Id, msg.From.Id).GetProperty <bool>("resume"));
                        Assert.AreEqual("MockedDataStore", client.Bots.GetUserData(msg.To.Id, msg.From.Id).ETag);
                    }
                }
        }
예제 #9
0
        public async Task InputHintTest()
        {
            var chain = Chain.PostToChain().Select(m => m.Text).ContinueWith <string, string>(async(context, result) =>
            {
                var text = await result;
                if (text.ToLower().StartsWith("inputhint"))
                {
                    var reply       = context.MakeMessage();
                    reply.Text      = "reply";
                    reply.InputHint = InputHints.ExpectingInput;
                    await context.PostAsync(reply);
                    return(Chain.Return($"{text}"));
                }
                else if (!text.ToLower().StartsWith("reset"))
                {
                    for (int i = 0; i < 10; i++)
                    {
                        await context.PostAsync($"message:{i}");
                    }
                    return(Chain.Return($"{text}"));
                }
                else
                {
                    return(Chain.From(() => new PromptDialog.PromptConfirm("Are you sure you want to reset the count?",
                                                                           "Didn't get that!", 3, PromptStyle.Keyboard)).ContinueWith <bool, string>(async(ctx, res) =>
                    {
                        string reply;
                        if (await res)
                        {
                            ctx.UserData.SetValue("count", 0);
                            reply = "Reset count.";
                        }
                        else
                        {
                            reply = "Did not reset count.";
                        }
                        return Chain.Return(reply);
                    }));
                }
            }).PostToUser();
            Func <IDialog <object> > MakeRoot = () => chain;

            using (new FiberTestBase.ResolveMoqAssembly(chain))
                using (var container = Build(Options.InMemoryBotDataStore | Options.NeedsInputHint, chain))
                {
                    var msg = DialogTestBase.MakeTestMessage();
                    msg.Text = "test";

                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
                        await Conversation.SendAsync(scope, msg);

                        var queue = scope.Resolve <Queue <IMessageActivity> >();
                        Assert.IsTrue(queue.Count > 0);
                        while (queue.Count > 0)
                        {
                            var toUser = queue.Dequeue();
                            if (queue.Count > 0)
                            {
                                Assert.IsTrue(toUser.InputHint == InputHints.IgnoringInput);
                            }
                            else
                            {
                                Assert.IsTrue(toUser.InputHint == InputHints.AcceptingInput);
                            }
                        }
                    }


                    msg.Text = "inputhint";
                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
                        await Conversation.SendAsync(scope, msg);

                        var queue = scope.Resolve <Queue <IMessageActivity> >();
                        Assert.IsTrue(queue.Count == 2);
                        var toUser = queue.Dequeue();
                        Assert.AreEqual("reply", toUser.Text);
                        Assert.IsTrue(toUser.InputHint == InputHints.ExpectingInput);
                    }

                    msg.Text = "reset";
                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
                        await Conversation.SendAsync(scope, msg);

                        var queue = scope.Resolve <Queue <IMessageActivity> >();
                        Assert.IsTrue(queue.Count == 1);
                        var toUser = queue.Dequeue();
                        Assert.IsTrue(toUser.InputHint == InputHints.ExpectingInput);
                    }
                }
        }
예제 #10
0
        protected override IBotData MakeBotData()
        {
            var msg = DialogTestBase.MakeTestMessage();

            return(new DictionaryBotData(new BotIdResolver(msg.Recipient.Id), msg, new CachingBotDataStore(new InMemoryDataStore(), CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency)));
        }
예제 #11
0
        public async Task BotDispatcher()
        {
            var token   = new CancellationTokenSource().Token;
            var pathOld = TestFiles.DeploymentItemPathsForCaller(TestContext, this.GetType()).Single();
            var pathNew = TestFiles.TestResultPathFor(TestContext, Path.GetFileName(pathOld));

            using (var writer = File.CreateText(pathNew))
            {
                var message = (Activity)DialogTestBase.MakeTestMessage();

                var bot = ExampleBot.MakeBot(MakeMockedLuisService);
                // TODO: Microsoft.Extensions.DependencyInjection
                {
                    // test mocks
                    var builder = new ContainerBuilder();

                    // register singleton StreamWriter
                    builder
                    .RegisterInstance(writer)
                    .AsSelf();

                    // log all activities to and from bot
                    builder
                    .RegisterType <TestActivityLogger>()
                    .AsImplementedInterfaces()
                    .SingleInstance();

                    // truncate AlwaysSendDirect_BotToUser/IConnectorClient with null implementation
                    builder
                    .RegisterType <NullBotToUser>()
                    .Keyed <IBotToUser>(typeof(AlwaysSendDirect_BotToUser))
                    .InstancePerLifetimeScope();

                    // truncate ConnectorStore/IStateClient with in-memory implementation
                    builder
                    .RegisterType <InMemoryDataStore>()
                    .Keyed <IBotDataStore <BotData> >(typeof(ConnectorStore))
                    .SingleInstance();

                    builder.Update(((Bot)bot).Container);
                }

                var texts = new[]
                {
                    "echo reset an empty stack",
                    "reset",

                    "echo start chit chat dialog with normal quit",
                    "hello",
                    "lol wut",
                    "goodbye",

                    "echo start chit chat dialog with cancel quit",
                    "hello",
                    "lol wut",
                    "cancel",

                    "echo start list builder dialog with cancel quit",
                    "list",
                    "itemA",
                    "itemB",
                    "cancel",

                    "echo start list builder dialog with message forward with cancel quit",
                    "list itemC",
                    "itemD",
                    "cancel",

                    "echo start list builder dialog with reset",
                    "list",
                    "itemE",
                    "reset",
                    "itemF",
                    "cancel",

                    "echo chit chat dialog is not re-entrant",
                    "hello",
                    "hello",
                    "cancel",

                    "echo list dialog is not re-entrant",
                    "list",
                    "list",
                    "cancel",

                    "echo list builder dialog interrupts chit chat dialog",
                    "hello",
                    "list itemG",
                    "cancel",

                    "echo chit chat dialog interrupts list builder dialog then resume list builder dialog",
                    "list itemH",
                    "hello",
                    "cancel",
                    "yes",
                    "itemI",
                    "cancel",

                    "echo chit chat dialog interrupts list builder dialog then cancel list builder dialog",
                    "list itemH",
                    "hello",
                    "cancel",
                    "no",

                    // proactive (NEED TO MOCK TIMER)
                    //"echo proactive",
                    //UtteranceSetAlarm,

                    // clean up
                    "reset",
                };

                for (int index = 0; index < texts.Length; ++index)
                {
                    var text = texts[index];

                    message.Text = "stack";
                    await bot.PostAsync(message, token);

                    message.Text = text;
                    await bot.PostAsync(message, token);
                }

                message.Text = "stack";
                await bot.PostAsync(message, token);
            }

            CollectionAssert.AreEqual(File.ReadAllLines(pathOld), File.ReadAllLines(pathNew));
        }
예제 #12
0
        public async Task If_Root_Dialog_Throws_Propagate_Exception_Reset_Store()
        {
            var dialog = new Mock <IDialogThatFails>(MockBehavior.Loose);

            dialog
            .Setup(d => d.StartAsync(It.IsAny <IDialogContext>()))
            .Returns <IDialogContext>(async context => { context.Wait(dialog.Object.MessageReceived); });

            dialog
            .Setup(d => d.MessageReceived(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()))
            .Returns <IDialogContext, IAwaitable <IMessageActivity> >(async(context, result) => { context.Wait(dialog.Object.Throw); });

            dialog
            .Setup(d => d.Throw(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()))
            .Throws <ApplicationException>();

            Func <IDialog <object> > MakeRoot = () => dialog.Object;
            var toBot = DialogTestBase.MakeTestMessage();

            using (new FiberTestBase.ResolveMoqAssembly(dialog.Object))
                using (var container = Build(Options.MockConnectorFactory, dialog.Object))
                {
                    using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                    {
                        DialogModule_MakeRoot.Register(scope, MakeRoot);

                        var task = scope.Resolve <IPostToBot>();
                        await task.PostAsync(toBot, CancellationToken.None);
                    }

                    dialog.Verify(d => d.StartAsync(It.IsAny <IDialogContext>()), Times.Once);
                    dialog.Verify(d => d.MessageReceived(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()), Times.Once);
                    dialog.Verify(d => d.Throw(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()), Times.Never);

                    using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                    {
                        DialogModule_MakeRoot.Register(scope, MakeRoot);

                        await scope.Resolve <IBotData>().LoadAsync(default(CancellationToken));

                        var task = scope.Resolve <IDialogStack>();
                        Assert.AreNotEqual(0, task.Frames.Count);
                    }

                    using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                    {
                        DialogModule_MakeRoot.Register(scope, MakeRoot);

                        var task = scope.Resolve <IPostToBot>();

                        try
                        {
                            await task.PostAsync(toBot, CancellationToken.None);

                            Assert.Fail();
                        }
                        catch (ApplicationException)
                        {
                        }
                        catch
                        {
                            Assert.Fail();
                        }
                    }

                    dialog.Verify(d => d.StartAsync(It.IsAny <IDialogContext>()), Times.Once);
                    dialog.Verify(d => d.MessageReceived(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()), Times.Once);
                    dialog.Verify(d => d.Throw(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()), Times.Once);

                    //make sure that data is persisted with connector
                    using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                    {
                        var connectorFactory = scope.Resolve <IConnectorClientFactory>();
                        var botDataStore     = scope.Resolve <IBotDataStore <BotData> >();
                        var botData          = scope.Resolve <IBotData>();
                        await botData.LoadAsync(default(CancellationToken));

                        Assert.AreEqual(1, botData.PrivateConversationData.Count);
                    }

                    using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                    {
                        DialogModule_MakeRoot.Register(scope, MakeRoot);

                        await scope.Resolve <IBotData>().LoadAsync(default(CancellationToken));

                        var stack = scope.Resolve <IDialogStack>();
                        Assert.AreEqual(0, stack.Frames.Count);
                    }

                    using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                    {
                        DialogModule_MakeRoot.Register(scope, MakeRoot);

                        var task = scope.Resolve <IPostToBot>();
                        await task.PostAsync(toBot, CancellationToken.None);
                    }

                    dialog.Verify(d => d.StartAsync(It.IsAny <IDialogContext>()), Times.Exactly(2));
                    dialog.Verify(d => d.MessageReceived(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()), Times.Exactly(2));
                    dialog.Verify(d => d.Throw(It.IsAny <IDialogContext>(), It.IsAny <IAwaitable <IMessageActivity> >()), Times.Once);
                }
        }
예제 #13
0
        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)
            {
                using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
                {
                    var task  = scope.Resolve <IPostToBot>();
                    var queue = scope.Resolve <Queue <IMessageActivity> >();

                    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);
                    }
                }
            }
        }
예제 #14
0
        protected override IBotData MakeBotData()
        {
            var msg = DialogTestBase.MakeTestMessage();

            return(new DictionaryBotData(new BotIdResolver(msg.Recipient.Id), msg, new CachingBotDataStore_LastWriteWins(new InMemoryDataStore())));
        }
예제 #15
0
        protected override IBotData MakeBotData()
        {
            var msg = DialogTestBase.MakeTestMessage();

            return(new DictionaryBotData(Address.FromActivity(msg), new CachingBotDataStore(new InMemoryDataStore(), CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency)));
        }
예제 #16
0
파일: Script.cs 프로젝트: watercow/HustBot
        public static async Task VerifyScript(ILifetimeScope container, bool proactive, StreamReader stream, Action <string> extraCheck, string[] expected)
        {
            var toBot = DialogTestBase.MakeTestMessage();

            using (var scope = DialogModule.BeginLifetimeScope(container, toBot))
            {
                var    task = scope.Resolve <IPostToBot>();
                var    queue = scope.Resolve <Queue <IMessageActivity> >();
                string input, label;
                Action check = () =>
                {
                    var count = int.Parse(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(ReadLine(stream, out label));
                };
                string result = null;
                var    root   = scope.Resolve <IDialog <object> >().Do(async(context, value) => result = JsonConvert.SerializeObject(await value));
                if (proactive)
                {
                    var loop = root.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();
                }
                else
                {
                    var builder = new ContainerBuilder();
                    builder
                    .RegisterInstance(root)
                    .AsSelf()
                    .As <IDialog <object> >();
                    builder.Update((IContainer)container);
                }
                int current = 0;
                while ((input = ReadLine(stream, out label)) != null)
                {
                    if (input.StartsWith("\""))
                    {
                        input = input.Substring(1, input.Length - 2);
                        Assert.IsTrue(current < expected.Length && input == expected[current++]);
                        toBot.Text = input;
                        try
                        {
                            await task.PostAsync(toBot, CancellationToken.None);

                            check();
                        }
                        catch (Exception e)
                        {
                            Assert.AreEqual(ReadLine(stream, out label), e.Message);
                        }
                    }
                    else if (input.StartsWith("Result:"))
                    {
                        Assert.AreEqual(input.Substring(7), result);
                    }
                }
            }
        }
예제 #17
0
        protected override IBotData MakeBotData()
        {
            var msg = DialogTestBase.MakeTestMessage();

            return(new DictionaryBotData(msg, new MessageBackedStore(msg)));
        }