예제 #1
0
        public void Execute_ShouldReturnError_WhenLoadFails()
        {
            var        console = Container.Resolve <IConsole>();
            var        factory = Container.Resolve <IGitDependFileFactory>();
            string     dir;
            ReturnCode loadCode = ReturnCode.GitRepositoryNotFound;

            factory.Arrange(f => f.LoadFromDirectory(Arg.AnyString, out dir, out loadCode))
            .Returns(null as GitDependFile);

            StringBuilder output = new StringBuilder();

            console.Arrange(c => c.WriteLine(Arg.AnyObject))
            .DoInstead((object obj) =>
            {
                output.AppendLine(obj.ToString());
            });

            var options  = new ConfigSubOptions();
            var instance = new ConfigCommand(options);

            var code = instance.Execute();

            Assert.AreEqual(ReturnCode.GitRepositoryNotFound, code, "Invalid Return Code");
            Assert.AreEqual(string.Empty, output.ToString());
        }
예제 #2
0
        public void ShouldAddConfigurationVariables([Frozen] Mock <IApplicationConfiguration> applicationConfiguration,
                                                    [Frozen] Mock <IAppHarborClient> client,
                                                    [Frozen] Mock <TextWriter> writer,
                                                    ConfigCommand command, string applicationId)
        {
            applicationConfiguration.Setup(x => x.GetApplicationId()).Returns(applicationId);
            var configurationVariables = new List <ConfigurationVariable>
            {
                new ConfigurationVariable {
                    Key = "foo", Value = "bar"
                },
                new ConfigurationVariable {
                    Key = "baz", Value = "qux"
                },
            };

            client.Setup(x => x.GetConfigurationVariables(applicationId)).Returns(configurationVariables);

            command.Execute(new string[0]);

            foreach (var configurationVariable in configurationVariables)
            {
                writer.Verify(x => x.WriteLine("{0} => {1}", configurationVariable.Key, configurationVariable.Value));
            }
        }
예제 #3
0
        public void Execute_ShouldPrintExistingConfig_WhenConfigExistsInGitRepo()
        {
            var        console = Container.Resolve <IConsole>();
            var        factory = Container.Resolve <IGitDependFileFactory>();
            string     dir;
            ReturnCode loadCode = ReturnCode.Success;

            factory.Arrange(f => f.LoadFromDirectory(Arg.AnyString, out dir, out loadCode))
            .Returns(Lib2Config);

            StringBuilder output = new StringBuilder();

            console.Arrange(c => c.WriteLine(Arg.AnyObject))
            .DoInstead((object obj) =>
            {
                output.AppendLine(obj.ToString());
            });

            var options  = new ConfigSubOptions();
            var instance = new ConfigCommand(options);

            var code = instance.Execute();

            Assert.AreEqual(ReturnCode.Success, code, "Invalid Return Code");
            Assert.AreEqual(Lib2Config.ToString() + Environment.NewLine, output.ToString());
        }
예제 #4
0
        public void ConstructorThrowsIfSettingsIsNull()
        {
            // Act and Assert
            var configCommand = new ConfigCommand();

            ExceptionAssert.Throws <InvalidOperationException>(
                () => configCommand.ExecuteCommand(),
                "Property Settings is null.");
        }
        public void Config_Execute_ReturnsEmpty()
        {
            var console = new TestConsole(_output);
            var command = new ConfigCommand(console, (new Mock <ILogger <ConfigCommand> >()).Object);

            var message = command.Execute();

            Assert.Equal("", message);
        }
예제 #6
0
        public void TestEmptyPasswordParameterException() {
            IConfigCommand command = new ConfigCommand() {
                Command = new Command() {
                    CommandType = CommandType.ConnectionQuery
                }
            };

            command.Encrypt("");
        }
예제 #7
0
        public void TestCommandNulledAfterEncryption() {
            IConfigCommand command = new ConfigCommand() {
                Command = new Command() {
                    CommandType = CommandType.ConnectionQuery
                }
            };

            command.Encrypt(TestEncrypt.Password);

            Assert.IsNull(command.Command);
        }
