Пример #1
0
        private static void Main()
        {
            Console.SetWindowSize(120, 40);
            Console.SetBufferSize(120, 1000);

            var match = new MatchBuilder {
                Games = 10
            };

            match.Teams.Add(
                RobotBuilder.FromFile(@"C:\Program Files (x86)\Robot Battle\fire.prg"),
                RobotBuilder.FromFile(@"C:\Program Files (x86)\Robot Battle\fire.prg"),
                RobotBuilder.FromFile(@"C:\Program Files (x86)\Robot Battle\fire.prg")
                );
            match.Teams.Add(
                RobotBuilder.FromFile(@"C:\Program Files (x86)\Robot Battle\fire.prg"),
                RobotBuilder.FromFile(@"C:\Program Files (x86)\Robot Battle\fire.prg")
                );
            using (var writer = XmlWriter.Create(Console.Out, new XmlWriterSettings {
                Indent = true
            })) {
                match.ToXml().WriteTo(writer);
            }
            Console.WriteLine();
            var runner = new MatchRunner(match);
            var result = runner.Run();

            using (var writer = XmlWriter.Create(Console.Out, new XmlWriterSettings {
                Indent = true
            })) {
                result.ToXml().WriteTo(writer);
            }
            Console.ReadKey();
        }
Пример #2
0
        public static void Main(string[] args)
        {
            // Read the configuration
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
                                .AddEnvironmentVariables()
                                .Build();

            // Build the robot.
            var robot = new RobotBuilder()
                        .UseGitter(configuration["Gitter:Token"])
                        .UseSlack(configuration["Slack:Token"])
                        .AddPart <PingPart>()
                        .UseSerilogConsole(LogEventLevel.Debug)
                        .Build();

            // Start the robot.
            robot.Start();

            // Setup cancellation.
            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                robot.Stop();
            };

            // Wait for termination.
            robot.Join();
        }
Пример #3
0
        public async Task WhenScriptStringIsRun_ActionRespondsToMessage()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .UseBrain <StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            var expectedFirst  = "Bad";
            var expectedSecond = "Good";

            robot.AutoLoadScripts = false;
            var adapter = robot.Adapters.First().Value as StubAdapter;

            robot.LoadScriptFile(Path.GetFullPath(Path.Combine("ScriptFiles", "ScriptRespondBad.csx")));
            robot.AutoLoadScripts = false;
            await robot.Run();

            adapter.SimulateMessage("test1", "mmbot test");

            var firstMessage = (await adapter.GetEmittedMessages(1)).Select(i => i.Item2).First();

            Assert.Equal(1, firstMessage.Count());
            Assert.Equal(expectedFirst, firstMessage.First(), StringComparer.InvariantCultureIgnoreCase);

            robot.LoadScriptFile(Path.GetFullPath(Path.Combine("ScriptFiles", "ScriptRespondGood.csx")));

            adapter.SimulateMessage("test1", "mmbot test");

            var secondMessage = (await adapter.GetEmittedMessages(10)).Select(i => i.Item2).Last();

            Assert.Equal(1, secondMessage.Count());
            Assert.Equal(expectedSecond, secondMessage.First(), StringComparer.InvariantCultureIgnoreCase);
        }
Пример #4
0
        public async Task Auth_CanAddRemoveUsernameToRole()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .UseBrain <StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();
            var adapter = robot.Adapters.First().Value as StubAdapter;

            robot.AutoLoadScripts = false;
            robot.LoadScriptName("Auth");
            await robot.Run();

            Assert.True(robot.ScriptData.Any(d => d.Name == "Auth"));

            adapter.SimulateMessage("test1", "mmbot add test1 to the testgroup role");
            adapter.SimulateMessage("test1", "mmbot remove test1 from the testgroup role");

            var messages = await adapter.GetEmittedMessages(2);

            Assert.Equal(2, messages.Count());
            Assert.True(
                "Got it, test1 is now in the testgroup role" == messages.First().Item2.First() ||
                "test1 is already in the testgroup role" == messages.First().Item2.First());
            Assert.Equal("Got it, test1 is no longer in the testgroup role", messages.Last().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
        }
 public void Construct(RobotBuilder robotBuilder)
 {
     robotBuilder.BuildHead();
     robotBuilder.BuildTorso();
     robotBuilder.BuildArms();
     robotBuilder.BuildLegs();
 }
Пример #6
0
    public void process(string line)
    {
        string[] args = line.Split(' ');
        print(args [0]);
        switch (args[0])
        {
        case "robi":
            /*build robot*/
            RobotBuilder rb    = gameObject.AddComponent <RobotBuilder> ();
            GameObject   robot = rb.ReceiveFile(ApplicationHelper.localDataPath() + args [1]);
            robot.transform.position = new Vector3(float.Parse(args[3]) / 1000, 0, float.Parse(args[4]) / 1000);
            /*run client*/

            break;

        case "world":
            WorldBuilder wb = gameObject.AddComponent <WorldBuilder> ();
            simManager.world      = wb.ReceiveFile(ApplicationHelper.localDataPath() + args [1]);
            simManager.world.name = "world";
            break;

        default:
            break;
        }
    }
