Skip to content

Commit

Permalink
Merge pull request #65 from micro-elements/v4
Browse files Browse the repository at this point in the history
V4
  • Loading branch information
petriashev authored Aug 21, 2020
2 parents bf04c72 + 4697cce commit dbb012d
Show file tree
Hide file tree
Showing 14 changed files with 112 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"cake.tool": {
"version": "0.35.0",
"version": "0.38.0",
"commands": [
"dotnet-cake"
]
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# Changes in 4.0.0:
* FluentValidation updated to [9.0.0]
* Swashbuckle.AspNetCore updated to [5.5.1]
* Changed getting included validator (FluentValidation internal API changed)
* New EmailValidator rule compatible with FluentValidation AspNetCoreCompatibleEmailValidator

# Changes in 3.2.0:
* FluentValidation fix version to [8.3.0, 9)
* Swashbuckle.AspNetCore fix version to [5.2.0, 6)
Expand Down
1 change: 1 addition & 0 deletions MicroElements.Swashbuckle.FluentValidation.sln
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
build.sh = build.sh
CHANGELOG.md = CHANGELOG.md
src\common.props = src\common.props
src\Directory.Build.props = src\Directory.Build.props
README.md = README.md
version.props = version.props
EndProjectSection
Expand Down
18 changes: 8 additions & 10 deletions build.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
##########################################################################
# This is modified Cake bootstrapper script for PowerShell.
# The initial file was downloaded from https://github.com/cake-build/resources
##########################################################################
#################################################################################################################
# This is the MicroElements.DevOps Cake bootstrapper script for PowerShell.
# For latest version see: https://github.com/micro-elements/MicroElements.DevOps/blob/master/resources/build.ps1
#################################################################################################################

[CmdletBinding()]
Param(
Expand All @@ -20,9 +20,8 @@ if(!$PSScriptRoot){
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}

$CAKE_VERSION = "0.29.0"
$CAKE_BAKERY_VERSION = "0.3.0"
$DEVOPS_VERSION = "1.9.1"
$CAKE_VERSION = "0.38.0"
$DEVOPS_VERSION = "1.11.0"
$NUGET_URL = "https://api.nuget.org/v3/index.json"
$NUGET_BETA_URL = "https://www.myget.org/F/micro-elements/api/v3/index.json"
#$NUGET_URL = "file://C:\NuGet"
Expand All @@ -31,16 +30,15 @@ $TOOLS_DIR = Join-Path $PSScriptRoot "tools"
$CAKE_DLL = Join-Path $TOOLS_DIR "Cake.CoreCLR/$CAKE_VERSION/Cake.dll"

# Script to run.
# $Script = Join-Path $TOOLS_DIR "microelements.devops/$DEVOPS_VERSION/scripts/main.cake"
$Script = Join-Path $TOOLS_DIR "microelements.devops/$DEVOPS_VERSION/scripts/main.cake"

$cake_props = @"
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Cake.CoreCLR" Version="$CAKE_VERSION" />
<PackageReference Include="Cake.Bakery" Version="$CAKE_BAKERY_VERSION" />
<PackageReference Include="MicroElements.DevOps" Version="$DEVOPS_VERSION" />
</ItemGroup>
</Project>
Expand Down
8 changes: 5 additions & 3 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@

echo "Starting build.sh"

DEVOPS_VERSION=1.9.1
DEVOPS_VERSION=1.11.0
NUGET_URL=https://api.nuget.org/v3/index.json
NUGET_BETA_URL=https://www.myget.org/F/micro-elements/api/v3/index.json

# Define directories.
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
Expand All @@ -17,7 +18,7 @@ TOOLS_DIR=$SCRIPT_DIR/tools
SCRIPT=$TOOLS_DIR/microelements.devops/$DEVOPS_VERSION/scripts/main.cake

CAKE_PROPS_PATH=$TOOLS_DIR/cake.props
CAKE_VERSION="0.35.0"
CAKE_VERSION="0.38.0"
CAKE_ARGUMENTS=()

# Parse arguments.
Expand All @@ -40,6 +41,7 @@ echo "SCRIPT_DIR: $SCRIPT_DIR"
echo "SCRIPT: $SCRIPT"
echo "TOOLS_DIR: $TOOLS_DIR"
echo "NUGET_URL: $NUGET_URL"
echo "NUGET_BETA_URL: $NUGET_BETA_URL"
echo "CAKE_PROPS_PATH: $CAKE_PROPS_PATH"
echo "CAKE_ARGUMENTS: ${CAKE_ARGUMENTS[*]}"

Expand Down Expand Up @@ -71,7 +73,7 @@ EOL
fi

# Restore Cake and Packages
dotnet restore $CAKE_PROPS_PATH --packages $TOOLS_DIR --source "$NUGET_URL"
dotnet restore $CAKE_PROPS_PATH --packages $TOOLS_DIR --source "$NUGET_URL" --source "$NUGET_BETA_URL"
dotnet tool restore

# Start Cake
Expand Down
5 changes: 4 additions & 1 deletion samples/SampleWebApi/Contracts/Sample.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.ComponentModel.DataAnnotations;
using FluentValidation;
using FluentValidation.Validators;

namespace SampleWebApi.Contracts
{
Expand All @@ -9,6 +10,7 @@ public class Sample

public string NotNull { get; set; }
public string NotEmpty { get; set; }
public string EmailAddressRegex { get; set; }
public string EmailAddress { get; set; }
public string RegexField { get; set; }

Expand All @@ -32,7 +34,8 @@ public SampleValidator()
{
RuleFor(sample => sample.NotNull).NotNull();
RuleFor(sample => sample.NotEmpty).NotEmpty();
RuleFor(sample => sample.EmailAddress).EmailAddress();
RuleFor(sample => sample.EmailAddressRegex).EmailAddress(EmailValidationMode.Net4xRegex);
RuleFor(sample => sample.EmailAddress).EmailAddress(EmailValidationMode.AspNetCoreCompatible);
RuleFor(sample => sample.RegexField).Matches(@"(\d{4})-(\d{2})-(\d{2})");

RuleFor(sample => sample.ValueInRange).GreaterThanOrEqualTo(5).LessThanOrEqualTo(10);
Expand Down
12 changes: 11 additions & 1 deletion samples/SampleWebApi/Controllers/SampleApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using SampleWebApi.Contracts;
using SampleWebApi.Validators;

namespace SampleWebApi.Controllers
{
Expand Down Expand Up @@ -52,6 +51,17 @@ public IActionResult AddSampleWithDataAnnotations([FromBody] SampleWithDataAnnot
return Ok();
}

[HttpPost("[action]")]
public IActionResult AddSampleFromQuery([FromQuery] Sample sample)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

return Ok();
}

[HttpPost("[action]")]
public IActionResult AddObjectA([FromBody] ObjectA objectA)
{
Expand Down
4 changes: 2 additions & 2 deletions samples/SampleWebApi/SampleWebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="8.5.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="9.1.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.2.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
</ItemGroup>

<ItemGroup>
Expand Down
5 changes: 2 additions & 3 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<Project>
<ItemGroup>
<PackageReference Include="SourceLink.Create.CommandLine" Version="2.8.3" PrivateAssets="All" />
<PackageReference Include="JetBrains.Annotations" Version="2019.1.3" PrivateAssets="All" />
<DotNetCliToolReference Include="dotnet-sourcelink" Version="2.8.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="JetBrains.Annotations" Version="2020.1.0" PrivateAssets="All" />
</ItemGroup>
<PropertyGroup>
<DebugType>embedded</DebugType>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,20 +107,40 @@ private void AddRulesFromIncludedValidators(OpenApiSchema schema, SchemaFilterCo
// Note: IValidatorDescriptor doesn't return IncludeRules so we need to get validators manually.
var childAdapters = (validator as IEnumerable<IValidationRule>)
.NotNull()
.OfType<IncludeRule>()
.Where(rule => rule is IIncludeRule)
.OfType<PropertyRule>()
.Where(includeRule => includeRule.HasNoCondition())
.SelectMany(includeRule => includeRule.Validators)
.OfType<ChildValidatorAdaptor>();
.OfType<IChildValidatorAdaptor>();

foreach (var adapter in childAdapters)
foreach (var childAdapter in childAdapters)
{
var propertyValidatorContext = new PropertyValidatorContext(new ValidationContext(null), null, string.Empty);
var includeValidator = adapter.GetValidator(propertyValidatorContext);
ApplyRulesToSchema(schema, context, includeValidator);
AddRulesFromIncludedValidators(schema, context, includeValidator);
IValidator includedValidator = GetValidatorFromChildValidatorAdapter(childAdapter);
if (includedValidator != null)
{
ApplyRulesToSchema(schema, context, includedValidator);
AddRulesFromIncludedValidators(schema, context, includedValidator);
}
}
}

private IValidator GetValidatorFromChildValidatorAdapter(IChildValidatorAdaptor childValidatorAdapter)
{
// Fake context. We have not got real context because no validation yet.
var fakeContext = new PropertyValidatorContext(new ValidationContext<object>(null), null, string.Empty);

// Try to validator with reflection.
var childValidatorAdapterType = childValidatorAdapter.GetType();
var getValidatorMethod = childValidatorAdapterType.GetMethod(nameof(ChildValidatorAdaptor<object, object>.GetValidator));
if (getValidatorMethod != null)
{
var validator = (IValidator)getValidatorMethod.Invoke(childValidatorAdapter, new[] { fakeContext });
return validator;
}

return null;
}

/// <summary>
/// Creates default rules.
/// Can be overriden by name.
Expand Down Expand Up @@ -177,6 +197,14 @@ public static FluentValidationRule[] CreateDefaultRules()
context.Schema.Properties[context.PropertyKey].Pattern = regularExpressionValidator.Expression;
}
},
new FluentValidationRule("EMail")
{
Matches = propertyValidator => propertyValidator.GetType().Name.Contains("EmailValidator") && propertyValidator.HasNoCondition(),
Apply = context =>
{
context.Schema.Properties[context.PropertyKey].Format = "email";
}
},
new FluentValidationRule("Comparison")
{
Matches = propertyValidator => propertyValidator is IComparisonValidator && propertyValidator.HasNoCondition(),
Expand Down Expand Up @@ -238,6 +266,7 @@ public static FluentValidationRule[] CreateDefaultRules()
}
}
},

};
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentValidation" Version="[8.3.0, 9)" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="[5.2.0, 6)" />
<PackageReference Include="FluentValidation" Version="[9.0.0, 10)" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="[5.5.1, 6)" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using FluentValidation;
using Microsoft.OpenApi.Models;
using SampleWebApi.Contracts;
using SampleWebApi.Validators;
using Swashbuckle.AspNetCore.SwaggerGen;
using Xunit;