예제 #8
0
        public void RemoveExistingEncryptedValue()
        {
            HostEnvironment.HostInteraction.Settings.SetEncryptedValue("TestSetting", "oldValue");
            var command = new ConfigCommand(HostEnvironment);

            command.Configure(null);

            _ = command.Execute("--setEncrypted TestSetting=".Split(" "));

            Assert.IsFalse(HostEnvironment.HostInteraction.Settings.TryGetValue("TestSetting", out _));
        }
예제 #9
0
        public void SetExistingValue()
        {
            HostEnvironment.HostInteraction.Settings.SetValue("TestSetting", "oldValue");
            var command = new ConfigCommand(HostEnvironment);

            command.Configure(null);

            _ = command.Execute("--set TestSetting=testValue".Split(" "));

            Assert.IsTrue(HostEnvironment.HostInteraction.Settings.TryGetValue("TestSetting", out string value));
            Assert.AreEqual("testValue", value);
        }
예제 #10
0
 private void buttonDown_Click(object sender, EventArgs e)
 {
     if (dataGridViewCommands.SelectedRows.Count > 0 &&
         dataGridViewCommands.SelectedRows[0].Index < dataGridViewCommands.Rows.Count - 1)
     {
         int           selectedIndex = dataGridViewCommands.SelectedRows[0].Index;
         ConfigCommand tempCommand   = ConfigCommands[selectedIndex + 1];
         ConfigCommands[selectedIndex + 1] = selectedCommand;
         ConfigCommands[selectedIndex]     = tempCommand;
         ChangeGridRowSelection(selectedIndex + 1);
     }
 }
예제 #11
0
        static void GetReferencedAbstractMethods(List <ConfigCommandMethod> list, ConfigCommand command)
        {
            if (command is ConfigCommandMethod method)
            {
                list.Add(method);

                foreach (var arg in method.Arguments)
                {
                    GetReferencedAbstractMethods(list, arg);
                }
            }
        }
예제 #12
0
        public void SetNewEncryptedValue()
        {
            Assert.IsFalse(HostEnvironment.HostInteraction.Settings.TryGetValue("TestSetting", out _));
            var command = new ConfigCommand(HostEnvironment);

            command.Configure(null);

            _ = command.Execute("--setEncrypted TestSetting=testValue".Split(" "));

            Assert.IsTrue(HostEnvironment.HostInteraction.Settings.TryGetValue("TestSetting", out string value));
            Assert.AreNotEqual("testValue", value);
        }
예제 #13
0
        public void Validate(ConfigCommand command, Production production)
        {
            var oldProduction = _production;

            try
            {
                _production = production;
                command.Apply(this);
            }
            finally
            {
                _production = oldProduction;
            }
        }
예제 #14
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
            commandService = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            ConfigCommand.Initialize(this);
            initializeCreatePackageCommand();
            initializeClearCacheCommand();
            initializePushPackageCommand();
            initializeCreateNuspecCommand();
            NuGetCommandLineCommand.Initialize(this);
            ContextMenuCommands.Initialize(this);

            ExtensionPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }
예제 #15
0
        public void Execute_WithDeleteFlag_ShouldDeleteFile()
        {
            // Arrange
            string        testPath      = testFileSystem.AllFiles.First();
            ConfigCommand configCommand = new ConfigCommand(false, true, testPath);

            testConfigHandler.Setup(m => m.DoesConfigExist(testPath)).Returns(true);

            // Act
            configCommand.Execute(testConsole, testConfigHandler.Object, testConfig.Object, testPathResolver);

            // Assert
            testConfigHandler.Verify(m => m.DeleteConfig(testPath));
        }
예제 #16
0
        public void Execute_WithOnlyInvalidPathFlag_FileDoesNotExist()
        {
            // Arrange
            string        testPath = "some config that does not exist";
            ConfigCommand command  = new ConfigCommand(false, false, testPath);

            testConfigHandler.Setup(m => m.DoesConfigExist(testPath)).Returns(false);

            // Act
            command.Execute(testConsole, testConfigHandler.Object, testConfig.Object, testPathResolver);

            // Assert
            Assert.IsTrue(testConsole.GetHistory().Contains("does not exist"));
        }