Пример #7
0
        public async Task WhenRobotIsReset_ScriptCleanupIsInvoked()
        {
            var loggerConfigurator = new LoggerConfigurator(LogLevel.All);
            var builder            = new RobotBuilder(loggerConfigurator)
                                     .UseAdapter <StubAdapter>()
                                     .UseBrain <StubBrain>()
                                     .DisablePluginDiscovery()
                                     .DisableScriptDiscovery();

            var scriptRunner = new ScriptRunner(loggerConfigurator.GetLogger());

            var robot = builder
                        .Build(c => c.Register <IScriptRunner>(scriptRunner));

            scriptRunner.Initialize(robot);

            robot.LoadScript <StubEchoScript>();

            bool isCleanedUp = false;

            using (scriptRunner.StartScriptProcessingSession(new ScriptSource("TestScript", string.Empty)))
            {
                robot.RegisterCleanup(() => isCleanedUp = true);
            }

            await robot.Reset();

            Assert.True(isCleanedUp);
        }
Пример #8
0
        public async Task WhenRouteCreatedAfterStartup_RouteExistsAfterDelay()
        {
            string expected = "Yo!";

            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .UseRouter <TestNancyRouter>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            robot.AutoLoadScripts = false;

            using (var testNancyRouter = (robot.Router as TestNancyRouter))
            {
                await robot.Run();

                await testNancyRouter.Started.Take(1);

                robot.Router.Get("/test/", context => expected);

                await testNancyRouter.Started.Take(2);

                var server = testNancyRouter.Server;

                var response = await server.HttpClient.GetAsync("/test/");

                Assert.Equal(expected, await response.Content.ReadAsStringAsync());
            }
        }
Пример #9
0
 public void WhenUnconfiguredBuildConstructsNewRobot()
 {
     var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All));
     var robot = builder.Build();
     
     Assert.IsType<Robot>(robot);
 }
Пример #10
0
        public async Task Auth_CanAddRemoveUsernameToRole()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .UseBrain<StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();
            var adapter = robot.Adapters.First().Value as StubAdapter;
            robot.AutoLoadScripts = false;
            robot.LoadScriptName("Auth");
            await robot.Run();

            Assert.True(robot.ScriptData.Any(d => d.Name == "Auth"));

            adapter.SimulateMessage("test1", "mmbot add test1 to the testgroup role");
            adapter.SimulateMessage("test1", "mmbot remove test1 from the testgroup role");

            var messages = await adapter.GetEmittedMessages(2);
            Assert.Equal(2, messages.Count());
            Assert.True(
                "Got it, test1 is now in the testgroup role" == messages.First().Item2.First() ||
                "test1 is already in the testgroup role" == messages.First().Item2.First());
            Assert.Equal("Got it, test1 is no longer in the testgroup role", messages.Last().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
        }
Пример #11
0
        public static async Task <Robot> StartBot(Options options)
        {
            if (options.Test && (options.ScriptFiles == null || !options.ScriptFiles.Any()))
            {
                Console.WriteLine("You need to specify at least one script file to test.");
                return(null);
            }

            var logConfig = CreateLogConfig(options);

            ConfigurePath(options, logConfig.GetLogger());

            var builder = new RobotBuilder(logConfig).WithConfiguration(GetConfiguration(options));

            if (!string.IsNullOrWhiteSpace(options.Name))
            {
                builder.WithName(options.Name);
            }

            if (options.Test)
            {
                builder.DisableScriptDiscovery();
            }

            if (!string.IsNullOrEmpty(options.WorkingDirectory))
            {
                builder.UseWorkingDirectory(options.WorkingDirectory);
            }

            if (options.Watch)
            {
                builder.EnableScriptWatcher();
            }

            Robot robot = null;

            try
            {
                robot = builder.Build();
                if (robot == null)
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                logConfig.GetLogger().Fatal("Could not build robot. Try installing the latest version of any mmbot packages (mmbot.jabbr, mmbot.slack etc) if there was a breaking change.", e);
            }

            await robot.Run().ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    Console.WriteLine(IntroText);
                    Console.WriteLine((options.Test ? "The test console is ready. " : "mmbot is running. ") + "Press CTRL+C at any time to exit");
                }
            });

            return(robot);
        }
Пример #12
0
    /// <summary>
    /// Compares the current devices in the scene with the urdf file and performs adjustments
    /// </summary>
    /// <param name="urdf"></param>
    public void SynchUrdf(string urdf)
    {
        ReportSynch();

        Robot robot = Robot.FromContent(urdf);


        if (!hasUrdfAssetsImported)
        {
            ImportInitialUrdfModel(urdf, robot);
            return;
        }

        robot.filename = assetsRootDirectoryName;

        //we do not return here since we want to apply any possible changes that were passed in the last urdf update.
        //the imported downloads the urdf from the file_server so it might be an old version.
        //If there are no changes to be made - even better.

        RobotBuilder builder = new RobotBuilder();

        builder.Synchronize(robot, RobotRootObject, assetsRootDirectoryName);

        synchronizationCounterWithoutFullRegeneration++;
    }
Пример #13
0
        public async Task WhenMessageIsSentFromScript_AdapterSendIsInvoked()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .UseBrain <StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            var adapter = robot.Adapters.First().Value as StubAdapter;

            robot.LoadScript <StubEchoScript>();

            var expectedMessages = new[]
            {
                Tuple.Create("test1", "Hello Test 1"),
                Tuple.Create("test2", "Hello Test 2"),
                Tuple.Create("test3", "Hello Test 3")
            };
            await robot.Run();

            expectedMessages.ForEach(t => adapter.SimulateMessage(t.Item1, "mmbot " + t.Item2));

            var expectedMessagesValues = expectedMessages.Select(t => string.Concat(t.Item1, t.Item2));

            Console.WriteLine("Expected:");
            Console.WriteLine(string.Join(Environment.NewLine, expectedMessagesValues));
            var actualMessagesValues = adapter.Messages.Select(t => string.Concat(t.Item1.User.Name, t.Item2.FirstOrDefault()));

            Console.WriteLine("Actual:");
            Console.WriteLine(string.Join(Environment.NewLine, actualMessagesValues));

            Assert.True(expectedMessagesValues.SequenceEqual(actualMessagesValues));
        }
