Skip to content

Commit

Permalink
Merge pull request #936 from RicoSuter/master
Browse files Browse the repository at this point in the history
Release v9.13.28
  • Loading branch information
RicoSuter authored Mar 29, 2019
2 parents 7118f53 + 78394f0 commit c620234
Show file tree
Hide file tree
Showing 15 changed files with 148 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,38 @@ public async Task When_definition_contains_both_min_length_a_string_length_attri
AssertCompile(code);
}

[Fact]
public async Task When_definition_contains_both_min_items_and_max_items_a_min_length_and_max_length_attributes_are_added_only_for_type_array()
{
//// Arrange
var json =
@"{
""type"": ""object"",
""properties"": {
""foo"": {
""type"": ""array"",
""minItems"": ""10"",
""maxItems"": ""20""
}
}
}";
var schema = await JsonSchema4.FromJsonAsync(json);

//// Act
var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
{
ClassStyle = CSharpClassStyle.Poco,
SchemaType = SchemaType.Swagger2
});
var code = generator.GenerateFile("MyClass");

//// Assert
Assert.Contains("System.ComponentModel.DataAnnotations.MinLength(10)", code);
Assert.Contains("System.ComponentModel.DataAnnotations.MaxLength(20)", code);

AssertCompile(code);
}

[Fact]
public async Task When_definition_contains_pattern_a_regular_expression_attribute_is_added()
{
Expand Down
30 changes: 30 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,36 @@ public bool RenderStringLengthAttribute
/// <summary>Gets the maximum value of the string length attribute.</summary>
public string StringLengthMaximumValue => _property.MaxLength.HasValue ? _property.MaxLength.Value.ToString(CultureInfo.InvariantCulture) : $"int.{nameof(int.MaxValue)}";

/// <summary>Gets a value indicating whether to render the min length attribute.</summary>
public bool RenderMinLengthAttribute
{
get
{
if (!_settings.GenerateDataAnnotations)
return false;

return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Array) && _property.MinItems > 0;
}
}

/// <summary>Gets the value of the min length attribute.</summary>
public int MinLengthAttribute => _property.MinItems;

/// <summary>Gets a value indicating whether to render the max length attribute.</summary>
public bool RenderMaxLengthAttribute
{
get
{
if (!_settings.GenerateDataAnnotations)
return false;

return _property.ActualTypeSchema.Type.HasFlag(JsonObjectType.Array) && _property.MaxItems > 0;
}
}

/// <summary>Gets the value of the max length attribute.</summary>
public int MaxLengthAttribute => _property.MaxItems;

/// <summary>Gets a value indicating whether to render a regular expression attribute.</summary>
public bool RenderRegularExpressionAttribute
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net451</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.27</Version>
<Version>9.13.28</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
6 changes: 6 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@
{% if property.RenderStringLengthAttribute -%}
[System.ComponentModel.DataAnnotations.StringLength({{ property.StringLengthMaximumValue }}{% if property.StringLengthMinimumValue > 0 %}, MinimumLength = {{ property.StringLengthMinimumValue }}{% endif %})]
{% endif -%}
{% if property.RenderMinLengthAttribute -%}
[System.ComponentModel.DataAnnotations.MinLength({{ property.MinLengthAttribute }})]
{% endif -%}
{% if property.RenderMaxLengthAttribute -%}
[System.ComponentModel.DataAnnotations.MaxLength({{ property.MaxLengthAttribute }})]
{% endif -%}
{% if property.RenderRegularExpressionAttribute -%}
[System.ComponentModel.DataAnnotations.RegularExpression(@"{{ property.RegularExpressionValue }}")]
{% endif -%}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net451</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.27</Version>
<Version>9.13.28</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class CodeGeneratorSettingsBase
public CodeGeneratorSettingsBase()
{
GenerateDefaultValues = true;
ExcludedTypeNames = new string[] { };
ExcludedTypeNames = new string[0];
}