예제 #17
0
        public void Execute_WithDeleteFlag_FileDoesNotExist()
        {
            // Arrange
            string        testPath      = "doesnotexist";
            ConfigCommand configCommand = new ConfigCommand(false, true, testPath);

            testConfigHandler.Setup(m => m.DoesConfigExist(testPath)).Returns(false);

            // Act
            configCommand.Execute(testConsole, testConfigHandler.Object, testConfig.Object, testPathResolver);

            // Assert
            Assert.IsTrue(testConsole.GetHistory().Contains("does not exist", System.StringComparison.OrdinalIgnoreCase));
        }
예제 #18
0
        public void Execute_WithConfigFlag_ShouldCreateFile()
        {
            // Arrange
            const string  testPath      = "config.linker";
            ConfigCommand configCommand = new ConfigCommand(true, false, testPath);

            testConfigHandler.Setup(m => m.DoesConfigExist(testPath)).Returns(false);

            // Act
            configCommand.Execute(testConsole, testConfigHandler.Object, testConfig.Object, testPathResolver);

            // Assert
            testConfigHandler.Verify(m => m.SaveConfig(testConfig.Object, testPath));
        }
예제 #19
0
        public void Execute_WithConfigFlag_FileAlreadyExists()
        {
            // Arrange
            string        testPath      = testFileSystem.AllFiles.First();
            ConfigCommand configCommand = new ConfigCommand(true, false, testPath);

            testConfigHandler.Setup(m => m.DoesConfigExist(testPath)).Returns(true);

            // Act
            configCommand.Execute(testConsole, testConfigHandler.Object, testConfig.Object, testPathResolver);

            // Assert
            Assert.IsTrue(testConsole.GetHistory().Contains("already exists", System.StringComparison.OrdinalIgnoreCase));
        }
예제 #20
0
        public void ExecuteThrowsIfSettingsIsNullSettings()
        {
            // Arrange
            var command = new ConfigCommand()
            {
                Settings = NullSettings.Instance
            };

            command.Set.Add("foo", "bar");

            // Act and Assert
            ExceptionAssert.Throws <InvalidOperationException>(
                () => command.ExecuteCommand(),
                "\"SetValue\" cannot be called on a NullSettings. This may be caused on account of insufficient permissions to read or write to \"%AppData%\\NuGet\\NuGet.config\".");
        }
예제 #21
0
        public void TestEncryptedCanBeDecryptedInMemory() {
            IConfigCommand command = new ConfigCommand() {
                Command = new Command() {
                    CommandType = CommandType.ConnectionQuery
                }
            };

            command.Encrypt(TestEncrypt.Password);

            Assert.IsNull(command.Command);

            command.Decrypt(TestEncrypt.Password);

            Assert.IsNotNull(command.Command);
        }
예제 #22
0
        public void TestEncryptedCanBeDecryptedInMemoryIntegrity() {
            IConfigCommand command = new ConfigCommand() {
                Command = new Command() {
                    CommandType = CommandType.ConnectionQuery
                }
            };

            command.Encrypt(TestEncrypt.Password);

            Assert.IsNull(command.Command);

            command.Decrypt(TestEncrypt.Password);

            Assert.AreEqual(CommandType.ConnectionQuery.ToString(), command.Command.Name);
        }
예제 #23
0
        public void ExecutePrintsNothingIfNoArgumentsAndNoSetPropertiesAreSpecified()
        {
            // Arrange
            var settings = Mock.Of <ISettings>();
            var console  = new MockConsole();
            var command  = new ConfigCommand(settings)
            {
                Console = console
            };

            // Act
            command.ExecuteCommand();

            // Assert
            Assert.Empty(console.Output);
        }