Пример #14
0
        public void WhenUnconfiguredBuildConstructsNewRobot()
        {
            var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All));
            var robot   = builder.Build();

            Assert.IsType <Robot>(robot);
        }
Пример #15
0
        public static async Task<Robot> StartBot(Options options)
        {
            if (options.Test && (options.ScriptFiles == null || !options.ScriptFiles.Any()))
            {
                Console.WriteLine("You need to specify at least one script file to test.");
                return null;
            }

            var logConfig = CreateLogConfig(options);
            ConfigurePath(options, logConfig.GetLogger());

            var builder = new RobotBuilder(logConfig).WithConfiguration(GetConfiguration(options));

            if (!string.IsNullOrWhiteSpace(options.Name))
            {
                builder.WithName(options.Name);
            }

            if (options.Test)
            {
                builder.DisableScriptDiscovery();
            }

            if (!string.IsNullOrEmpty(options.WorkingDirectory))
            {
                builder.UseWorkingDirectory(options.WorkingDirectory);
            }

            if (options.Watch)
            {
                builder.EnableScriptWatcher();
            }

            Robot robot = null;

            try
            {
                robot = builder.Build();
            }
            catch (Exception e)
            {
                logConfig.GetLogger().Fatal("Could not build robot. Try installing the latest version of any mmbot packages (mmbot.jabbr, mmbot.slack etc) if there was a breaking change.", e);
            }

            if (robot == null)
            {
                return null;
            }

            await robot.Run().ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    Console.WriteLine(IntroText);
                    Console.WriteLine((options.Test ? "The test console is ready. " : "mmbot is running. ") + "Press CTRL+C at any time to exit");
                }
            });
            return robot;
        }
Пример #16
0
 public static RobotBuilder UseCampfireAdapter(this RobotBuilder builder)
 {
     builder.RegisterAdapter("Campfire", configuration => new CampfireAdapter.CampfireAdapter(
                                 configuration.Settings["CampfireToken"].ToString(),
                                 configuration.Settings["CampfireAccount"].ToString(),
                                 configuration.Settings["CampfireRoomsToJoin"].ToString().Split(new[] { ',', ';' }).Select(int.Parse).ToArray()));
     return(builder);
 }
Пример #17
0
    public void Start()
    {
        m_RobotBuilder = GetComponentInChildren <RobotBuilder>();

        var robot = GetRobot();

        m_RobotBuilder.BuildRobot(robot);
    }
Пример #18
0
 public void CanRegisterCompiledScripts()
 {
     var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                 .UseAdapter<StubAdapter>()
                 .DisablePluginDiscovery()
                 .DisableScriptDiscovery()
                 .Build();
     robot.LoadScripts(typeof(Ping).Assembly);
 }
Пример #19
0
        public void WhenInstantiatedWithoutDictionary_RobotIsConfigured()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .DisablePluginDiscovery()
                        .Build();

            Assert.Null(robot.GetConfigVariable("NothingExpected"));
        }
Пример #20
0
        public void WhenInstantiatedWithoutDictionary_RobotIsConfigured()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .DisablePluginDiscovery()
                        .Build();

            Assert.Null(robot.GetConfigVariable("NothingExpected"));
        }
Пример #21
0
        public async Task WhenMultipleAdaptersAreConfigured_ResponsesAreOnlySentToTheOriginatingAdapter()
        {
            var logConfig = new LoggerConfigurator(LogLevel.Trace);

            logConfig.ConfigureForConsole();
            var robot = new RobotBuilder(logConfig)
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .UseAdapter <StubAdapter>()
                        .UseAdapter <StubAdapter2>()
                        .UseBrain <StubBrain>()
                        .Build();

            robot.AutoLoadScripts = false;

            var adapter1 = robot.Adapters.Values.OfType <StubAdapter>().First();
            var adapter2 = robot.Adapters.Values.OfType <StubAdapter2>().First();

            robot.LoadScript <StubEchoScript>();

            var expectedMessages = new[]
            {
                Tuple.Create("test1", "Hello Test 1"),
                Tuple.Create("test2", "Hello Test 2"),
                Tuple.Create("test3", "Hello Test 3")
            };
            await robot.Run();

            Console.WriteLine("Testing Adapter 1");
            expectedMessages.ForEach(t => adapter1.SimulateMessage(t.Item1, "mmbot " + t.Item2));

            var expectedMessagesValues = expectedMessages.Select(t => string.Concat(t.Item1, t.Item2));

            Console.WriteLine("Expected:");
            Console.WriteLine(string.Join(Environment.NewLine, expectedMessagesValues));
            var actualMessagesValues = adapter1.Messages.Select(t => string.Concat(t.Item1.User.Name, t.Item2.FirstOrDefault()));

            Console.WriteLine("Actual:");
            Console.WriteLine(string.Join(Environment.NewLine, actualMessagesValues));

            Assert.True(expectedMessagesValues.SequenceEqual(actualMessagesValues));
            Assert.Equal(0, adapter2.Messages.Count());

            Console.WriteLine("Testing Adapter 2");
            expectedMessages.ForEach(t => adapter2.SimulateMessage(t.Item1, "mmbot " + t.Item2));


            Console.WriteLine("Expected:");
            Console.WriteLine(string.Join(Environment.NewLine, expectedMessagesValues));
            actualMessagesValues = adapter2.Messages.Select(t => string.Concat(t.Item1.User.Name, t.Item2.FirstOrDefault()));
            Console.WriteLine("Actual:");
            Console.WriteLine(string.Join(Environment.NewLine, actualMessagesValues));

            Assert.True(expectedMessagesValues.SequenceEqual(actualMessagesValues));
            Assert.Equal(3, adapter1.Messages.Count());
        }
