-
Notifications
You must be signed in to change notification settings - Fork 95
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #76 from zadykian/feature/params-validation
Parameters validation via attributes
- Loading branch information
Showing
4 changed files
with
158 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using System.ComponentModel.DataAnnotations; | ||
using System.Linq; | ||
using System.Reflection; | ||
|
||
namespace ConsoleAppFramework | ||
{ | ||
/// <summary> | ||
/// Validator of command parameters. | ||
/// </summary> | ||
public interface IParamsValidator | ||
{ | ||
/// <summary> | ||
/// Validate <paramref name="parameters"/> of command based on validation attributes | ||
/// applied to method's parameters. | ||
/// </summary> | ||
ValidationResult? ValidateParameters(IEnumerable<(ParameterInfo Parameter, object? Value)> parameters); | ||
} | ||
|
||
/// <inheritdoc /> | ||
public class ParamsValidator : IParamsValidator | ||
{ | ||
private readonly ConsoleAppOptions options; | ||
|
||
public ParamsValidator(ConsoleAppOptions options) => this.options = options; | ||
|
||
/// <inheritdoc /> | ||
ValidationResult? IParamsValidator.ValidateParameters( | ||
IEnumerable<(ParameterInfo Parameter, object? Value)> parameters) | ||
{ | ||
var invalidParameters = parameters | ||
.Select(tuple => (tuple.Parameter, tuple.Value, Result: Validate(tuple.Parameter, tuple.Value))) | ||
.Where(tuple => tuple.Result != ValidationResult.Success) | ||
.ToImmutableArray(); | ||
|
||
if (!invalidParameters.Any()) | ||
{ | ||
return ValidationResult.Success; | ||
} | ||
|
||
var errorMessage = string.Join(Environment.NewLine, | ||
invalidParameters | ||
.Select(tuple => | ||
$"{options.NameConverter(tuple.Parameter.Name!)} " + | ||
$"({tuple.Value}): " + | ||
$"{tuple.Result!.ErrorMessage}") | ||
); | ||
|
||
return new ValidationResult($"Some parameters have invalid values:{Environment.NewLine}{errorMessage}"); | ||
} | ||
|
||
private static ValidationResult? Validate(ParameterInfo parameterInfo, object? value) | ||
{ | ||
if (value is null) return ValidationResult.Success; | ||
|
||
var validationContext = new ValidationContext(value, null, null); | ||
|
||
var failedResults = GetValidationAttributes(parameterInfo) | ||
.Select(attribute => attribute.GetValidationResult(value, validationContext)) | ||
.Where(result => result != ValidationResult.Success) | ||
.ToImmutableArray(); | ||
|
||
return failedResults.Any() | ||
? new ValidationResult(string.Join("; ", failedResults.Select(res => res?.ErrorMessage))) | ||
: ValidationResult.Success; | ||
} | ||
|
||
private static IEnumerable<ValidationAttribute> GetValidationAttributes(ParameterInfo parameterInfo) | ||
=> parameterInfo | ||
.GetCustomAttributes() | ||
.OfType<ValidationAttribute>(); | ||
} | ||
} |
65 changes: 65 additions & 0 deletions
65
tests/ConsoleAppFramework.Tests/Integration/ValidationAttributeTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
using System; | ||
using System.ComponentModel.DataAnnotations; | ||
using FluentAssertions; | ||
using Xunit; | ||
|
||
// ReSharper disable UnusedMember.Global | ||
// ReSharper disable UnusedParameter.Global | ||
|
||
namespace ConsoleAppFramework.Integration.Test; | ||
|
||
public class ValidationAttributeTests | ||
{ | ||
/// <summary> | ||
/// Try to execute command with invalid option value. | ||
/// </summary> | ||
[Fact] | ||
public void Validate_String_Length_Test() | ||
{ | ||
using var console = new CaptureConsoleOutput(); | ||
|
||
const string optionName = "arg"; | ||
const string optionValue = "too-large-string-value"; | ||
|
||
var args = new[] { nameof(AppWithValidationAttributes.StrLength), $"--{optionName}", optionValue }; | ||
ConsoleApp.Run<AppWithValidationAttributes>(args); | ||
|
||
// Validation should fail, so StrLength command should not be executed. | ||
console.Output.Should().NotContain(AppWithValidationAttributes.Output); | ||
|
||
console.Output.Should().Contain(optionName); | ||
console.Output.Should().Contain(optionValue); | ||
} | ||
|
||
[Fact] | ||
public void Command_With_Multiple_Params() | ||
{ | ||
using var console = new CaptureConsoleOutput(); | ||
|
||
var args = new[] | ||
{ | ||
nameof(AppWithValidationAttributes.MultipleParams), | ||
"--second-arg", "10", | ||
"--first-arg", "invalid-email-address" | ||
}; | ||
|
||
ConsoleApp.Run<AppWithValidationAttributes>(args); | ||
|
||
// Validation should fail, so StrLength command should not be executed. | ||
console.Output.Should().NotContain(AppWithValidationAttributes.Output); | ||
} | ||
|
||
/// <inheritdoc /> | ||
internal class AppWithValidationAttributes : ConsoleAppBase | ||
{ | ||
public const string Output = $"hello from {nameof(AppWithValidationAttributes)}"; | ||
|
||
[Command(nameof(StrLength))] | ||
public void StrLength([StringLength(maximumLength: 8)] string arg) => Console.WriteLine(Output); | ||
|
||
[Command(nameof(MultipleParams))] | ||
public void MultipleParams( | ||
[EmailAddress] string firstArg, | ||
[Range(0, 2)] int secondArg) => Console.WriteLine(Output); | ||
} | ||
} |