예제 #24
0
        private void AddUserMicrosoftAd(LaunchConfiguration instance, object ou, object user, object password)
        {
            var configSet         = instance.Metadata.Init.ConfigSets.GetConfigSet(ActiveDirectoryConfigSet);
            var createDevOuConfig = configSet.GetConfig(ActiveDirectoryConfig);

            ConfigCommand command = null;

            if (!createDevOuConfig.Commands.ContainsKey("InstallActiveDirectoryTools"))
            {
                command                     = createDevOuConfig.Commands.AddCommand <Command>("InstallActiveDirectoryTools");
                command.Command             = new FnJoinPowershellCommand(FnJoinDelimiter.None, "Add-WindowsFeature RSAT-AD-PowerShell,RSAT-AD-AdminCenter");
                command.WaitAfterCompletion = 0.ToString();
            }

            var adminUserNameFqdn = new FnJoin(FnJoinDelimiter.None,
                                               new ReferenceProperty(ActiveDirectoryBase.DomainAdminUsernameParameterName),
                                               "@",
                                               new ReferenceProperty(ActiveDirectoryBase.DomainFqdnParameterName));


            var addUserCommand = "New-ADUser";

            command         = createDevOuConfig.Commands.AddCommand <Command>(ResourceBase.NormalizeLogicalId($"AddUser{user}"));
            command.Command = new FnJoinPowershellCommand(FnJoinDelimiter.None,
                                                          addUserCommand,
                                                          " -Name ",
                                                          user,
                                                          " -Path '",
                                                          ou,
                                                          "' -Credential (New-Object System.Management.Automation.PSCredential('",
                                                          adminUserNameFqdn,
                                                          "',(ConvertTo-SecureString '",
                                                          new ReferenceProperty(ActiveDirectoryBase.DomainAdminPasswordParameterName),
                                                          "' -AsPlainText -Force)))",
                                                          " -SamAccountName ",
                                                          user,
                                                          " -AccountPassword (ConvertTo-SecureString -AsPlainText '",
                                                          password,
                                                          "' -Force)",
                                                          " -Enabled $true");
            command.Test = new FnJoinPowershellCommand(FnJoinDelimiter.Space,
                                                       "try {Get-ADUser -Identity",
                                                       user,
                                                       ";exit 1} catch {exit 0}");
            command.WaitAfterCompletion = 0.ToString();
        }
예제 #25
0
        public async Task InvokeAsync_Provided_Username_Password_Data_User_NULL_Expected_Result_0()
        {
            _logger.Responses.Clear();
            TestConsole console = new TestConsole();

            const string str      = "randomstringrandomstring";
            Random       r        = new Random();
            string       username = null;
            string       password = new string(str.ToCharArray().OrderBy(s => (r.Next(3) % 2) == 0).ToArray());

            _data.User = null;
            ConfigCommand command = new ConfigCommand(username, password, _store, _logger, _data);

            int result = await command.InvAsync(console);

            Assert.IsTrue(result == 0);
        }
예제 #26
0
        public void Execute_WithOnlyPathFlag_WillPrintTotalLinks()
        {
            // Arrange
            string        testPath = testFileSystem.AllFiles.First();
            ConfigCommand command  = new ConfigCommand(false, false, testPath);

            testLinks.Add(testLinkElements[0]);

            testConfigHandler.Setup(m => m.LoadConfig(testPath)).Returns(testConfig.Object);
            testConfigHandler.Setup(m => m.DoesConfigExist(testPath)).Returns(true);

            // Act
            command.Execute(testConsole, testConfigHandler.Object, testConfig.Object, testPathResolver);

            // Assert
            Assert.IsTrue(testConsole.GetHistory().Contains("Total links: " + testLinks.Count));
        }
