Exemplo n.º 1
0
        public async void RestartPlannerAdd1StoppedModule()
        {
            var factory = new TestCommandFactory();

            IModule   stoppedModule = new TestModule("mod1", "version1", "test", ModuleStatus.Stopped, Config2, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars);
            ModuleSet addStopped    = ModuleSet.Create(stoppedModule);

            IImmutableDictionary <string, IModuleIdentity> moduleIdentities = GetModuleIdentities(new List <IModule>()
            {
                stoppedModule
            });
            var planner = new RestartPlanner(factory);
            var token   = new CancellationToken();

            var addStoppedExecutionList = new List <TestRecordType>
            {
                new TestRecordType(TestCommandType.TestCreate, stoppedModule),
            };
            Plan addStoppedPlan = await planner.PlanAsync(addStopped, ModuleSet.Empty, RuntimeInfo, moduleIdentities);

            var planRunner = new OrderedPlanRunner();
            await planRunner.ExecuteAsync(1, addStoppedPlan, token);

            factory.Recorder.ForEach(r => Assert.Equal(addStoppedExecutionList, r.ExecutionList));
        }
        public void CreateCommandErrorTest()
        {
            var command = TestCommandFactory.CreateCommand("xxx");

            Assert.IsTrue(command.Syntax.HasFlag(TestCommandSyntax.Target));
            Assert.IsFalse(command.Syntax.HasFlag(TestCommandSyntax.Value));
        }
Exemplo n.º 3
0
        public void ExceptionsThrownWhenSettingFixturesProperlyReported()
        {
            var testClassCommand = new TestClassCommand(Reflector.Wrap(typeof(SetFixtureFailureSpy)));

            testClassCommand.ClassStart();

            var method       = testClassCommand.TypeUnderTest.GetMethod("Method");
            var testCommands = TestCommandFactory.Make(testClassCommand, method);

            var methodResult = testCommands.Single().Execute(null);

            // If you get a test failure here, then there's another missing instance of "throw;" where there
            // is a call to RethrowWithNoStackTraceLoss. Specifically, for this test, it's in FixtureCommand.Execute
            // Again, it should look like:
            //
            // catch (TargetInvocationException ex)
            // {
            //     ExceptionUtility.RethrowWithNoStackTraceLoss(ex.InnerException);
            //     throw;  // <---- New line
            // }
            if (!(methodResult is FailedResult))
            {
                throw new ExceptionNotBeingRethrownException("FixtureCommand.Execute");
            }

            Assert.Equal("System.Reflection.TargetInvocationException", ((FailedResult)methodResult).ExceptionType);
        }