Пример #22
0
        public void CanRegisterCompiledScripts()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            robot.LoadScripts(typeof(Ping).Assembly);
        }
Пример #23
0
        public void WhenConfiguredWithConsoleAdapter_CanInstantiateRobot()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
            .UseAdapter<ConsoleAdapter>()
            .DisablePluginDiscovery()
            .DisableScriptDiscovery()
            .Build();

            Assert.True(robot.Adapters.Values.OfType<ConsoleAdapter>().Any());
        }
Пример #24
0
        public void WhenNameNotDefinedBuildNamesNewRobotWithDefaultName()
        {
            string name = "mmbot";

            var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All));
            var robot = builder.Build();

            Assert.IsType<Robot>(robot);
            Assert.Equal(name, robot.Name);
        }
Пример #25
0
        public void WhenNameNotDefinedBuildNamesNewRobotWithDefaultName()
        {
            string name = "mmbot";

            var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All));
            var robot   = builder.Build();

            Assert.IsType <Robot>(robot);
            Assert.Equal(name, robot.Name);
        }
Пример #26
0
        public void WhenConfiguredWithConsoleAdapter_CanInstantiateRobot()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <ConsoleAdapter>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            Assert.True(robot.Adapters.Values.OfType <ConsoleAdapter>().Any());
        }
Пример #27
0
        private static IPi2GoLiteRobot BuildLocalRobot()
        {
            IOperatingSystemService operatingSystemService = new ClassicDotnetOperatingSystemService();
            IGpioPort gpioPort =
                new DmaLinuxGpioPort(operatingSystemService);

            //new SysfsLinuxGpioPort(operatingSystemService);

            return(RobotBuilder.BuildPi2GoLite(operatingSystemService, gpioPort));
        }
Пример #28
0
 private void Awake()
 {
     if (instance == null || instance == this)
     {
         instance = this;
     }
     else
     {
         Destroy(this);
     }
 }
Пример #29
0
        static void Main(string[] args)
        {
            IRobotBuilder oldStyleRobot = new RobotBuilder();
            RobotEngineer robotEngineer = new RobotEngineer(oldStyleRobot);

            robotEngineer.BuildRobot();
            var robot = robotEngineer.GetRobot();

            Console.WriteLine($"Your robot has been built with the following specs.\nHead: {robot.RobotHead}\nTorso: {robot.RobotTorso}\nArms: {robot.RobotArms}\nLegs: {robot.RobotLegs}");
            Console.ReadLine();
        }
Пример #30
0
 public void WhenConfiguredFromDictionary_GetConfigVariableReturnsValue()
 {
     var paramName = "param1";
     var paramValue = "param1Value";
     var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                 .UseAdapter<StubAdapter>()
                 .DisablePluginDiscovery()
                 .WithConfiguration(new Dictionary<string, string>{{"param1", "param1Value"}})
                 .Build();
     Assert.Equal(robot.GetConfigVariable(paramName), paramValue);
 }
Пример #31
0
        private RobotModel CreateDefaultRobot()
        {
            RobotBuilder robotBuilder = new RobotBuilder();

            return(robotBuilder
                   .CreateRobot()
                   .WithHead()
                   .WithLeftArm()
                   .WithRightArm()
                   .Get());
        }
Пример #32
0
        public void WhenWithNameCalledBuildNamesNewRobotWithName()
        {
            string name = "my-shiny-robot";

            var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                          .WithName(name);

            var robot = builder.Build();

            Assert.IsType <Robot>(robot);
            Assert.Equal(name, robot.Name);
        }
Пример #33
0
        public void WhenWithNameCalledBuildNamesNewRobotWithName()
        {
            string name = "my-shiny-robot";
            
            var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                .WithName(name);

            var robot = builder.Build();

            Assert.IsType<Robot>(robot);
            Assert.Equal(name, robot.Name);
        }
Пример #34
0
        public void WhenNameInConfigurationBuildNamesNewRobotFromConfiguration()
        {
            string name = "my-shiny-robot";

            var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                .WithConfiguration(new Dictionary<string, string>{{"MMBOT_ROBOT_NAME", name}});

            var robot = builder.Build();

            Assert.IsType<Robot>(robot);
            Assert.Equal(name, robot.Name);
        }
