(#916) fixed missing call to Validate when using CommandConstructorBinder

This commit is contained in:
Nils Andresen 2022-08-17 16:18:13 +02:00 committed by Patrik Svensson
parent 78d841e3dc
commit 0d19ccd8a6
5 changed files with 65 additions and 0 deletions

View File

@ -45,6 +45,13 @@ internal static class CommandConstructorBinder
}
}
// Validate the settings.
var validationResult = settings.Validate();
if (!validationResult.Successful)
{
throw CommandRuntimeException.ValidationFailed(validationResult);
}
return settings;
}
}

View File

@ -0,0 +1,11 @@
namespace Spectre.Console.Tests.Data;
[Description("The turtle command.")]
public class TurtleCommand : AnimalCommand<TurtleSettings>
{
public override int Execute(CommandContext context, TurtleSettings settings)
{
DumpSettings(context, settings);
return 0;
}
}

View File

@ -0,0 +1,7 @@
namespace Spectre.Console.Tests.Data;
public class ReptileSettings : AnimalSettings
{
[CommandOption("-n|-p|--name|--pet-name <VALUE>")]
public string Name { get; set; }
}

View File

@ -0,0 +1,16 @@
namespace Spectre.Console.Tests.Data;
public sealed class TurtleSettings : ReptileSettings
{
public TurtleSettings(string name)
{
Name = name;
}
public override ValidationResult Validate()
{
return Name != "Lonely George"
? ValidationResult.Error("Only 'Lonely George' is valid name for a turtle!")
: ValidationResult.Success();
}
}

View File

@ -54,6 +54,30 @@ public sealed partial class CommandAppTests
});
}
[Fact]
public void Should_Throw_If_Settings_Validation_Fails_On_Settings_With_ctor()
{
// Given
var app = new CommandApp();
app.Configure(config =>
{
config.PropagateExceptions();
config.AddBranch<AnimalSettings>("animal", animal =>
{
animal.AddCommand<TurtleCommand>("turtle");
});
});
// When
var result = Record.Exception(() => app.Run(new[] { "animal", "4", "turtle", "--name", "Klaus" }));
// Then
result.ShouldBeOfType<CommandRuntimeException>().And(e =>
{
e.Message.ShouldBe("Only 'Lonely George' is valid name for a turtle!");
});
}
[Fact]
public void Should_Throw_If_Command_Validation_Fails()
{