예제 #27
0
        private void AddUserSimpleAd(LaunchConfiguration instance, string ou, object user, object password)
        {
            var configSet = instance.Metadata.Init.ConfigSets.GetConfigSet(ActiveDirectoryConfigSet);

            var createDevOuConfig = configSet.GetConfig(ActiveDirectoryConfig);

            const string createUserPath = "c:/cfn/scripts/create-user.ps1";
            const string pstools        = "c:/cfn/tools/pstools";

            if (!createDevOuConfig.Sources.ContainsKey(pstools))
            {
                createDevOuConfig.Sources.Add("c:/cfn/tools/pstools", "https://s3.amazonaws.com/gtbb/software/pstools.zip");
            }


            createDevOuConfig.Files.GetFile(createUserPath).Source = "https://s3.amazonaws.com/gtbb/create-user.ps1";

            ConfigCommand command = null;

            if (!createDevOuConfig.Commands.ContainsKey("InstallActiveDirectoryTools"))
            {
                command                     = createDevOuConfig.Commands.AddCommand <Command>("InstallActiveDirectoryTools");
                command.Command             = new FnJoinPowershellCommand(FnJoinDelimiter.None, "Add-WindowsFeature RSAT-AD-PowerShell,RSAT-AD-AdminCenter");
                command.WaitAfterCompletion = 0.ToString();
            }

            var adminUserNameFqdn = new FnJoin(FnJoinDelimiter.None,
                                               new ReferenceProperty(ActiveDirectoryBase.DomainAdminUsernameParameterName),
                                               "@",
                                               new ReferenceProperty(ActiveDirectoryBase.DomainFqdnParameterName));

            command = createDevOuConfig.Commands.AddCommand <Command>(ResourceBase.NormalizeLogicalId($"AddUser{user}"));

            command.Command = new FnJoinPsExecPowershell(
                new FnJoin(FnJoinDelimiter.None,
                           new ReferenceProperty(ActiveDirectoryBase.DomainNetBiosNameParameterName),
                           "\\",
                           new ReferenceProperty(ActiveDirectoryBase.DomainAdminUsernameParameterName)),
                new ReferenceProperty(ActiveDirectoryBase.DomainAdminPasswordParameterName),
                createUserPath,
                " ",
                user,
                new FnJoin(FnJoinDelimiter.None, "\"", password, "\""));

            command.WaitAfterCompletion = 0.ToString();
        }
예제 #28
0
        public void ReadExistingSetting_ShouldPrintValueOnly()
        {
            HostEnvironment.HostInteraction.Settings.SetValue("TestSetting", "testValue");
            var mockLogger = new Mock <ILogger>();

            mockLogger.Setup(log => log.Log(It.Is <string>(s => s.Equals("testValue", StringComparison.Ordinal)),
                                            It.Is <LogLevel>(l => l == LogLevel.Task)));
            HostEnvironment.Logger = mockLogger.Object;

            var command = new ConfigCommand(HostEnvironment);

            command.Configure(null);

            _ = command.Execute("TestSetting");

            mockLogger.Verify();
        }
예제 #29
0
        /// <summary>
        /// Main the args
        /// </summary>
        /// <param name="args">The args</param>
        /// <returns>A task containing the int</returns>
        public static async Task <int> Main(string[] args)
        {
            // Declare the dotnet-document command
            var documentCommand = new RootCommand("dotnet-document")
            {
                // Add sub commands
                ApplyCommand.Create(HandleApplyAsync),
                ConfigCommand.Create(HandleConfigAsync)
            };

            // Declare a new command line builder
            return(await new CommandLineBuilder(documentCommand)
                   .UseDefaults()
                   .UseExceptionHandler(ExceptionFilter.Handle)
                   .UseMiddleware(MeasureMiddleware.Handle)
                   .Build()
                   .InvokeAsync(args));
        }