Exemplo n.º 4
0
        public async void TestPlanFactoryCommands()
        {
            var factory             = new TestCommandFactory();
            var runtimeInfo         = Mock.Of <IRuntimeInfo>();
            var moduleExecutionList = new List <TestRecordType>
            {
                new TestRecordType(TestCommandType.TestCreate, new TestModule("module1", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image1"), RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestUpdate, new TestModule("module3", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image3"), RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestRemove, new TestModule("module4", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image4"), RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestStart, new TestModule("module5", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image5"), RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestStop, new TestModule("module6", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image6"), RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars)),
            };
            var identity    = new Mock <IModuleIdentity>();
            var commandList = new List <ICommand>
            {
                await factory.CreateAsync(new ModuleWithIdentity(moduleExecutionList[0].Module, identity.Object), runtimeInfo),
                await factory.UpdateAsync(moduleExecutionList[0].Module, new ModuleWithIdentity(moduleExecutionList[1].Module, identity.Object), runtimeInfo),
                await factory.RemoveAsync(moduleExecutionList[2].Module),
                await factory.StartAsync(moduleExecutionList[3].Module),
                await factory.StopAsync(moduleExecutionList[4].Module),
            };
            var plan1      = new Plan(commandList);
            var token      = new CancellationToken();
            var planRunner = new OrderedPlanRunner();
            await planRunner.ExecuteAsync(1, plan1, token);

            Assert.All(commandList,
                       command =>
            {
                var c = command as TestCommand;
                Assert.NotNull(c);
                Assert.True(c.CommandExecuted);
            });
            factory.Recorder.ForEach(r => Assert.Equal(moduleExecutionList, r.ExecutionList));
        }
Exemplo n.º 5
0
        public async void RestartPlannerUpdate1Module()
        {
            var factory = new TestCommandFactory();

            IModule currentModule = new TestModule("mod1", "version1", "test", ModuleStatus.Running, Config1, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars);
            IModule desiredModule = new TestModule("mod1", "version1", "test", ModuleStatus.Running, Config2, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars);

            IImmutableDictionary <string, IModuleIdentity> moduleIdentities = GetModuleIdentities(new List <IModule>()
            {
                desiredModule
            });
            var planner = new RestartPlanner(factory);
            var token   = new CancellationToken();

            ModuleSet currentSet          = ModuleSet.Create(currentModule);
            ModuleSet desiredSet          = ModuleSet.Create(desiredModule);
            var       updateExecutionList = new List <TestRecordType>
            {
                new TestRecordType(TestCommandType.TestStop, currentModule),
                new TestRecordType(TestCommandType.TestUpdate, desiredModule),
                new TestRecordType(TestCommandType.TestStart, desiredModule),
            };
            Plan addPlan = await planner.PlanAsync(desiredSet, currentSet, RuntimeInfo, moduleIdentities);

            var planRunner = new OrderedPlanRunner();
            await planRunner.ExecuteAsync(1, addPlan, token);

            factory.Recorder.ForEach(r => Assert.Equal(updateExecutionList, r.ExecutionList));
        }
Exemplo n.º 6
0
        public void SetsCommandFactory()
        {
            var commandFactory = new TestCommandFactory();
            var options        = (HttpOptions)defaultOptions.WithCommandFactory(x => commandFactory)
                                 .Build();

            options.CommandFactory.Should().Be(commandFactory);
        }
Exemplo n.º 7
0
        public CommandLineApplicationShould()
        {
            _outputWriter   = new TestOutputWriter();
            _commandFactory = new TestCommandFactory();

            _application = new CommandLineApplication(
                _commandFactory,
                _outputWriter);
        }
Exemplo n.º 8
0
        private void DocPaneControl_Load(object sender, EventArgs e)
        {
            this.comboBox1.Items.AddRange(TestCommandFactory.GetCommandNames().ToArray());

            this.webBrowser1.Navigate("about:blank");
            this.webBrowser1.Navigate(Properties.Resources.HelpUrl);
#if DEBUG
            this.webBrowser1.IsWebBrowserContextMenuEnabled = true;
#endif
        }
Exemplo n.º 9
0
        public override bool Validate(TestCommandFactory testCommandFactory)
        {
            var recorded = testCommandFactory.RecordedCommands;
            for (int i = 0; i < recorded.Count; i++)
            {
                Assert.Equal(this.ModuleCommands[i].Command, recorded[i].Item1);
                Assert.Equal(this.ModuleCommands[i].ModuleName, recorded[i].Item2);
            }

            return true;
        }
Exemplo n.º 10
0
        public void Setup()
        {
            _repository = new MockRepository();

            var viewFactory = _repository.StrictMock<IFactory<IView>>();
            _textEditor = _repository.DynamicMock<ITextEditor>();
            viewFactory.Expect(a => a.Create(String.Empty)).Return(_textEditor);
            _app = Concepts.SetupApplication(_repository, viewFactory, _cmdFactory = new TestCommandFactory());
            _textEditor.Expect(a => a.ProcessMissingCommand(null)).IgnoreArguments();

            NavigateToDictionary(_app);
        }
Exemplo n.º 11
0
        public async void TestPlanContinueOnFailure()
        {
            var runtimeInfo         = Mock.Of <IRuntimeInfo>();
            var factory             = new TestCommandFactory();
            var failureFactory      = new TestCommandFailureFactory();
            var moduleExecutionList = new List <TestRecordType>
            {
                new TestRecordType(TestCommandType.TestCreate, new TestModule("module1", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image1"), RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestUpdate, new TestModule("module3", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image3"), RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestRemove, new TestModule("module4", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image4"), RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestStart, new TestModule("module5", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image5"), RestartPolicy.OnUnhealthy, ImagePullPolicy.Never, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVars)),
                new TestRecordType(TestCommandType.TestStop, new TestModule("module6", "version1", "type1", ModuleStatus.Stopped, new TestConfig("image6"), RestartPolicy.OnUnhealthy, ImagePullPolicy.Never, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVars)),
            };
            var identity    = new Mock <IModuleIdentity>();
            var commandList = new List <ICommand>
            {
                await failureFactory.CreateAsync(new ModuleWithIdentity(moduleExecutionList[0].Module, identity.Object), runtimeInfo),
                await factory.CreateAsync(new ModuleWithIdentity(moduleExecutionList[0].Module, identity.Object), runtimeInfo),
                await failureFactory.UpdateAsync(moduleExecutionList[0].Module, new ModuleWithIdentity(moduleExecutionList[1].Module, identity.Object), runtimeInfo),
                await factory.UpdateAsync(moduleExecutionList[0].Module, new ModuleWithIdentity(moduleExecutionList[1].Module, identity.Object), runtimeInfo),
                await failureFactory.RemoveAsync(moduleExecutionList[2].Module),
                await factory.RemoveAsync(moduleExecutionList[2].Module),
                await failureFactory.StartAsync(moduleExecutionList[3].Module),
                await factory.StartAsync(moduleExecutionList[3].Module),
                await failureFactory.StopAsync(moduleExecutionList[4].Module),
                await factory.StopAsync(moduleExecutionList[4].Module),
            };
            var plan1             = new Plan(commandList);
            var token             = default(CancellationToken);
            var planRunner        = new OrderedPlanRunner();
            AggregateException ex = await Assert.ThrowsAsync <AggregateException>(async() => await planRunner.ExecuteAsync(1, plan1, token));

            Assert.True(ex.InnerExceptions.Count == commandList.Count / 2);
            Assert.True(
                commandList.Where(
                    command =>
            {
                var c = command as TestCommand;
                Assert.NotNull(c);
                return(c.CommandExecuted);
            }).Count() == commandList.Count / 2);
            Assert.True(
                commandList.Where(
                    command =>
            {
                var c = command as TestCommand;
                Assert.NotNull(c);
                return(!c.CommandExecuted);
            }).Count() == commandList.Count / 2);

            factory.Recorder.ForEach(r => Assert.Equal(moduleExecutionList, r.ExecutionList));
        }
Exemplo n.º 12
0
        public async void RestartPlannerMinimalTest()
        {
            var factory = new TestCommandFactory();
            var planner = new RestartPlanner(factory);
            var token = new CancellationToken();

            var addExecutionList = new List<TestRecordType>();
            Plan addPlan = await planner.PlanAsync(ModuleSet.Empty, ModuleSet.Empty, RuntimeInfo, ImmutableDictionary<string, IModuleIdentity>.Empty);
            var planRunner = new OrderedPlanRunner();
            await planRunner.ExecuteAsync(1, addPlan, token);

            factory.Recorder.ForEach(r => Assert.Equal(addExecutionList, r.ExecutionList));
        }
Exemplo n.º 13
0
        public void IncludesTimeoutCommandWhenTestCommandSaysTheresATimeout()
        {
            MethodInfo           method       = typeof(TestCommandFactoryTests).GetMethod("PublicTestMethod");
            List <ITestCommand>  testCommands = new List <ITestCommand>();
            StubTestClassCommand classCommand = new StubTestClassCommand();

            testCommands.Add(new StubTestCommand {
                Timeout__Result = 153
            });
            classCommand.EnumerateTestCommands__Result = testCommands;

            List <ITestCommand> result = new List <ITestCommand>(TestCommandFactory.Make(classCommand, Reflector.Wrap(method)));

            Assert.Same(method, classCommand.EnumerateTestCommands_TestMethod.MethodInfo);
            Assert.Equal(testCommands.Count, result.Count);
            Assert.IsType <TimeoutCommand>(result[0]);
        }
Exemplo n.º 14
0
        public async void RestartPlannerRemove1Module()
        {
            var factory = new TestCommandFactory();
            var planner = new RestartPlanner(factory);
            var token = new CancellationToken();

            IModule removeModule = new TestModule("mod1", "version1", "test", ModuleStatus.Running, Config1, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars);
            ModuleSet removeRunning = ModuleSet.Create(removeModule);
            var removeExecutionList = new List<TestRecordType>
            {
                new TestRecordType(TestCommandType.TestStop, removeModule),
                new TestRecordType(TestCommandType.TestRemove, removeModule),
            };
            Plan addPlan = await planner.PlanAsync(ModuleSet.Empty, removeRunning, RuntimeInfo, ImmutableDictionary<string, IModuleIdentity>.Empty);
            var planRunner = new OrderedPlanRunner();
            await planRunner.ExecuteAsync(1, addPlan, token);

            factory.Recorder.ForEach(r => Assert.Equal(removeExecutionList, r.ExecutionList));
        }
Exemplo n.º 15
0
        private void AddCommandWorkbookIfNotExists(Excel.Workbook workbook)
        {
            Excel.Worksheet worksheet = this.GetCommandWorksheet(workbook);

            if (null == worksheet)
            {
                worksheet      = ExcelHelper.WorksheetAdd(workbook);
                worksheet.Name = SeleniumCommandWorksheetName;
            }

            var versionString   = ExcelWorksheetCustomPropertyAccessor.Get(worksheet, SeleniumCommandVersion);
            var commandUpdating = true;

            if (!string.IsNullOrWhiteSpace(versionString))
            {
                var version = new Version(versionString);

                if (App.Context.Version <= version)
                {
                    commandUpdating = false;
                }
            }

#if DEBUG
            commandUpdating = true;
#endif

            if (!commandUpdating)
            {
                return;
            }

            ExcelWorksheetCustomPropertyAccessor.Set(worksheet, SeleniumCommandVersion, App.Context.Version.ToString());
            var commands = TestCommandFactory.GetCommandNames();

            for (int i = 0; i < commands.Count(); i++)
            {
                string command = commands.ElementAt(i).Trim();
                worksheet.Cells[i + 1, 1] = command.Trim();
            }

            worksheet.Visible = Excel.XlSheetVisibility.xlSheetHidden;
        }
Exemplo n.º 16
0
        public void CallsTestClassCommandToGetTestCommandsAndWrapsTheminTimedCommands()
        {
            MethodInfo           method       = typeof(TestCommandFactoryTests).GetMethod("PublicTestMethod");
            List <ITestCommand>  testCommands = new List <ITestCommand>();
            StubTestClassCommand classCommand = new StubTestClassCommand();

            testCommands.Add(new StubTestCommand());
            classCommand.EnumerateTestCommands__Result = testCommands;

            List <ITestCommand> result = new List <ITestCommand>(TestCommandFactory.Make(classCommand, Reflector.Wrap(method)));

            Assert.Same(method, classCommand.EnumerateTestCommands_TestMethod.MethodInfo);
            Assert.Equal(testCommands.Count, result.Count);
            var timedCommand       = Assert.IsType <TimedCommand>(result[0]);
            var captureCommand     = Assert.IsType <ExceptionAndOutputCaptureCommand>(timedCommand.InnerCommand);
            var lifetimeCommand    = Assert.IsType <LifetimeCommand>(captureCommand.InnerCommand);
            var beforeAfterCommand = Assert.IsType <BeforeAfterCommand>(lifetimeCommand.InnerCommand);

            Assert.Same(testCommands[0], beforeAfterCommand.InnerCommand);
        }
Exemplo n.º 17
0
        public void DoesNotIncludeCreationCommandWhenTestCommandSaysNotToCreateInstance()
        {
            MethodInfo           method       = typeof(TestCommandFactoryTests).GetMethod("PublicTestMethod");
            List <ITestCommand>  testCommands = new List <ITestCommand>();
            StubTestClassCommand classCommand = new StubTestClassCommand();
            StubTestCommand      testCommand  = new StubTestCommand();

            testCommand.ShouldCreateInstance__Result = false;
            testCommands.Add(testCommand);
            classCommand.EnumerateTestCommands__Result = testCommands;

            List <ITestCommand> result = new List <ITestCommand>(TestCommandFactory.Make(classCommand, Reflector.Wrap(method)));

            Assert.Same(method, classCommand.EnumerateTestCommands_TestMethod.MethodInfo);
            Assert.Equal(testCommands.Count, result.Count);
            var timedCommand       = Assert.IsType <TimedCommand>(result[0]);
            var captureCommand     = Assert.IsType <ExceptionAndOutputCaptureCommand>(timedCommand.InnerCommand);
            var beforeAfterCommand = Assert.IsType <BeforeAfterCommand>(captureCommand.InnerCommand);

            Assert.Same(testCommands[0], beforeAfterCommand.InnerCommand);
        }
Exemplo n.º 18
0
        public async void RestartPlannerAddModulesWithPriority()
        {
            var factory = new TestCommandFactory();

            IModule module1        = new TestModule("mod1", "version1", "test", ModuleStatus.Running, Config1, RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, 3, DefaultConfigurationInfo, EnvVars);
            IModule updatedModule1 = new TestModule("mod1", "version1", "test", ModuleStatus.Running, Config2, RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, 3, DefaultConfigurationInfo, EnvVars);
            IModule addModule2     = new TestModule("mod2", "version1", "test", ModuleStatus.Running, Config1, RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, 2, DefaultConfigurationInfo, EnvVars);
            IModule addModule3     = new TestModule("mod3", "version1", "test", ModuleStatus.Running, Config1, RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, 1, DefaultConfigurationInfo, EnvVars);

            IImmutableDictionary <string, IModuleIdentity> moduleIdentities = GetModuleIdentities(new List <IModule>()
            {
                module1, addModule2, addModule3
            });

            var planner = new RestartPlanner(factory);
            var token   = default(CancellationToken);

            ModuleSet currentSet    = ModuleSet.Create(module1);
            ModuleSet desiredSet    = ModuleSet.Create(updatedModule1, addModule2, addModule3);
            var       executionList = new List <TestRecordType>
            {
                new TestRecordType(TestCommandType.TestCreate, addModule3),
                new TestRecordType(TestCommandType.TestStart, addModule3),
                new TestRecordType(TestCommandType.TestCreate, addModule2),
                new TestRecordType(TestCommandType.TestStart, addModule2),
                new TestRecordType(TestCommandType.TestStop, module1),
                new TestRecordType(TestCommandType.TestUpdate, updatedModule1),
                new TestRecordType(TestCommandType.TestStart, updatedModule1),
            };
            Plan addPlan = await planner.PlanAsync(desiredSet, currentSet, RuntimeInfo, moduleIdentities);

            var planRunner = new OrderedPlanRunner();
            await planRunner.ExecuteAsync(1, addPlan, token);

            factory.Recorder.ForEach(r => Assert.Equal(executionList, r.ExecutionList));
        }
        private bool IsCommandExists(string name)
        {
            var names = TestCommandFactory.GetCommandNames();

            return(0 < names.Where(i => string.Equals(i, name, StringComparison.OrdinalIgnoreCase)).Count());
        }
Exemplo n.º 20
0
 public abstract bool Validate(TestCommandFactory testCommandFactory);
Exemplo n.º 21
0
        protected async Task AgentExecutionTestAsync(TestConfig testConfig)
        {
            string             sharedAccessKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("test"));
            IConfigurationRoot configRoot      = new ConfigurationBuilder().AddInMemoryCollection(
                new Dictionary <string, string>
            {
                { "DeviceConnectionString", $"Hostname=fakeiothub;Deviceid=test;SharedAccessKey={sharedAccessKey}" }
            }).Build();

            var deploymentConfigInfo = new DeploymentConfigInfo(1, testConfig.DeploymentConfig);

            var configSource = new Mock <IConfigSource>();

            configSource.Setup(cs => cs.Configuration).Returns(configRoot);
            configSource.Setup(cs => cs.GetDeploymentConfigInfoAsync()).ReturnsAsync(deploymentConfigInfo);
            NullReporter reporter = NullReporter.Instance;

            var restartStateStore                = Mock.Of <IEntityStore <string, ModuleState> >();
            var configStore                      = Mock.Of <IEntityStore <string, string> >();
            var deploymentConfigInfoSerde        = Mock.Of <ISerde <DeploymentConfigInfo> >();
            IRestartPolicyManager restartManager = new Mock <IRestartPolicyManager>().Object;

            var environment = new Mock <IEnvironment>();

            environment.Setup(e => e.GetModulesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(testConfig.RuntimeInfo);
            environment.Setup(e => e.GetRuntimeInfoAsync()).ReturnsAsync(UnknownRuntimeInfo.Instance);

            var environmentProvider = new Mock <IEnvironmentProvider>();

            environmentProvider.Setup(ep => ep.Create(It.IsAny <DeploymentConfig>())).Returns(environment.Object);

            var commandFactory = new TestCommandFactory();

            var credential = new ConnectionStringCredentials("fake");
            IDictionary <string, IModuleIdentity> identities = new Dictionary <string, IModuleIdentity>();

            var identity = new Mock <IModuleIdentity>();

            identity.Setup(id => id.Credentials).Returns(credential);
            identity.Setup(id => id.ModuleId).Returns(Constants.EdgeAgentModuleName);
            identities.Add(Constants.EdgeAgentModuleName, identity.Object);

            if (testConfig.DeploymentConfig.SystemModules.EdgeHub.HasValue)
            {
                identity = new Mock <IModuleIdentity>();
                identity.Setup(id => id.Credentials).Returns(credential);
                identity.Setup(id => id.ModuleId).Returns(Constants.EdgeHubModuleName);
                identities.Add(Constants.EdgeHubModuleName, identity.Object);
            }

            foreach (var module in testConfig.DeploymentConfig.Modules)
            {
                identity = new Mock <IModuleIdentity>();
                identity.Setup(id => id.Credentials).Returns(credential);
                identity.Setup(id => id.ModuleId).Returns(module.Key);
                identities.Add(module.Key, identity.Object);
            }

            foreach (var module in testConfig.RuntimeInfo.Modules)
            {
                if (identities.ContainsKey(module.Key))
                {
                    continue;
                }

                identity = new Mock <IModuleIdentity>();
                identity.Setup(id => id.Credentials).Returns(credential);
                identity.Setup(id => id.ModuleId).Returns(module.Key);
                identities.Add(module.Key, identity.Object);
            }

            IImmutableDictionary <string, IModuleIdentity> immutableIdentities = identities.ToImmutableDictionary();
            var moduleIdentityLifecycleManager = new Mock <IModuleIdentityLifecycleManager>();

            moduleIdentityLifecycleManager.Setup(m => m.GetModuleIdentitiesAsync(It.IsAny <ModuleSet>(), It.IsAny <ModuleSet>())).Returns(Task.FromResult(immutableIdentities));
            var availabilityMetric = Mock.Of <IAvailabilityMetric>();

            var store = Mock.Of <IEntityStore <string, ModuleState> >();
            HealthRestartPlanner restartPlanner = new HealthRestartPlanner(commandFactory, store, TimeSpan.FromSeconds(10), restartManager);

            Agent agent = await Agent.Create(
                configSource.Object,
                restartPlanner,
                new OrderedPlanRunner(),
                reporter,
                moduleIdentityLifecycleManager.Object,
                environmentProvider.Object,
                configStore,
                deploymentConfigInfoSerde,
                NullEncryptionProvider.Instance,
                availabilityMetric);

            await agent.ReconcileAsync(CancellationToken.None);

            Assert.True(testConfig.Validator.Validate(commandFactory));
        }
        public string Convert()
        {
            var items    = new List <Item>();
            var xml      = this.GetXml();
            var ns       = xml.Root.Name.Namespace;
            var elements = xml.XPathSelectElements("//strong/a[@name]");

            foreach (var element in elements)
            {
                var item = new Item()
                {
                    Name = element.Attribute("name").Value,
                };

                XElement dt = element.Parent.Parent;
                this.GetArgs(item, dt);

                XElement dd = dt.ElementsAfterSelf().First();
                this.GetArgs2(item, dd);
                this.GetDescription(item, dd);

                var tmps = new List <Item>();
                tmps.Add(item);
                tmps.AddRange(this.GetSubItems(dd, item.Description));

                foreach (var tmp in tmps)
                {
                    var andWaitName = tmp.Name + "AndWait";

                    if (this.IsCommandExists(andWaitName))
                    {
                        items.Add(new Item()
                        {
                            Name        = andWaitName,
                            Target      = item.Target,
                            Value       = item.Value,
                            Description = item.Description,
                        });
                    }
                }

                items.AddRange(tmps);
            }

            var missing = new StringBuilder();

            foreach (var name in TestCommandFactory.GetCommandNames())
            {
                if (0 == items.Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)).Count())
                {
                    missing.AppendLine(name);
                }
            }

            File.WriteAllText(Path.Combine(App.TempDir, "commands-missing.txt"), missing.ToString());


            StringBuilder sb = new StringBuilder();

            foreach (var item in items
                     .Where(i => this.IsCommandExists(i.Name))
                     .OrderBy(i => i.Name))
            {
                var s = @"
<div class=""command"">
<h3 id=""***NAME***"">***NAME***</h3>
<ul>
***TARGET***
***VALUE***
</ul>
<div class=""command-description"">***DESC***</div>
</div>
";

                s = s.Replace("***NAME***", item.Name);

                if (string.IsNullOrWhiteSpace(item.Target))
                {
                    s = s.Replace("***TARGET***", string.Empty);
                }
                else
                {
                    s = s.Replace("***TARGET***", @"<li class=""command-target""><strong>Target</strong> = <span class=""command-target-description"">" + item.Target + "</span></li>");
                }

                if (string.IsNullOrWhiteSpace(item.Value))
                {
                    s = s.Replace("***VALUE***", string.Empty);
                }
                else
                {
                    s = s.Replace("***VALUE***", @"<li class=""command-value""><strong>Value</strong> = <span class=""command-value-description"">" + item.Value + "</span></li>");
                }

                s = s.Replace("***DESC***", item.Description);

                sb.AppendLine(s);
            }

            return(sb.ToString());
        }
