feat: OptionsValidatorBase<TOptions>
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ZB.MOM.WW.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for <see cref="IValidateOptions{TOptions}"/> implementations that removes the
|
||||
/// failure-accumulation plumbing. Override <see cref="Validate(ValidationBuilder, TOptions)"/> and
|
||||
/// use the supplied <see cref="ValidationBuilder"/>; the base aggregates ALL failures and returns
|
||||
/// <see cref="ValidateOptionsResult.Success"/> only when none were recorded.
|
||||
/// </summary>
|
||||
/// <typeparam name="TOptions">The options type being validated.</typeparam>
|
||||
public abstract class OptionsValidatorBase<TOptions> : IValidateOptions<TOptions>
|
||||
where TOptions : class
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public ValidateOptionsResult Validate(string? name, TOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var builder = new ValidationBuilder();
|
||||
Validate(builder, options);
|
||||
return builder.IsValid
|
||||
? ValidateOptionsResult.Success
|
||||
: ValidateOptionsResult.Fail(builder.Failures);
|
||||
}
|
||||
|
||||
/// <summary>Records validation failures for <paramref name="options"/> on <paramref name="builder"/>.</summary>
|
||||
/// <param name="builder">The accumulator to record failures on.</param>
|
||||
/// <param name="options">The options instance to validate.</param>
|
||||
protected abstract void Validate(ValidationBuilder builder, TOptions options);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.Configuration.Tests;
|
||||
|
||||
public sealed class OptionsValidatorBaseTests
|
||||
{
|
||||
private sealed class SampleOptions
|
||||
{
|
||||
public int Port { get; set; }
|
||||
public string? Name { get; set; }
|
||||
}
|
||||
|
||||
private sealed class SampleValidator : OptionsValidatorBase<SampleOptions>
|
||||
{
|
||||
protected override void Validate(ValidationBuilder v, SampleOptions o)
|
||||
{
|
||||
v.Port(o.Port, "Sample:Port");
|
||||
v.Required(o.Name, "Sample:Name");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Success_when_clean()
|
||||
{
|
||||
var r = new SampleValidator().Validate(null, new SampleOptions { Port = 8080, Name = "ok" });
|
||||
Assert.True(r.Succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fails_and_reports_all_failures()
|
||||
{
|
||||
var r = new SampleValidator().Validate(null, new SampleOptions { Port = 0, Name = "" });
|
||||
Assert.True(r.Failed);
|
||||
Assert.Equal(2, r.Failures!.Count());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user