diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index b2f52ee7..70f1f3ee 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using FastEndpoints.Swagger; -using FluentValidation; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Enums.Authorization; @@ -10,10 +9,12 @@ using Lumina.Presentation.Web.Common.Http; using Lumina.Presentation.Web.Common.Localization; using Lumina.Presentation.Web.Common.Security; using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Common.Validation; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization.Routing; @@ -51,14 +52,14 @@ public static class PresentationWebLayerServices public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) { services.AddControllersWithViews() - .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) - .AddDataAnnotationsLocalization() - .AddJsonOptions(jsonOptions => - { - jsonOptions.JsonSerializerOptions.MaxDepth = 256; - jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures - jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); - }); + .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) + .AddDataAnnotationsLocalization() + .AddJsonOptions(jsonOptions => + { + jsonOptions.JsonSerializerOptions.MaxDepth = 256; + jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); // configure the locations where the Razor view engine looks for views and layouts, since the views live under the Core directory services.Configure(razorViewEngineOptions => @@ -97,10 +98,7 @@ public static class PresentationWebLayerServices documentOptions.ShortSchemaNames = true; }); // configure URL-based localization - services.AddLocalization(localizationOptions => - { - localizationOptions.ResourcesPath = "Core/Resources"; - }); + services.AddLocalization(localizationOptions => localizationOptions.ResourcesPath = "Core/Resources"); // resolve the resources of the views that live under the Core/Views directory services.AddSingleton(); @@ -257,8 +255,21 @@ public static class PresentationWebLayerServices sessionOptions.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance }); - // scan the current assembly for validators and register them to the DI container - services.AddValidatorsFromAssemblyContaining(ServiceLifetime.Singleton); + // scan the current assembly for validators and register them as singletons in the DI container + foreach (Type validatorType in typeof(Program).Assembly.GetTypes()) + { + if (validatorType.IsInterface || validatorType.IsAbstract || validatorType.IsGenericTypeDefinition) + continue; + + foreach (Type contract in validatorType.GetInterfaces()) + { + if (contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(Validation.IValidator<>)) + { + services.AddSingleton(contract, validatorType); + break; + } + } + } // handle transient errors like network timeouts or intermittent failures AsyncRetryPolicy retryPolicy = Policy @@ -287,6 +298,7 @@ public static class PresentationWebLayerServices // enable access to the current HTTP context in non-controller classes services.AddHttpContextAccessor(); + services.Configure(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs b/src/Lumina.Presentation.Web/Common/Utilities/OptionsBuilderValidationUtilities.cs similarity index 74% rename from src/Lumina.Presentation.Web/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs rename to src/Lumina.Presentation.Web/Common/Utilities/OptionsBuilderValidationUtilities.cs index 692713ab..38684c4d 100644 --- a/src/Lumina.Presentation.Web/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs +++ b/src/Lumina.Presentation.Web/Common/Utilities/OptionsBuilderValidationUtilities.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; using Lumina.Presentation.Web.Common.Validation; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -10,22 +9,22 @@ namespace Lumina.Presentation.Web.Common.Utilities; /// /// Extension methods for adding configuration related options services to the DI container via . /// -public static class OptionsBuilderFluentValidationUtilities +public static class OptionsBuilderValidationUtilities { /// - /// Extension method to add fluent validation to the options validation pipeline. + /// Extension method to add validation to the options validation pipeline. /// /// The type of options being validated. /// The options builder to add the validation to. /// - /// This method allows validating options of type using a FluentValidation validator registered in the DI container. + /// This method allows validating options of type using a validator registered in the DI container. /// /// The same instance, to allow for chaining. public static OptionsBuilder ValidateFluently(this OptionsBuilder optionsBuilder) where TOptions : class { - // register a singleton instance of IValidateOptions using FluentValidation + // register a singleton instance of IValidateOptions using the validator optionsBuilder.Services.AddSingleton>( - serviceProvider => new FluentValidationOptions(optionsBuilder.Name, serviceProvider.GetRequiredService>())); + serviceProvider => new ValidationOptions(optionsBuilder.Name, serviceProvider.GetRequiredService>())); return optionsBuilder; } -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs new file mode 100644 index 00000000..d0fb3591 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs @@ -0,0 +1,392 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Validation; +using System; +using System.Collections; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Presentation.Web.Common.Utilities; + +/// +/// Validator extension methods for the to define common validation rules. +/// +public static class ValidatorUtilities +{ + /// + /// Defines a validation rule that ensures the integer property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable integer property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the long property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, long valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable long property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, long valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the decimal property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, decimal valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable decimal property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, decimal valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the time span property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, TimeSpan valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the integer property is greater than or equal to the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than or equal to. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => value >= valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable integer property is greater than or equal to the specified value. + /// + /// + /// If the property is , this rule passes. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than or equal to. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, int valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable decimal property is greater than or equal to the specified value. + /// + /// + /// If the property is , this rule passes. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than or equal to. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, decimal valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare); + } + + /// + /// Defines a validation rule that ensures the property is not . + /// + /// + /// This rule checks reference/nullable-value nullness only. Combine with + /// to also reject empty values. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder NotNull(this IRuleBuilder ruleBuilder) + { + return ruleBuilder.Must(value => value is not null); + } + + /// + /// Defines a validation rule that ensures the property is not empty. + /// + /// + /// This rule is type-aware: a is checked for white-space only content, a + /// is checked against , and any is checked for having at least + /// one item. If the property is , this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder NotEmpty(this IRuleBuilder ruleBuilder) + { + return ruleBuilder.Must(value => value switch + { + null => false, + string stringValue => stringValue.Trim().Length > 0, + Guid guidValue => guidValue != Guid.Empty, + IEnumerable enumerable => enumerable.GetEnumerator().MoveNext(), + _ => true + }); + } + + /// + /// Defines a validation rule that ensures the value is a defined member of the specified enumeration type. + /// + /// The type of the request being validated. + /// The type of the enumeration. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum + { + return ruleBuilder.Must(value => Enum.IsDefined(value)); + } + + /// + /// Defines a validation rule that ensures a nullable enum value is either or a defined member of the specified enumeration type. + /// + /// The type of the request being validated. + /// The type of the enumeration. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum + { + return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value)); + } + + /// + /// Defines a validation rule that ensures the string property does not exceed the specified maximum length. + /// + /// + /// If the property is or not a string, this rule passes. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The maximum allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder MaximumLength(this IRuleBuilder ruleBuilder, int maximumLength) + { + return ruleBuilder.Must(value => value is not string stringValue || stringValue.Length <= maximumLength); + } + + /// + /// Defines a validation rule that ensures the string property is at least the specified minimum length. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The minimum allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder MinimumLength(this IRuleBuilder ruleBuilder, int minimumLength) + { + return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength); + } + + /// + /// Defines a validation rule that ensures the string property has exactly the specified length. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The exact allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder Length(this IRuleBuilder ruleBuilder, int length) + { + return ruleBuilder.Must(value => value is string stringValue && stringValue.Length == length); + } + + /// + /// Defines a validation rule that ensures the string property length is within the specified inclusive range. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The minimum allowed length of the property. + /// The maximum allowed length of the property. + /// The current instance for method chaining. + public static IRuleBuilder Length(this IRuleBuilder ruleBuilder, int minimumLength, int maximumLength) + { + return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength && stringValue.Length <= maximumLength); + } + + /// + /// Defines a validation rule that ensures the string property matches the specified regular expression pattern. + /// + /// + /// If the property is or not a string, this rule fails (use + /// to skip optional properties). + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// The regular expression pattern the property must match. + /// The current instance for method chaining. + public static IRuleBuilder Matches(this IRuleBuilder ruleBuilder, string regexPattern) + { + return ruleBuilder.Must(value => value is string stringValue && Regex.IsMatch(stringValue, regexPattern)); + } + + /// + /// Defines a validation rule that ensures the string property matches the regular expression pattern selected from the request instance. + /// + /// + /// If the property is or not a string, this rule fails. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// A function that selects the regular expression pattern to match against from the request instance. + /// The current instance for method chaining. + public static IRuleBuilder Matches(this IRuleBuilder ruleBuilder, Func regexPatternSelector) + { + return ruleBuilder.Must((instance, value) => value is string stringValue && Regex.IsMatch(stringValue, regexPatternSelector(instance))); + } + + /// + /// Defines a validation rule that ensures the integer property is within the specified inclusive range. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, int minimumValue, int maximumValue) + { + return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue); + } + + /// + /// Defines a validation rule that ensures the nullable integer property is within the specified inclusive range. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, int minimumValue, int maximumValue) + { + return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue)); + } + + /// + /// Defines a validation rule that ensures the unsigned short property is within the specified inclusive range. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, ushort minimumValue, ushort maximumValue) + { + return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue); + } + + /// + /// Defines a validation rule that ensures the character property is within the specified inclusive range. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, char minimumValue, char maximumValue) + { + return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue); + } + + /// + /// Defines a validation rule that ensures the long property is within the specified inclusive range. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The minimum allowed value of the property. + /// The maximum allowed value of the property. + /// The current instance for method chaining. + public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, long minimumValue, long maximumValue) + { + return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue); + } + + /// + /// Defines a validation rule that ensures the property is equal to another property of the request. + /// + /// The type of the request being validated. + /// The type of the property being validated. + /// The rule builder instance. + /// A function that selects the property the validated property must equal. + /// The current instance for method chaining. + public static IRuleBuilder Equal(this IRuleBuilder ruleBuilder, Func comparisonSelector) + { + return ruleBuilder.Must((instance, value) => Equals(value, comparisonSelector(instance))); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/AbstractValidator.cs b/src/Lumina.Presentation.Web/Common/Validation/AbstractValidator.cs new file mode 100644 index 00000000..db974619 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validation/AbstractValidator.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.Validation; + +/// +/// Base class for creating validators for a specific type. +/// +/// The type of the instance to be validated. +public abstract class AbstractValidator : IValidator +{ + private readonly List> _rules = []; + + /// + /// Defines a validation rule for a specific property on the request being validated. + /// + /// The type of the property being validated. + /// A function that selects the property to validate from the request instance. + /// An instance to configure the rule fluently. + public IRuleBuilder RuleFor(Func propertySelector) + { + ValidationRule rule = new(propertySelector); + _rules.Add(rule); + return rule; + } + + /// + /// Defines a validation rule that is evaluated against each item within a collection property on the request being validated. + /// + /// The type of the items in the collection being validated. + /// A function that selects the collection to validate from the request instance. + /// An instance to configure the per-item rule fluently. + public IRuleBuilder RuleForEach(Func?> collectionSelector) + { + ValidationRuleForEach rule = new(collectionSelector); + _rules.Add(rule); + return rule; + } + + /// + /// Validates the specified request instance against all defined rules. + /// + /// The request instance to validate. + /// A list of validation errors. If the instance is valid, the list will be empty. + public List Validate(TRequest instance) + { + List errors = []; + + foreach (IValidationRule rule in _rules) + errors.AddRange(rule.Validate(instance)); + + return errors; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/IRuleBuilder.cs b/src/Lumina.Presentation.Web/Common/Validation/IRuleBuilder.cs new file mode 100644 index 00000000..4c892926 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validation/IRuleBuilder.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using System; +#endregion + +namespace Lumina.Presentation.Web.Common.Validation; + +/// +/// Provides a fluent API for building validation rules for a specific type. +/// +/// The type of the instance being validated. +/// The type of the specific property on the instance that the rule applies to. +public interface IRuleBuilder +{ + /// + /// Specifies a condition that the property must satisfy to be considered valid. + /// + /// A function to test the property value. + /// The current instance for method chaining. + IRuleBuilder Must(Func predicate); + + /// + /// Specifies a condition that both the request instance and the property value must satisfy to be considered valid. + /// + /// A function to test the request instance together with the property value. + /// The current instance for method chaining. + IRuleBuilder Must(Func predicate); + + /// + /// Specifies a condition that must be met for the validation rule to be executed. + /// + /// A function evaluating the request instance. + /// The current instance for method chaining. + IRuleBuilder When(Func condition); + + /// + /// Specifies a custom object to be returned when the validation fails. + /// + /// The specific error to return upon failure. + /// The current instance for method chaining. + IRuleBuilder WithError(Error error); + + /// + /// Defines nested validation rules for the complex property being validated. + /// + /// An action used to configure the inline validator for the property. + /// The current instance for method chaining. + IRuleBuilder ChildRules(Action> configure); +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/IValidationRule.cs b/src/Lumina.Presentation.Web/Common/Validation/IValidationRule.cs new file mode 100644 index 00000000..498df76c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validation/IValidationRule.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.Validation; + +/// +/// Interface for triggering validator evaluation. +/// +/// The type of the instance being evaluated. +internal interface IValidationRule +{ + /// + /// Evaluates the validation rule against the specified request instance. + /// + /// The request instance to validate. + /// The s produced by this rule; empty if the rule passes. + IEnumerable Validate(TRequest instance); +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/IValidator.cs b/src/Lumina.Presentation.Web/Common/Validation/IValidator.cs new file mode 100644 index 00000000..01e357d4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validation/IValidator.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.Validation; + +/// +/// Interface for validating instances of a specific type. +/// +/// The type of the instance to be validated. +public interface IValidator +{ + /// + /// Validates the specified request instance against the defined rules. + /// + /// The request instance to validate. + /// A list of validation errors. If the instance is valid, the list will be empty. + List Validate(TRequest instance); +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/InlineValidator.cs b/src/Lumina.Presentation.Web/Common/Validation/InlineValidator.cs new file mode 100644 index 00000000..9b49422e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validation/InlineValidator.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +#endregion + +namespace Lumina.Presentation.Web.Common.Validation; + +/// +/// Concrete used to declare validation rules inline for nested complex properties. +/// +/// The type of the instance to be validated. +public class InlineValidator : AbstractValidator +{ +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs b/src/Lumina.Presentation.Web/Common/Validation/ValidationOptions.cs similarity index 71% rename from src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs rename to src/Lumina.Presentation.Web/Common/Validation/ValidationOptions.cs index 65dd9627..d1632065 100644 --- a/src/Lumina.Presentation.Web/Common/Validation/FluentValidationOptions.cs +++ b/src/Lumina.Presentation.Web/Common/Validation/ValidationOptions.cs @@ -1,17 +1,18 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; +using Lumina.Presentation.Web.Common.Primitives; using Microsoft.Extensions.Options; using System; +using System.Collections.Generic; using System.Linq; #endregion namespace Lumina.Presentation.Web.Common.Validation; /// -/// Provides options for fluent validation of a specific options type. +/// Provides options validation for a specific options type using the validation framework. /// /// The type of options being validated. -public class FluentValidationOptions : IValidateOptions where TOptions : class +public class ValidationOptions : IValidateOptions where TOptions : class { private readonly IValidator _validator; @@ -21,11 +22,11 @@ public class FluentValidationOptions : IValidateOptions wher public string? Name { get; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The name of the options being validated. This can be . /// The validator instance used to validate the options. - public FluentValidationOptions(string? name, IValidator validator) + public ValidationOptions(string? name, IValidator validator) { Name = name; _validator = validator; @@ -45,15 +46,14 @@ public class FluentValidationOptions : IValidateOptions wher ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null - FluentValidation.Results.ValidationResult validationResult = _validator.Validate(options); // validate the options using the validator + List validationResult = _validator.Validate(options); // validate the options using the validator // return a response based on the validation result - if (validationResult.IsValid) + if (validationResult.Count == 0) return ValidateOptionsResult.Success; // if the validation fails, collect the error messages - string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") - .ToArray(); + string[] errors = [.. validationResult.Select(error => $"Options validation failed for '{error.Code}' with error: '{error.Description}'")]; // and return them with a failure result return ValidateOptionsResult.Fail(errors); diff --git a/src/Lumina.Presentation.Web/Common/Validation/ValidationRule.cs b/src/Lumina.Presentation.Web/Common/Validation/ValidationRule.cs new file mode 100644 index 00000000..5ee5d892 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validation/ValidationRule.cs @@ -0,0 +1,156 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.Validation; + +/// +/// Defines a validation rule that evaluates a specific property of an instance. +/// +/// The type of the instance being validated. +/// The type of the specific property on the instance that the rule applies to. +internal sealed class ValidationRule : IValidationRule, IRuleBuilder +{ + private readonly Func _propertySelector; + + // Predicates and their errors are kept in two parallel lists (rather than a single list of tuples) + // so that Must() can append cheaply and WithError() can patch the *last* entry by index, without + // having to rebuild a composite struct each time. + private readonly List> _predicates = []; + private readonly List _predicateErrors = []; + + // instance-aware predicates get their own separate pair of lists instead of being merged into the + // lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty). + // Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape. + private readonly List> _instanceAwarePredicates = []; + private readonly List _instanceAwarePredicateErrors = []; + + private Error currentError = Error.Validation(); + private Func? condition; + + // Tracks which list WithError() should patch, since it doesn't know on its own whether the + // most recent Must() call went to the plain-predicate list or the instance-aware list. + private bool lastAddedPredicateIsInstanceAware; + + private AbstractValidator? _childValidator; + + /// + /// Initializes a new instance of the class. + /// + /// A function that extracts the property value from the request instance. + public ValidationRule(Func propertySelector) + { + _propertySelector = propertySelector; + } + + /// + /// Adds a condition that the property must satisfy to be considered valid. + /// + /// A function to test the property value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + _predicates.Add(predicate); + // Every predicate is paired with whatever error is "current" at the time it's added, so that a + // subsequent WithError() call has something concrete to overwrite via index lookup. + _predicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = false; + return this; + } + + /// + /// Adds a condition that the request instance together with the property must satisfy to be considered valid. + /// + /// A function to test the request instance together with the property value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + // This overload exists for cross-field rules (e.g. "EndDate must be after StartDate") where + // the check can't be expressed from the property value alone and needs the whole request. + _instanceAwarePredicates.Add(predicate); + _instanceAwarePredicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = true; + return this; + } + + /// + /// Specifies a condition that must be met for the validation rule to be executed. + /// + /// A function evaluating the request instance. + /// The current instance for method chaining. + public IRuleBuilder When(Func condition) + { + this.condition = condition; + return this; + } + + /// + /// Specifies a custom object to be returned when the validation fails. + /// + /// The specific error to return upon failure. + /// The current instance for method chaining. + public IRuleBuilder WithError(Error error) + { + // Callers might pass in an error created with the wrong factory (e.g. Error.NotFound()) by mistake. + // Rebuilding it as Error.Validation() here guarantees every error surfaced by this class is + // consistently typed as a validation error, regardless of what the caller supplied. + Error validationError = Error.Validation(description: error.Description); + currentError = validationError; + + // WithError() is meant to apply to the predicate that was *just* added via Must(), not to all + // predicates registered so far. Since Must() can target either parallel-list pair, we use the + // flag set by the last Must() call to figure out which list's last slot to overwrite. + if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0) + _instanceAwarePredicateErrors[^1] = validationError; + else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + _predicateErrors[^1] = validationError; + return this; + } + + /// + /// Defines nested validation rules for the complex property being validated. + /// + /// An action used to configure the inline validator for the property. + /// The current instance for method chaining. + public IRuleBuilder ChildRules(Action> configure) + { + // Lets a rule delegate to a fully separate validator for a complex nested object (e.g. validating + // an Address property's own fields) instead of forcing every nested check to be flattened into + // Must() predicates on this rule. + InlineValidator childValidator = new(); + configure(childValidator); + _childValidator = childValidator; + return this; + } + + /// + /// Evaluates all configured predicates against the specified request instance. + /// + /// The request instance to validate. + /// The of every predicate that fails; empty if the rule passes. + public IEnumerable Validate(TRequest instance) + { + // evaluate the condition first, if it returns false, skip validation entirely. + if (condition is not null && !condition(instance)) + yield break; + + TProperty value = _propertySelector(instance); + + // Deliberately does NOT stop at the first failure: every failing predicate contributes its own error, + // so a caller sees the full set of problems for // this property in one pass instead of having to fix + // and resubmit one error at a time. + for (int index = 0; index < _predicates.Count; index++) + if (!_predicates[index](value)) + yield return _predicateErrors[index]; + + for (int index = 0; index < _instanceAwarePredicates.Count; index++) + if (!_instanceAwarePredicates[index](instance, value)) + yield return _instanceAwarePredicateErrors[index]; + + if (_childValidator is not null && value is not null) + foreach (Error childError in _childValidator.Validate(value)) + yield return childError; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs b/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs new file mode 100644 index 00000000..22822f7c --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.Validation; + +/// +/// Defines a validation rule that evaluates each item within a collection property of an instance. +/// +/// The type of the instance being validated. +/// The type of the items in the collection that the rule applies to. +internal sealed class ValidationRuleForEach : IValidationRule, IRuleBuilder +{ + private readonly Func?> _collectionSelector; + private readonly List> _predicates = []; + private readonly List _predicateErrors = []; + private readonly List> _instanceAwarePredicates = []; + private readonly List _instanceAwarePredicateErrors = []; + private Error currentError = Error.Validation(); + private Func? condition; + private bool lastAddedPredicateIsInstanceAware; + private AbstractValidator? _childValidator; + + /// + /// Initializes a new instance of the class. + /// + /// A function that extracts the collection to iterate from the request instance. + public ValidationRuleForEach(Func?> collectionSelector) + { + _collectionSelector = collectionSelector; + } + + /// + /// Adds a condition that each item in the collection must satisfy to be considered valid. + /// + /// A function to test each item value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + _predicates.Add(predicate); + _predicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = false; + return this; + } + + /// + /// Adds a condition that the request instance together with each item must satisfy to be considered valid. + /// + /// A function to test the request instance together with each item value. + /// The current instance for method chaining. + public IRuleBuilder Must(Func predicate) + { + _instanceAwarePredicates.Add(predicate); + _instanceAwarePredicateErrors.Add(currentError); + lastAddedPredicateIsInstanceAware = true; + return this; + } + + /// + /// Specifies a condition that must be met for the validation rule to be executed. + /// + /// A function evaluating the request instance. + /// The current instance for method chaining. + public IRuleBuilder When(Func condition) + { + this.condition = condition; + return this; + } + + /// + /// Specifies a custom object to be returned when the validation fails. + /// + /// The specific error to return upon failure. + /// The current instance for method chaining. + public IRuleBuilder WithError(Error error) + { + // validation rules always produce validation errors, regardless of the error type of the source error + Error validationError = Error.Validation(description: error.Description); + currentError = validationError; + if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0) + _instanceAwarePredicateErrors[^1] = validationError; + else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + _predicateErrors[^1] = validationError; + return this; + } + + /// + /// Defines nested validation rules for each item of the collection being validated. + /// + /// An action used to configure the inline validator for each item. + /// The current instance for method chaining. + public IRuleBuilder ChildRules(Action> configure) + { + InlineValidator childValidator = new(); + configure(childValidator); + _childValidator = childValidator; + return this; + } + + /// + /// Evaluates all configured predicates against each item in the collection. + /// + /// The request instance to validate. + /// One per failing predicate, per item; empty if every item passes. + public IEnumerable Validate(TRequest instance) + { + // evaluate the condition first, if it returns false, skip validation entirely. + if (condition is not null && !condition(instance)) + yield break; + + IEnumerable? collection = _collectionSelector(instance); + if (collection is null) + yield break; + + foreach (TItem item in collection) + { + for (int index = 0; index < _predicates.Count; index++) + if (!_predicates[index](item)) + yield return _predicateErrors[index]; + + for (int index = 0; index < _instanceAwarePredicates.Count; index++) + if (!_instanceAwarePredicates[index](instance, item)) + yield return _instanceAwarePredicateErrors[index]; + + if (_childValidator is not null && item is not null) + foreach (Error childError in _childValidator.Validate(item)) + yield return childError; + } + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsDtoValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsDtoValidator.cs new file mode 100644 index 00000000..dfd44afb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsDtoValidator.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Utilities; +using Lumina.Presentation.Web.Common.Validation; +using System; +using System.Buffers.Text; +#endregion + +namespace Lumina.Presentation.Web.Common.Validators; + +/// +/// Validates the needed validation rules for the EncryptionSettings application configuration settings section. +/// +public class EncryptionSettingsDtoValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public EncryptionSettingsDtoValidator() + { + RuleFor(settings => settings.SecretKey) + .NotEmpty() + .WithError(Error.Validation(description: "Encryption secret key cannot be empty!")) + .Must(secretKey => Base64.IsValid(secretKey.AsSpan())) + .WithError(Error.Validation(description: "Encryption secret key must be a base64 string!")); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs deleted file mode 100644 index d08fbd42..00000000 --- a/src/Lumina.Presentation.Web/Common/Validators/EncryptionSettingsModelValidator.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentValidation; -using Lumina.Presentation.Web.Common.DTO.Configuration; -using System; -using System.Buffers.Text; -#endregion - -namespace Lumina.Presentation.Web.Common.Validators; - -/// -/// Validates the needed validation rules for the EncryptionSettings application configuration settings section. -/// -public class EncryptionSettingsModelValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public EncryptionSettingsModelValidator() - { - RuleFor(x => x.SecretKey) - .NotEmpty().WithMessage("Encryption secret key cannot be empty!") - .Must(value => Base64.IsValid(value.AsSpan())).WithMessage("Encryption secret key must be a base64 string!"); - } -} diff --git a/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationDtoValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationDtoValidator.cs new file mode 100644 index 00000000..8ecc4b14 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationDtoValidator.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Utilities; +using Lumina.Presentation.Web.Common.Validation; +#endregion + +namespace Lumina.Presentation.Web.Common.Validators; + +/// +/// Validates the needed validation rules for the ServerConfiguration application configuration settings section. +/// +public class ServerConfigurationDtoValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ServerConfigurationDtoValidator() + { + RuleFor(configuration => configuration.BaseAddress) + .NotEmpty() + .WithError(Error.Validation(description: "Base address cannot be empty!")); + + RuleFor(configuration => configuration.Port) + .InclusiveBetween((ushort)0, (ushort)65535) + .WithError(Error.Validation(description: "Port number must be between 0 and 65535!")); + + RuleFor(configuration => configuration.ApiVersion) + .InclusiveBetween((char)0, (char)255) + .WithError(Error.Validation(description: "API version must be between 0 and 255!")); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationModelValidator.cs b/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationModelValidator.cs deleted file mode 100644 index 8d8281f8..00000000 --- a/src/Lumina.Presentation.Web/Common/Validators/ServerConfigurationModelValidator.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentValidation; -using Lumina.Presentation.Web.Common.DTO.Configuration; -#endregion - -namespace Lumina.Presentation.Web.Common.Validators; - -/// -/// Validates the needed validation rules for the ServerConfiguration application configuration settings section. -/// -public class ServerConfigurationModelValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public ServerConfigurationModelValidator() - { - RuleFor(x => x.BaseAddress).NotEmpty().WithMessage("Base address cannot be empty!"); - RuleFor(x => x.Port).InclusiveBetween((ushort)0, (ushort)65535).WithMessage("Port number must be between 0 and 65535!"); - RuleFor(x => x.ApiVersion).InclusiveBetween((char)0, (char)255).WithMessage("API version must be between 0 and 255!"); - } -} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index c4010b22..34a7ce11 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -21,8 +21,6 @@ - - diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Setup/ValidatorTestExtensions.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Setup/ValidatorTestExtensions.cs new file mode 100644 index 00000000..aed023cc --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Setup/ValidatorTestExtensions.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Validation; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Setup; + +/// +/// Validator extension methods for for unit tests. +/// +[ExcludeFromCodeCoverage] +public static class ValidatorTestExtensions +{ + /// + /// Executes the validator against the specified request instance and returns the resulting errors. + /// + /// The type of the request being validated. + /// The validator instance to execute. + /// The request instance to validate. + /// A list of produced by the validator. If the request is valid, the list will be empty. + public static List TestValidate(this IValidator validator, TRequest request) + { + return validator.Validate(request); + } + + /// + /// Asserts that the validation results do not contain the specified error. + /// + /// The list of errors returned by the validator. + /// The error that should not be present in the validation results. + public static void ShouldNotHaveValidationError(this List errors, Error expectedError) + { + Assert.DoesNotContain(errors, error => error.Description == expectedError.Description); + } + + /// + /// Asserts that the validation results contain the specified error. + /// + /// The list of errors returned by the validator. + /// The error that should be present in the validation results. + public static void ShouldHaveValidationError(this List errors, Error expectedError) + { + Assert.Contains(errors, error => error.Description == expectedError.Description); + } + + /// + /// Asserts that the validation results are completely empty, indicating the request is valid. + /// + /// The list of errors returned by the validator. + public static void ShouldNotHaveAnyValidationErrors(this List errors) + { + Assert.Empty(errors); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs index 7f4999ac..33365464 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs @@ -1,21 +1,22 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; -using FluentValidation.Results; using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Validators; +using Lumina.Presentation.Web.UnitTests.Common.Setup; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Web.UnitTests.Common.Validators; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class EncryptionSettingsModelValidatorTests { private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; - private readonly EncryptionSettingsModelValidator _validator = new(); + private readonly EncryptionSettingsDtoValidator _validator = new(); [Fact] public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError() @@ -24,11 +25,10 @@ public class EncryptionSettingsModelValidatorTests EncryptionSettingsDto settings = new() { SecretKey = string.Empty }; // Act - ValidationResult result = _validator.Validate(settings); + List result = _validator.TestValidate(settings); // Assert - Assert.False(result.IsValid); - Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key cannot be empty!"); + result.ShouldHaveValidationError(Error.Validation(description: "Encryption secret key cannot be empty!")); } [Fact] @@ -38,11 +38,10 @@ public class EncryptionSettingsModelValidatorTests EncryptionSettingsDto settings = new() { SecretKey = "not-base64-key!" }; // Act - ValidationResult result = _validator.Validate(settings); + List result = _validator.TestValidate(settings); // Assert - Assert.False(result.IsValid); - Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key must be a base64 string!"); + result.ShouldHaveValidationError(Error.Validation(description: "Encryption secret key must be a base64 string!")); } [Fact] @@ -52,9 +51,9 @@ public class EncryptionSettingsModelValidatorTests EncryptionSettingsDto settings = new() { SecretKey = VALID_BASE64_KEY }; // Act - ValidationResult result = _validator.Validate(settings); + List result = _validator.TestValidate(settings); // Assert - Assert.True(result.IsValid); + result.ShouldNotHaveAnyValidationErrors(); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs index a4509ebf..94ae0008 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs @@ -1,20 +1,21 @@ #region ========================================================================= USING ===================================================================================== -using FluentValidation; -using FluentValidation.Results; using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Validators; +using Lumina.Presentation.Web.UnitTests.Common.Setup; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Web.UnitTests.Common.Validators; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class ServerConfigurationModelValidatorTests { - private readonly ServerConfigurationModelValidator _validator = new(); + private readonly ServerConfigurationDtoValidator _validator = new(); [Fact] public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError() @@ -23,11 +24,10 @@ public class ServerConfigurationModelValidatorTests ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = string.Empty, Port = 5214 }; // Act - ValidationResult result = _validator.Validate(configuration); + List result = _validator.TestValidate(configuration); // Assert - Assert.False(result.IsValid); - Assert.Contains(result.Errors, error => error.PropertyName == nameof(ServerConfigurationDto.BaseAddress) && error.ErrorMessage == "Base address cannot be empty!"); + result.ShouldHaveValidationError(Error.Validation(description: "Base address cannot be empty!")); } [Theory] @@ -39,10 +39,10 @@ public class ServerConfigurationModelValidatorTests ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = port }; // Act - ValidationResult result = _validator.Validate(configuration); + List result = _validator.TestValidate(configuration); // Assert - Assert.True(result.IsValid); + result.ShouldNotHaveAnyValidationErrors(); } [Theory] @@ -54,10 +54,10 @@ public class ServerConfigurationModelValidatorTests ServerConfigurationDto configuration = new() { ApiVersion = apiVersion, BaseAddress = "http://localhost", Port = 5214 }; // Act - ValidationResult result = _validator.Validate(configuration); + List result = _validator.TestValidate(configuration); // Assert - Assert.True(result.IsValid); + result.ShouldNotHaveAnyValidationErrors(); } [Fact] @@ -67,9 +67,9 @@ public class ServerConfigurationModelValidatorTests ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 }; // Act - ValidationResult result = _validator.Validate(configuration); + List result = _validator.TestValidate(configuration); // Assert - Assert.True(result.IsValid); + result.ShouldNotHaveAnyValidationErrors(); } }