Expand Down Expand Up @@ -68,22 +69,24 @@ public void MaximumLength_ShouldNot_Override_NotEmpty()
}

[Fact]
public void SampleValidator_FromSampleApi_HugeTest()
public void SampleValidator_FromSampleApi_Test()
{
var schemaRepository = new SchemaRepository();
var referenceSchema = SchemaGenerator(new SampleValidator()).GenerateSchema(typeof(Sample), schemaRepository);
var schema = schemaRepository.Schemas[referenceSchema.Reference.Id];

schema.Type.Should().Be("object");
schema.Properties.Keys.Count.Should().Be(12);
schema.Properties.Keys.Count.Should().Be(13);


schema.Properties["NotNull"].Nullable.Should().BeFalse();
schema.Required.Should().Contain("NotNull");

schema.Properties["NotEmpty"].MinLength.Should().Be(1);

schema.Properties["EmailAddress"].Pattern.Should().NotBeNullOrEmpty();
schema.Properties["EmailAddressRegex"].Pattern.Should().NotBeNullOrEmpty();
schema.Properties["EmailAddressRegex"].Format.Should().Be("email");
schema.Properties["EmailAddress"].Format.Should().Be("email");

schema.Properties["RegexField"].Pattern.Should().Be(@"(\d{4})-(\d{2})-(\d{2})");

Expand Down Expand Up @@ -116,6 +119,32 @@ public void SampleValidator_FromSampleApi_HugeTest()
schema.Properties["NotEmptyWithMaxLength"].MaxLength.Should().Be(50);
}