/// <summary>Gets or sets the schema type (default: JsonSchema).</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net451</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.27</Version>
<Version>9.13.28</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
42 changes: 42 additions & 0 deletions src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,48 @@ public async Task When_StringLengthAttribute_is_set_then_minLength_and_maxLenght
Assert.Equal(10, property.MaxLength);
}

public class MinLengthAttributeClass
{
[MinLength(1)]
public int[] Items { get; set; }

[MinLength(50)]
public string Foo { get; set; }
}

[Fact]
public async Task When_MinLengthAttribute_is_set_then_minItems_or_minLength_is_set()
{
var schema = await JsonSchema4.FromTypeAsync<MinLengthAttributeClass>();

var arrayProperty = schema.Properties["Items"];
Assert.Equal(1, arrayProperty.MinItems);

var stringProperty = schema.Properties["Foo"];
Assert.Equal(50, stringProperty.MinLength);
}

public class MaxLengthAttributeClass
{
[MaxLength(100)]
public int[] Items { get; set; }

[MaxLength(500)]
public string Foo { get; set; }
}

[Fact]
public async Task When_MaxLengthAttribute_is_set_then_maxItems_or_maxLength_is_set()
{
var schema = await JsonSchema4.FromTypeAsync<MaxLengthAttributeClass>();

var arrayProperty = schema.Properties["Items"];
Assert.Equal(100, arrayProperty.MaxItems);

var stringProperty = schema.Properties["Foo"];
Assert.Equal(500, stringProperty.MaxLength);
}

public class StringRequiredClass
{
[Required(AllowEmptyStrings = false)]
Expand Down
17 changes: 15 additions & 2 deletions src/NJsonSchema.Tests/Generation/EnumGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ public class Foo
public Bar Bar2 { get; set; }
}

/// <summary>
/// Foo bar.
/// </summary>
public enum Bar
{
A = 0,
Expand All @@ -34,7 +37,8 @@ public async Task When_property_is_integer_enum_then_schema_has_enum()
//// Act
var schema = await JsonSchema4.FromTypeAsync<Foo>(new JsonSchemaGeneratorSettings
{
DefaultEnumHandling = EnumHandling.Integer
DefaultEnumHandling = EnumHandling.Integer,
GenerateEnumMappingDescription = true
});
var data = schema.ToJson();

Expand All @@ -44,6 +48,9 @@ public async Task When_property_is_integer_enum_then_schema_has_enum()
Assert.Equal(0, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(0));
Assert.Equal(5, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(1));
Assert.Equal(6, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(2));

Assert.Contains("Foo bar.", schema.Properties["Bar"].ActualTypeSchema.Description); // option is enabled
Assert.Contains("5 = B", schema.Properties["Bar"].ActualTypeSchema.Description); // option is enabled
}

[Fact]
Expand All @@ -63,6 +70,8 @@ public async Task When_string_and_integer_enum_used_then_two_refs_are_generated(
Assert.NotNull(schema.Properties["Bar"].ActualTypeSchema);
Assert.NotNull(schema.Properties["Bar2"].ActualTypeSchema); // must not be a reference but second enum declaration
Assert.NotEqual(schema.Properties["Bar"].ActualTypeSchema, schema.Properties["Bar2"].ActualTypeSchema);

Assert.DoesNotContain("5 = B", schema.Properties["Bar"].ActualTypeSchema.Description); // option is not enabled
}

[Fact]
Expand All @@ -74,15 +83,19 @@ public async Task When_property_is_string_enum_then_schema_has_enum()
//// Act
var schema = await JsonSchema4.FromTypeAsync<Foo>(new JsonSchemaGeneratorSettings
{
DefaultEnumHandling = EnumHandling.String
DefaultEnumHandling = EnumHandling.String,
GenerateEnumMappingDescription = true
});
var data = schema.ToJson();

//// Assert
Assert.Equal(JsonObjectType.String, schema.Properties["Bar"].ActualTypeSchema.Type);
Assert.Equal(3, schema.Properties["Bar"].ActualTypeSchema.Enumeration.Count);
Assert.Equal("A", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(0));
Assert.Equal("B", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(1));
Assert.Equal("C", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(2));