Пример #35
0
        public async Task CanListen()
        {
            using (var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                               .UseAdapter <StubAdapter>()
                               .UseBrain <StubBrain>()
                               .WithName("mmbot")
                               .DisablePluginDiscovery()
                               .DisableScriptDiscovery()
                               .Build())
            {
                var adapter = robot.Adapters.First().Value as StubAdapter;
                robot.LoadScript <ListenerTest>();
                robot.LoadScript <TextListenerTest>();
                robot.AutoLoadScripts = false;
                await robot.Run();

                Assert.IsType <Listener <TextMessage> >(robot.Listeners[0]);
                Assert.IsType <Listener <TextMessage> >(robot.Listeners[1]);
                Assert.IsType <Listener <TextMessage> >(robot.Listeners[2]);
                Assert.IsType <TextListener>(robot.Listeners[3]);

                adapter.SimulateMessage("tester", "test message");

                var messages = await adapter.GetEmittedMessages(2);

                Assert.Equal(2, messages.Count());
                Assert.Equal("Handled TextMessage without regex", messages.First().Item2.First(),
                             StringComparer.InvariantCultureIgnoreCase);
                Assert.Equal("Handled TextMessage with no other handlers", messages.Skip(1).First().Item2.First(),
                             StringComparer.InvariantCultureIgnoreCase);

                adapter.SimulateMessage("tester", "testregex test message");

                messages = await adapter.GetEmittedMessages(5);

                Assert.Equal(5, messages.Count());
                Assert.Equal("Handled TextMessage with regex", messages.Skip(2).First().Item2.First(),
                             StringComparer.InvariantCultureIgnoreCase);
                Assert.Equal("Handled TextMessage without regex", messages.Skip(3).First().Item2.First(),
                             StringComparer.InvariantCultureIgnoreCase);
                Assert.Equal("Handled TextMessage with no other handlers", messages.Skip(4).First().Item2.First(),
                             StringComparer.InvariantCultureIgnoreCase);

                adapter.SimulateMessage("tester", "mmbot gif me cat");

                messages = await adapter.GetEmittedMessages(7);

                Assert.Equal(7, messages.Count());
                Assert.Equal("Handled TextMessage without regex", messages.Skip(5).First().Item2.First(),
                             StringComparer.InvariantCultureIgnoreCase);
                Assert.Equal("cat", messages.Skip(6).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
            }
        }
Пример #36
0
        public static RobotBuilder UseSerilogConsole(this RobotBuilder builder, LogEventLevel level)
        {
            builder.Services.AddSingleton <ILog>(
                new SerilogLogAdapter(
                    new LoggerConfiguration()
                    .WriteTo.LiterateConsole()
                    .MinimumLevel.Is(level)
                    .Enrich.FromLogContext()
                    .CreateLogger()));

            return(builder);
        }
Пример #37
0
 private static Response<TextMessage> CreateTestResponse()
 {
     var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                 .UseAdapter<StubAdapter>()
                 .UseBrain<StubBrain>()
                 .DisablePluginDiscovery()
                 .DisableScriptDiscovery()
                 .Build();
     var message = new TextMessage(new User("foo", "foo", new string[0], "testRoom", "stubAdapter"), "");
     var matchResult = new MatchResult(false, null);
     return new Response<TextMessage>(robot, message, matchResult);
 }
Пример #38
0
        public void WhenSpeakIsCalledOnInvalidAdapterIdExceptionIsNotThrown()
        {
            // No Asserts.......argh!
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .UseBrain <StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            robot.Speak("InvalidAdapter", "Room", "Foo");
        }
Пример #39
0
        private static Response <TextMessage> CreateTestResponse()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter <StubAdapter>()
                        .UseBrain <StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();
            var message     = new TextMessage(new User("foo", "foo", new string[0], "testRoom", "stubAdapter"), "");
            var matchResult = new MatchResult(false, null);

            return(new Response <TextMessage>(robot, message, matchResult));
        }
Пример #40
0
        public void ShouldBuildRobotWithDefaultValues()
        {
            var robot = new RobotBuilder()
                        .Build();

            const int expectedSpaceSize = RobotBuilder.SpaceSize;
            var       expectedPosition  = new Position(0, 0);
            var       expectedCommands  = new List <ICommand>();

            robot.SpaceSize.Should().Be(expectedSpaceSize);
            robot.Position.Should().Be(expectedPosition);
            robot.Commands.Should().BeEquivalentTo(expectedCommands);
        }
Пример #41
0
        public async Task XmppRobot()
        {
            //enter config values to enable this test
            var config = new Dictionary <string, string>();

            //config.Add("MMBOT_XMPP_HOST", "userver");
            //config.Add("MMBOT_XMPP_CONNECT_HOST", "userver");
            //config.Add("MMBOT_XMPP_USERNAME", "mmbot");
            //config.Add("MMBOT_XMPP_PASSWORD", "password");
            //config.Add("MMBOT_XMPP_CONFERENCE_SERVER", "conference.userver");
            //config.Add("MMBOT_XMPP_ROOMS", "testroom");
            //config.Add("MMBOT_XMPP_LOGROOMS", "logroom");

            if (config.Count() == 0)
            {
                return;
            }

            var logConfig = new LoggerConfigurator(LogLevel.Trace);

            logConfig.AddTraceListener();

            var robot = new RobotBuilder(logConfig)
                        .WithConfiguration(config)
                        .UseAdapter <XmppAdapter>()
                        .Build();

            robot.AutoLoadScripts = false;
            robot.LoadScript <CompiledScripts.Ping>();

            bool robotReady = false;

            robot.On <bool>("RobotReady", result =>
            {
                robotReady = result;
            });

            await robot.Run();

            Assert.True(robotReady);

            int cmdReceived = 0;

            robot.Hear("mmbot", msg => { cmdReceived++; });

            //will wait for two commands
            while (cmdReceived < 2)
            {
                Thread.Sleep(1000);
            }
        }
Пример #42
0
 public void WhenConfiguredFromEnvironmentVariable_GetConfigVariableReturnsValue()
 {
     var paramName = "param1";
     var paramValue = "param1Value";
     Environment.SetEnvironmentVariable(paramName, paramValue);
     using(Disposable.Create(() => Environment.SetEnvironmentVariable(paramName, null)))
     {
         var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                     .UseAdapter<StubAdapter>()
                     .DisablePluginDiscovery()
                     .Build();
         Assert.Equal(robot.GetConfigVariable(paramName), paramValue);
     }
 }