[Fact]
public void CustomerValidator_FromSampleApi_Test()
{
var schemaRepository = new SchemaRepository();
var referenceSchema = SchemaGenerator(new CustomerValidator()).GenerateSchema(typeof(Customer), schemaRepository);
var schema = schemaRepository.Schemas[referenceSchema.Reference.Id];
schema.Properties["Surname"].MinLength.Should().Be(1);
schema.Properties["Forename"].MinLength.Should().Be(1);

// From included validator
schema.Properties["Address"].MinLength.Should().Be(20);
schema.Properties["Address"].MaxLength.Should().Be(250);

schema.Properties["Discount"].Should().BeEquivalentTo(new OpenApiSchema()
{
Type = "number",
Format = "double",
Minimum = 4,
ExclusiveMinimum = true,
Maximum = 5,
ExclusiveMaximum = true
});

schema.Properties.Keys.Count.Should().Be(5);
}

[Theory]
[InlineData(1, 2, 1)]
[InlineData(2, 1, 1)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public SchemaGenerator SchemaGenerator(
var serializerOptions = new JsonSerializerOptions();
configureSerializer?.Invoke(serializerOptions);

return new SchemaGenerator(generatorOptions, new JsonSerializerMetadataResolver(serializerOptions));
return new SchemaGenerator(generatorOptions, new JsonSerializerDataContractResolver(serializerOptions));
}

public SchemaGenerator SchemaGenerator(params IValidator[] validators)
Expand Down
2 changes: 1 addition & 1 deletion version.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<VersionPrefix>3.2.0</VersionPrefix>
<VersionPrefix>4.0.0</VersionPrefix>
<VersionSuffix></VersionSuffix>
</PropertyGroup>
</Project>

0 comments on commit dbb012d

Please sign in to comment.