예제 #30
0
        public void GetAtCommandTest()
        {
            //string tid, uint dtuId, JObject[] cmdobjs, TaskType type, ATTaskResultConsumer tc
            ATTask           task     = new ATTask(string.Empty, 0, null, TaskType.INSTANT, null);
            ConfigCommand    commadns = task.GetAtCommands(this.cmds);
            List <ATCommand> lst      = new List <ATCommand>();

            lst = commadns.AtCommands;
            Assert.AreEqual("***COMMIT CONFIG***", lst[0].ToATString());
            Assert.AreEqual("AT+SVRCNT=2\r", lst[1].ToATString());
            Assert.AreEqual("AT+IPAD=223.4.212.14\r", lst[2].ToATString());
            Assert.AreEqual("AT+PORT=4050\r", lst[3].ToATString());
            Assert.AreEqual("AT+IPAD2=218.3.150.107\r", lst[4].ToATString());
            Assert.AreEqual("AT+PORT2=5001\r", lst[5].ToATString());
            Assert.AreEqual("AT+MODE=TRNS\r", lst[6].ToATString());
            Assert.AreEqual("AT+BYTEINT=100\r", lst[7].ToATString());
            Assert.AreEqual("AT+RETRY=3\r", lst[8].ToATString());
        }
예제 #31
0
        private void dataGridViewCommands_SelectionChanged(object sender, EventArgs e)
        {
            if (selectedCommandIndex != null)
            {
                if (!ValidateAll())
                {
                    dataGridViewCommands.SelectionChanged -= dataGridViewCommands_SelectionChanged;
                    ChangeGridRowSelection(selectedCommandIndex.Value);
                    dataGridViewCommands.SelectionChanged += dataGridViewCommands_SelectionChanged;
                }
            }

            if (dataGridViewCommands.SelectedRows.Count > 0)
            {
                selectedCommand      = ConfigCommands[dataGridViewCommands.SelectedRows[0].Index];
                selectedCommandIndex = dataGridViewCommands.SelectedRows[0].Index;
                LoadControls();
            }
        }
예제 #32
0
        public void ReadAndWriteInSameInvocation_ShouldFailWithError()
        {
            var command = new ConfigCommand(HostEnvironment);

            command.Configure(null);

            try
            {
                _ = command.Execute("TestSetting --set TestSetting2=testValue".Split(" "));
                Assert.Fail();
            }
            catch (AggregateException ae)
            {
                var ioe = ae.InnerException as InvalidOperationException;
                Assert.IsNotNull(ioe);
                string expected = Resources.Text.ConfigCommand_Error_ConflictingParameters;
                Assert.AreEqual(expected, ioe.Message);
            }
        }
예제 #33
0
        public void ReadNonExistingSetting_ShouldLogError()
        {
            var command = new ConfigCommand(HostEnvironment);

            command.Configure(null);

            try
            {
                _ = command.Execute("TestSetting");
                Assert.Fail();
            }
            catch (AggregateException ae)
            {
                var ioe = ae.InnerException as InvalidOperationException;
                Assert.IsNotNull(ioe);
                string expected = string.Format(Resources.Text.ConfigCommand_Error_KeyNotFound, "TestSetting");
                Assert.AreEqual(expected, ioe.Message);
            }
        }
예제 #34
0
        public async Task InvokeAsync_Provided_Username_Password_Expected_Updated_DataFile()
        {
            _logger.Responses.Clear();
            TestConsole console = new TestConsole();

            const string  str      = "randomstringrandomstring";
            Random        r        = new Random();
            string        username = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());
            string        password = new string(str.ToCharArray().OrderBy(s => (r.Next(3) % 2) == 0).ToArray());
            ConfigCommand command  = new ConfigCommand(username, password, _store, _logger, _data);

            await command.InvAsync(console);

            AppData resultData = _store.Read();

            Assert.IsTrue(resultData.User.UserName == username && resultData.User.Password == password);
            _data.User.UserName = "******";
            _data.User.Password = "******";
            _store.Write(_data);
        }
예제 #35
0
        public void TestEncryptedCanBeDecryptedInMemoryIntegrityWithComplexPassword() {
            const string password = "******";

            IConfigCommand command = new ConfigCommand() {
                Command = new Command() {
                    CommandType = CommandType.ConnectionQuery
                }
            };

            command.Encrypt(password);

            Assert.IsNull(command.Command);

            command.Decrypt(password);

            Assert.AreEqual(CommandType.ConnectionQuery.ToString(), command.Command.Name);
        }