Пример #43
0
 public async Task WhenValueIsRemovedToBrain_GetReturnsDefault()
 {
     var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                 .UseAdapter<StubAdapter>()
                 .UseBrain<StubBrain>()
                 .DisablePluginDiscovery()
                 .Build();
     
     var key = "test1";
     var value = "value1";
     await robot.Brain.Set(key, value);
     await robot.Brain.Remove<string>(key);
     Assert.Null(await robot.Brain.Get<string>(key));
 }
Пример #44
0
        public async Task WhenValueIsAddedToBrain_CanBeRetrievedViaGet()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .UseBrain<StubBrain>()
                        .DisablePluginDiscovery()
                        .Build();
            
            var key = "test1";
            var value = "value1";
            await robot.Brain.Set(key, value);

            Assert.Equal(value, await robot.Brain.Get<string>(key));
        }
Пример #45
0
        public void WhenNameInConfigurationAndWithNameCalledBuildNamesNewRobotWithName()
        {
            string withName = "my-shiny-robot";
            string configuredName = "my-not-so-shint-robot";

            var builder = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                .WithName(withName)
                .WithConfiguration(new Dictionary<string, string> {{"MMBOT_ROBOT_NAME", configuredName}});

            var robot = builder.Build();

            Assert.IsType<Robot>(robot);
            Assert.Equal(withName, robot.Name);
            Assert.NotEqual(configuredName, robot.Name);
        }
Пример #46
0
 public void WhenConfiguredFromDictionary_EnvironmentVariableIsOverriden()
 {
     var paramName = "param1";
     var paramValue = "param1Value";
     var newParamValue = "param1Value_new";
     Environment.SetEnvironmentVariable(paramName, paramValue);
     using (Disposable.Create(() => Environment.SetEnvironmentVariable(paramName, null)))
     {
         var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                     .UseAdapter<StubAdapter>()
                     .DisablePluginDiscovery()
                     .WithConfiguration(new Dictionary<string, string>{{paramName, newParamValue}})
                     .Build();
         Assert.Equal(robot.GetConfigVariable(paramName), newParamValue);
     }
 }
Пример #47
0
        public void WhenConfiguredWithConsoleAdapter_CanInstantiateRobot()
        {
			// This stinks but the test runners in TeamCity and AppVeyor 
			// will cause this test to fail as the Console Adapter is removed
			// when not in an interactive session.
	        if (Environment.UserInteractive)
	        {
		        var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
			        .UseAdapter<ConsoleAdapter>()
			        .DisablePluginDiscovery()
			        .DisableScriptDiscovery()
			        .Build();

		        Assert.True(robot.Adapters.Values.OfType<ConsoleAdapter>().Any());
	        }
        }
Пример #48
0
        public async Task WhenPing_ReceivePong()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .UseBrain<StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();
            
            robot.AutoLoadScripts = false;
            var adapter = robot.Adapters.First().Value as StubAdapter;
            robot.LoadScript<Ping>();
            robot.AutoLoadScripts = false;
            await robot.Run();

            adapter.SimulateMessage("test1", "mmbot ping");

            var firstMessage = (await adapter.GetEmittedMessages(1)).Select(i => i.Item2).First();
            Assert.Equal(1, firstMessage.Count());
            Assert.Equal("pong", firstMessage.First(), StringComparer.InvariantCultureIgnoreCase);
        }
Пример #49
0
        public async Task CanCatchAnyMessage()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .UseBrain<StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            var adapter = robot.Adapters.First().Value as StubAdapter;
            robot.LoadScript<CatchAllTest>();
            robot.AutoLoadScripts = false;
            await robot.Run();

            adapter.SimulateMessage("tester", "test message");

            var messages = await adapter.GetEmittedMessages(1);
            Assert.Equal(1, messages.Count());
            Assert.Equal("Caught msg test message from tester", messages.First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);

            adapter.SimulateEnter("tester");

            messages = await adapter.GetEmittedMessages(2);
            Assert.Equal(2, messages.Count());
            Assert.Equal("Caught msg tester joined testRoom from tester", messages.Skip(1).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);

            adapter.SimulateLeave("tester");

            messages = await adapter.GetEmittedMessages(3);
            Assert.Equal(3, messages.Count());
            Assert.Equal("Caught msg tester left testRoom from tester", messages.Skip(2).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);

            adapter.SimulateTopic("tester", "new topic");

            messages = await adapter.GetEmittedMessages(4);
            Assert.Equal(4, messages.Count());
            Assert.Equal("Caught msg new topic from tester", messages.Skip(3).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
        }
Пример #50
0
        public async Task WhenScriptStringIsRun_ActionRespondsToMessage()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
            .UseAdapter<StubAdapter>()
            .UseBrain<StubBrain>()
            .DisablePluginDiscovery()
            .DisableScriptDiscovery()
            .Build();

            var expectedFirst = "Bad";
            var expectedSecond = "Good";

            robot.AutoLoadScripts = false;
            var adapter = robot.Adapters.First().Value as StubAdapter;
            robot.LoadScriptFile(Path.GetFullPath(Path.Combine("ScriptFiles", "ScriptRespondBad.csx")));
            robot.AutoLoadScripts = false;
            await robot.Run();

            adapter.SimulateMessage("test1", "mmbot test");

            var firstMessage = (await adapter.GetEmittedMessages(1)).Select(i => i.Item2).First();
            Assert.Equal(1, firstMessage.Count());
            Assert.Equal(expectedFirst, firstMessage.First(), StringComparer.InvariantCultureIgnoreCase);

            robot.LoadScriptFile(Path.GetFullPath(Path.Combine("ScriptFiles", "ScriptRespondGood.csx")));

            adapter.SimulateMessage("test1", "mmbot test");

            var secondMessage = (await adapter.GetEmittedMessages(10)).Select(i => i.Item2).Last();
            Assert.Equal(1, secondMessage.Count());
            Assert.Equal(expectedSecond, secondMessage.First(), StringComparer.InvariantCultureIgnoreCase);
        }