Assert.DoesNotContain("=", schema.Properties["Bar"].ActualTypeSchema.Description); // string enums do not have mapping in description
}

[Fact]
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema.Yaml/NJsonSchema.Yaml.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.3;netstandard2.0;net45</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.27</Version>
<Version>9.13.28</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down
5 changes: 1 addition & 4 deletions src/NJsonSchema/DefaultTypeNameGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace NJsonSchema
{
Expand Down Expand Up @@ -57,9 +56,7 @@ public virtual string Generate(JsonSchema4 schema, string typeNameHint, IEnumera
/// <returns>The type name.</returns>
protected virtual string Generate(JsonSchema4 schema, string typeNameHint)
{
if (string.IsNullOrEmpty(typeNameHint) &&
string.IsNullOrEmpty(schema.Title) == false &&
Regex.IsMatch(schema.Title, "^[a-zA-Z0-9_]*$"))
if (string.IsNullOrEmpty(typeNameHint) && schema.HasTypeNameTitle)
{
typeNameHint = schema.Title;
}
Expand Down
10 changes: 8 additions & 2 deletions src/NJsonSchema/Generation/JsonSchemaGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -490,11 +490,11 @@ private async Task GenerateEnum<TSchemaType>(
schema.Reference = schemaResolver.GetSchema(type, isIntegerEnumeration);
else if (schema.GetType() == typeof(JsonSchema4))
{
LoadEnumerations(type, schema, typeDescription);

typeDescription.ApplyType(schema);
schema.Description = await type.GetXmlSummaryAsync().ConfigureAwait(false);

LoadEnumerations(type, schema, typeDescription);

schemaResolver.AddSchema(type, isIntegerEnumeration, schema);
}
else
Expand Down Expand Up @@ -905,6 +905,12 @@ private void LoadEnumerations(Type type, JsonSchema4 schema, JsonTypeDescription

schema.EnumerationNames.Add(enumName);
}

if (typeDescription.Type == JsonObjectType.Integer && Settings.GenerateEnumMappingDescription)
{
schema.Description = (schema.Description + "\n\n" +
string.Join("\n", schema.Enumeration.Select((e, i) => e + " = " + schema.EnumerationNames[i]))).Trim();
}
}

private async Task LoadPropertyOrFieldAsync(Newtonsoft.Json.Serialization.JsonProperty property, MemberInfo propertyInfo, Type parentType, JsonSchema4 parentSchema, JsonSchemaResolver schemaResolver)
Expand Down
3 changes: 3 additions & 0 deletions src/NJsonSchema/Generation/JsonSchemaGeneratorSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ public JsonSchemaGeneratorSettings()
/// defined on the object (otherwise allOf/oneOf with $ref is used, default: false).</summary>
public bool AllowReferencesWithProperties { get; set; }

/// <summary>Gets or sets a value indicating whether to generate a description with number to enum name mappings (for integer enums only, default: false).</summary>
public bool GenerateEnumMappingDescription { get; set; }

/// <summary>Gets or sets the schema type to generate (default: JsonSchema).</summary>
public SchemaType SchemaType { get; set; }

Expand Down
5 changes: 5 additions & 0 deletions src/NJsonSchema/JsonSchema4.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Expand Down Expand Up @@ -329,6 +330,10 @@ public IDictionary<string, JsonProperty> ActualProperties
[JsonProperty("title", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 3)]
public string Title { get; set; }

/// <summary>Gets a value indicating whether the schema title can be used as type name.</summary>
[JsonIgnore]
public bool HasTypeNameTitle => !string.IsNullOrEmpty(Title) && Regex.IsMatch(Title, "^[a-zA-Z0-9_]*$");

/// <summary>Gets or sets the description. </summary>
[JsonProperty("description", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public virtual string Description { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema/NJsonSchema.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard1.0;netstandard2.0;net40;net45</TargetFrameworks>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<Version>9.13.27</Version>
<Version>9.13.28</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2018</Copyright>
<PackageLicenseUrl>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</PackageLicenseUrl>
Expand Down

0 comments on commit c620234

Please sign in to comment.