public Command ResolveCommand(CommandOptionSet optionSet) { // Get command type var commandType = !optionSet.CommandName.IsNullOrWhiteSpace() ? GetCommandType(optionSet.CommandName) : GetDefaultCommandType(); // Activate command var command = commandType.Activate(); // Set command options foreach (var property in commandType.Options) { // Get option for this property var option = optionSet.GetOptionOrDefault(property.Name, property.ShortName); // If there are any matching options - set value if (option != null) { var convertedValue = _commandOptionConverter.ConvertOption(option, property.Type); property.SetValue(command, convertedValue); } // If the property is required but it's missing - throw else if (property.IsRequired) { throw new CommandResolveException($"Can't resolve command because required property [{property.Name}] is not set."); } } return(command); }
public void ResolveCommand_IsRequired_Test(CommandOptionSet commandOptionSet) { // Arrange var typeProvider = new TypeProvider(typeof(TestCommand)); var optionConverter = new CommandOptionConverter(); var resolver = new CommandResolver(typeProvider, optionConverter); // Act & Assert Assert.Throws <CommandResolveException>(() => resolver.ResolveCommand(commandOptionSet)); }
public void ResolveCommand_Test(CommandOptionSet commandOptionSet, TestCommand expectedCommand) { // Arrange var typeProvider = new TypeProvider(typeof(TestCommand)); var optionConverter = new CommandOptionConverter(); var resolver = new CommandResolver(typeProvider, optionConverter); // Act var command = resolver.ResolveCommand(commandOptionSet) as TestCommand; // Assert Assert.Multiple(() => { Assert.That(command, Is.Not.Null); Assert.That(command.StringOption, Is.EqualTo(expectedCommand.StringOption), nameof(command.StringOption)); Assert.That(command.IntOption, Is.EqualTo(expectedCommand.IntOption), nameof(command.IntOption)); }); }
public void ParseOptions_Test(IReadOnlyList <string> commandLineArguments, CommandOptionSet expectedCommandOptionSet) { // Arrange var parser = new CommandOptionParser(); // Act var optionSet = parser.ParseOptions(commandLineArguments); // Assert Assert.Multiple(() => { Assert.That(optionSet.CommandName, Is.EqualTo(expectedCommandOptionSet.CommandName), "Command name"); Assert.That(optionSet.Options.Count, Is.EqualTo(expectedCommandOptionSet.Options.Count), "Option count"); for (var i = 0; i < optionSet.Options.Count; i++) { Assert.That(optionSet.Options[i].Name, Is.EqualTo(expectedCommandOptionSet.Options[i].Name), $"Option[{i}] name"); Assert.That(optionSet.Options[i].Values, Is.EqualTo(expectedCommandOptionSet.Options[i].Values), $"Option[{i}] values"); } }); }