Пример #51
0
        public async Task CanListen()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
            .UseAdapter<StubAdapter>()
            .UseBrain<StubBrain>()
            .WithName("mmbot")
            .DisablePluginDiscovery()
            .DisableScriptDiscovery()
            .Build();

            var adapter = robot.Adapters.First().Value as StubAdapter;
            robot.LoadScript<ListenerTest>();
            robot.LoadScript<TextListenerTest>();
            robot.AutoLoadScripts = false;
            await robot.Run();

            Assert.IsType<Listener<TextMessage>>(robot.Listeners[0]);
            Assert.IsType<Listener<TextMessage>>(robot.Listeners[1]);
            Assert.IsType<Listener<TextMessage>>(robot.Listeners[2]);
            Assert.IsType<TextListener>(robot.Listeners[3]);

            adapter.SimulateMessage("tester", "test message");

            var messages = await adapter.GetEmittedMessages(2);
            Assert.Equal(2, messages.Count());
            Assert.Equal("Handled TextMessage without regex", messages.First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
            Assert.Equal("Handled TextMessage with no other handlers", messages.Skip(1).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);

            adapter.SimulateMessage("tester", "testregex test message");

            messages = await adapter.GetEmittedMessages(5);
            Assert.Equal(5, messages.Count());
            Assert.Equal("Handled TextMessage with regex", messages.Skip(2).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
            Assert.Equal("Handled TextMessage without regex", messages.Skip(3).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
            Assert.Equal("Handled TextMessage with no other handlers", messages.Skip(4).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);

            adapter.SimulateMessage("tester", "mmbot gif me cat");

            messages = await adapter.GetEmittedMessages(7);
            Assert.Equal(7, messages.Count());
            Assert.Equal("Handled TextMessage without regex", messages.Skip(5).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
            Assert.Equal("cat", messages.Skip(6).First().Item2.First(), StringComparer.InvariantCultureIgnoreCase);
        }
Пример #52
0
        public async Task WhenMultipleAdaptersAreConfigured_ResponsesAreOnlySentToTheOriginatingAdapter()
        {
            var logConfig = new LoggerConfigurator(LogLevel.Trace);
            logConfig.ConfigureForConsole();
            using(var robot = new RobotBuilder(logConfig)
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .UseAdapter<StubAdapter>()
                        .UseAdapter<StubAdapter2>()
                        .UseBrain<StubBrain>()
                        .Build()){
            
                robot.AutoLoadScripts = false;

                var adapter1 = robot.Adapters.Values.OfType<StubAdapter>().First();
                var adapter2 = robot.Adapters.Values.OfType<StubAdapter2>().First();

                robot.LoadScript<StubEchoScript>();

                var expectedMessages = new[]
                {
                    Tuple.Create("test1", "Hello Test 1"),
                    Tuple.Create("test2", "Hello Test 2"),
                    Tuple.Create("test3", "Hello Test 3")
                };
                await robot.Run();

                Console.WriteLine("Testing Adapter 1");
                expectedMessages.ForEach(t => adapter1.SimulateMessage(t.Item1, "mmbot " + t.Item2));

                var expectedMessagesValues = expectedMessages.Select(t => string.Concat(t.Item1, t.Item2));
                Console.WriteLine("Expected:");
                Console.WriteLine(string.Join(Environment.NewLine, expectedMessagesValues));
                var actualMessagesValues = adapter1.Messages.Select(t => string.Concat(t.Item1.User.Name, t.Item2.FirstOrDefault()));
                Console.WriteLine("Actual:");
                Console.WriteLine(string.Join(Environment.NewLine, actualMessagesValues));

                Assert.True(expectedMessagesValues.SequenceEqual(actualMessagesValues));
                Assert.Equal(0, adapter2.Messages.Count());

                Console.WriteLine("Testing Adapter 2");
                expectedMessages.ForEach(t => adapter2.SimulateMessage(t.Item1, "mmbot " + t.Item2));

            
                Console.WriteLine("Expected:");
                Console.WriteLine(string.Join(Environment.NewLine, expectedMessagesValues));
                actualMessagesValues = adapter2.Messages.Select(t => string.Concat(t.Item1.User.Name, t.Item2.FirstOrDefault()));
                Console.WriteLine("Actual:");
                Console.WriteLine(string.Join(Environment.NewLine, actualMessagesValues));

                Assert.True(expectedMessagesValues.SequenceEqual(actualMessagesValues));
                Assert.Equal(3, adapter1.Messages.Count());
            };
        }
Пример #53
0
        public async Task WhenRobotIsReset_ScriptCleanupIsInvoked()
        {
            var loggerConfigurator = new LoggerConfigurator(LogLevel.All);
            var builder = new RobotBuilder(loggerConfigurator)
                .UseAdapter<StubAdapter>()
                .UseBrain<StubBrain>()
                .DisablePluginDiscovery()
                .DisableScriptDiscovery();

            var scriptRunner = new ScriptRunner(loggerConfigurator.GetLogger());
            
            var robot = builder
                        .Build(c => c.Register<IScriptRunner>(scriptRunner));

            scriptRunner.Initialize(robot);

            robot.LoadScript<StubEchoScript>();

            bool isCleanedUp = false;
            using(scriptRunner.StartScriptProcessingSession(new ScriptSource("TestScript", string.Empty)))
            {
                robot.RegisterCleanup(() => isCleanedUp = true);
            }

            await robot.Reset();

            Assert.True(isCleanedUp);
        }
Пример #54
0
        public async Task WhenRouteCreatedAfterStartup_RouteExistsAfterDelay()
        {
            string expected = "Yo!";

            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .UseRouter<TestNancyRouter>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            robot.AutoLoadScripts = false;

            using (var testNancyRouter = (robot.Router as TestNancyRouter))
            {

                await robot.Run();

                await testNancyRouter.Started.Take(1);

                robot.Router.Get("/test/", context => expected);

                await testNancyRouter.Started.Take(2);

                var server = testNancyRouter.Server;

                var response = await server.HttpClient.GetAsync("/test/");

                Assert.Equal(expected, await response.Content.ReadAsStringAsync());
            }
        }
Пример #55
0
        private async Task<TestNancyRouter> SetupRoute(Action<Robot> setup)
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .UseRouter<TestNancyRouter>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();


            robot.AutoLoadScripts = false;
            
            robot.Router.Start();
            setup(robot);

            await robot.Run();

            return (robot.Router as TestNancyRouter);
        }
Пример #56
0
 public MessageHandlerRoomAuthorization(RobotBuilder robotBuilder, List<IMessageHandler> handlers)
 {
     _robotBuilder = robotBuilder;
     _handlers = handlers;
 }
Пример #57
0
 public void WhenEmitInvokeOn()
 {
     var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                 .UseAdapter<StubAdapter>()
                 .DisablePluginDiscovery()
                 .DisableScriptDiscovery()
                 .Build();
     robot.On<string>("Test", result =>
     {
         var data = result;
         Assert.NotNull(data);
         Assert.Equal(data, "Emitted");
     });
     
     robot.Emit("Test", "Emitted");
 }
Пример #58
0
        public async Task WhenEmitReadyInvokeOn()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();
            robot.AutoLoadScripts = false;
            bool onInvoked = false;
            robot.On<bool>("RobotReady", result =>
            {
                onInvoked = result;
            });

            await robot.Run();
            Assert.True(onInvoked);
        }
Пример #59
0
        public async Task XmppRobot()
        {
            //enter config values to enable this test
            var config = new Dictionary<string, string>();         
            //config.Add("MMBOT_XMPP_HOST", "userver");
            //config.Add("MMBOT_XMPP_CONNECT_HOST", "userver");
            //config.Add("MMBOT_XMPP_USERNAME", "mmbot");
            //config.Add("MMBOT_XMPP_PASSWORD", "password");
            //config.Add("MMBOT_XMPP_CONFERENCE_SERVER", "conference.userver");
            //config.Add("MMBOT_XMPP_ROOMS", "testroom");
            //config.Add("MMBOT_XMPP_LOGROOMS", "logroom");

            if (config.Count() == 0)
                return;

            var logConfig = new LoggerConfigurator(LogLevel.Trace);
            logConfig.AddTraceListener();

            var robot = new RobotBuilder(logConfig)
                        .WithConfiguration(config)
                        .UseAdapter<XmppAdapter>()
                        .Build(); 
            
            robot.AutoLoadScripts = false;
            robot.LoadScript<CompiledScripts.Ping>();

            bool robotReady = false;
            robot.On<bool>("RobotReady", result =>
            {
                robotReady = result;
            });

            await robot.Run();

            Assert.True(robotReady);

            int cmdReceived = 0;
            robot.Hear("mmbot", msg => { cmdReceived++; });

            //will wait for two commands
            while (cmdReceived < 2)
                Thread.Sleep(1000);            
        }
Пример #60
0
        public async Task WhenMessageIsSentFromScript_AdapterSendIsInvoked()
        {
            var robot = new RobotBuilder(new LoggerConfigurator(LogLevel.All))
                        .UseAdapter<StubAdapter>()
                        .UseBrain<StubBrain>()
                        .DisablePluginDiscovery()
                        .DisableScriptDiscovery()
                        .Build();

            var adapter = robot.Adapters.First().Value as StubAdapter;
            robot.LoadScript<StubEchoScript>();
            
            var expectedMessages = new[]
            {
                Tuple.Create("test1", "Hello Test 1"),
                Tuple.Create("test2", "Hello Test 2"),
                Tuple.Create("test3", "Hello Test 3")
            };
            await robot.Run();
            expectedMessages.ForEach(t => adapter.SimulateMessage(t.Item1, "mmbot " +  t.Item2));

            var expectedMessagesValues = expectedMessages.Select(t => string.Concat(t.Item1, t.Item2));
            Console.WriteLine("Expected:");
            Console.WriteLine(string.Join(Environment.NewLine, expectedMessagesValues));
            var actualMessagesValues = adapter.Messages.Select(t => string.Concat(t.Item1.User.Name, t.Item2.FirstOrDefault()));
            Console.WriteLine("Actual:");
            Console.WriteLine(string.Join(Environment.NewLine, actualMessagesValues));

            Assert.True(expectedMessagesValues.SequenceEqual(actualMessagesValues));
        }