Exemplo n.º 23
0
        public async void RestartPlannerAddRemoveUpdate()
        {
            var      factory       = new TestCommandFactory();
            var      token         = new CancellationToken();
            DateTime lastStartTime = DateTime.Parse("2017-08-04T17:52:13.0419502Z", null, DateTimeStyles.RoundtripKind);
            DateTime lastExitTime  = lastStartTime.AddDays(1);

            var currentModules = new List <IModule>
            {
                new TestRuntimeModule("UpdateMod1", "version1", RestartPolicy.OnUnhealthy, "test", ModuleStatus.Running, Config1, 0, "Running", lastStartTime, lastExitTime, 0, DateTime.MinValue, ModuleStatus.Running),
                new TestRuntimeModule("UpdateMod2", "version1", RestartPolicy.OnUnhealthy, "test", ModuleStatus.Running, Config1, 0, "Running", lastStartTime, lastExitTime, 0, DateTime.MinValue, ModuleStatus.Stopped),
                new TestRuntimeModule("RemoveMod1", "version1", RestartPolicy.OnUnhealthy, "test", ModuleStatus.Running, Config1, 0, "Running", lastStartTime, lastExitTime, 0, DateTime.MinValue, ModuleStatus.Running),
                new TestRuntimeModule("RemoveMod2", "version1", RestartPolicy.OnUnhealthy, "test", ModuleStatus.Running, Config1, 0, "Running", lastStartTime, lastExitTime, 0, DateTime.MinValue, ModuleStatus.Stopped)
            };
            var desiredModules = new List <IModule>
            {
                new TestModule("NewMod1", "version1", "test", ModuleStatus.Running, Config1, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars),
                new TestModule("NewMod2", "version1", "test", ModuleStatus.Stopped, Config1, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars),
                new TestModule("UpdateMod1", "version1", "test", ModuleStatus.Running, Config1, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars),
                new TestModule("UpdateMod2", "version1", "test", ModuleStatus.Stopped, Config1, RestartPolicy.OnUnhealthy, DefaultConfigurationInfo, EnvVars)
            };

            IImmutableDictionary <string, IModuleIdentity> moduleIdentities = GetModuleIdentities(desiredModules);
            var planner = new RestartPlanner(factory);

            ModuleSet currentSet          = ModuleSet.Create(currentModules.ToArray());
            ModuleSet desiredSet          = ModuleSet.Create(desiredModules.ToArray());
            var       updateExecutionList = new List <TestRecordType>
            {
                new TestRecordType(TestCommandType.TestStop, currentModules[0]),
                new TestRecordType(TestCommandType.TestStop, currentModules[1]),
                new TestRecordType(TestCommandType.TestStop, currentModules[2]),
                new TestRecordType(TestCommandType.TestStop, currentModules[3]),
                new TestRecordType(TestCommandType.TestRemove, currentModules[2]),
                new TestRecordType(TestCommandType.TestRemove, currentModules[3]),
                new TestRecordType(TestCommandType.TestCreate, desiredModules[0]),
                new TestRecordType(TestCommandType.TestCreate, desiredModules[1]),
                new TestRecordType(TestCommandType.TestStart, desiredModules[0]),
                new TestRecordType(TestCommandType.TestStart, desiredModules[2]),
            };
            Plan addPlan = await planner.PlanAsync(desiredSet, currentSet, RuntimeInfo, moduleIdentities);

            var planRunner = new OrderedPlanRunner();
            await planRunner.ExecuteAsync(1, addPlan, token);

            //Weak confirmation: no assumed order.
            factory.Recorder.ForEach(recorder => Assert.All(updateExecutionList, r => Assert.True(recorder.ExecutionList.Contains(r))));
            factory.Recorder.ForEach(
                recorder =>
            {
                // One way to validate order
                // UpdateMod1
                Assert.True(recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[0])) < recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[8])));
                Assert.True(recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[6])) < recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[9])));
                // UpdateMod2
                Assert.True(recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[1])) < recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[9])));
                // RemoveMod1
                Assert.True(recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[3])) < recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[5])));
                // RemoveMod2
                Assert.True(recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[4])) < recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[6])));
                // AddMod1
                Assert.True(recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[6])) < recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[8])));
                // AddModTrue2
                Assert.True(recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[0])) < recorder.ExecutionList.FindIndex(r => r.Equals(updateExecutionList[6])));
            });
        }