Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C# Generator: Generate range for different formats #1720

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public async Task When_int64_property_has_minimum_then_range_attribute_is_render
Assert.Null(schema.Properties["value"].Minimum);
Assert.Equal(10, schema.Properties["value"].ActualSchema.Minimum);

Assert.Contains("[System.ComponentModel.DataAnnotations.Range(10D, double.MaxValue)]\n" +
Assert.Contains("[System.ComponentModel.DataAnnotations.Range(10L, long.MaxValue)]\n" +
" public long Value { get; set; }\n", code);
}

Expand Down Expand Up @@ -229,7 +229,7 @@ public async Task When_integer_property_has_minimum_and_maximum_that_are_int64_t
Assert.Equal(10000000000m, schema.Properties["value"].ActualSchema.Maximum);

// expect the integer to be converted to an int64
Assert.Contains("[System.ComponentModel.DataAnnotations.Range(-10000000000D, 10000000000D)]\n" +
Assert.Contains("[System.ComponentModel.DataAnnotations.Range(-10000000000L, 10000000000L)]\n" +
" public long Value { get; set; }\n", code);
}

Expand Down
37 changes: 37 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp.Tests/ValueGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,43 @@ public async Task When_schema_contains_range_then_code_is_correctly_generated()
Assert.Contains("[System.ComponentModel.DataAnnotations.Range(2, int.MaxValue)]", code);
}

[Theory]
[InlineData("integer", JsonFormatStrings.Integer, "1, int.MaxValue")]
[InlineData("integer", JsonFormatStrings.Long, "1L, long.MaxValue")]
[InlineData("integer", JsonFormatStrings.ULong, "1UL, ulong.MaxValue")]
[InlineData("number", JsonFormatStrings.Float, "1F, float.MaxValue")]
[InlineData("number", JsonFormatStrings.Double, "1D, double.MaxValue")]
[InlineData("number", JsonFormatStrings.Decimal, "1M, decimal.MaxValue")]
public async Task When_schema_contains_range_and_format_then_code_is_correctly_generated(string propertyType,
string propertyFormat, string expectedRange)
{
/// Arrange
var json = $$"""
{
"type": "object",
"properties": {
"pageSize": {
"type": "{{propertyType}}",
"format": "{{propertyFormat}}",
"minimum": 1
},
}
}
""";
var schema = await JsonSchema.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.Range({expectedRange})]", code);
}

[Fact]
public async Task When_property_is_integer_and_no_format_is_available_then_default_value_is_int32()
{
Expand Down
2 changes: 2 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ public override string GetNumericValue(JsonObjectType type, object value, string
return Convert.ToInt32(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
case JsonFormatStrings.Long:
return Convert.ToInt64(value, CultureInfo.InvariantCulture) + "L";
case JsonFormatStrings.ULong:
return Convert.ToUInt64(value, CultureInfo.InvariantCulture) + "UL";
case JsonFormatStrings.Double:
return ConvertNumberToString(value) + "D";
case JsonFormatStrings.Float:
Expand Down
34 changes: 30 additions & 4 deletions src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

using NJsonSchema.Annotations;
using System.Globalization;
using System.Linq;
using NJsonSchema.CodeGeneration.Models;

namespace NJsonSchema.CodeGeneration.CSharp.Models
Expand All @@ -18,6 +19,16 @@ public class PropertyModel : PropertyModelBase
private readonly JsonSchemaProperty _property;
private readonly CSharpGeneratorSettings _settings;
private readonly CSharpTypeResolver _resolver;
private static readonly string[] RangeFormats =
[
JsonFormatStrings.Integer,
JsonFormatStrings.Float,
JsonFormatStrings.Double,
JsonFormatStrings.Long,
JsonFormatStrings.ULong,
JsonFormatStrings.Decimal
];


/// <summary>Initializes a new instance of the <see cref="PropertyModel"/> class.</summary>
/// <param name="classTemplateModel">The class template model.</param>
Expand Down Expand Up @@ -139,8 +150,8 @@ public string RangeMinimumValue
{
var schema = _property.ActualSchema;
var propertyFormat = GetSchemaFormat(schema);
var format = propertyFormat == JsonFormatStrings.Integer ? JsonFormatStrings.Integer : JsonFormatStrings.Double;
var type = propertyFormat == JsonFormatStrings.Integer ? "int" : "double";
var format = GetRangeFormat(propertyFormat);
var type = GetRangeType(propertyFormat);

var minimum = schema.Minimum;
if (minimum.HasValue && schema.IsExclusiveMinimum)
Expand Down Expand Up @@ -171,8 +182,8 @@ public string RangeMaximumValue
{
var schema = _property.ActualSchema;
var propertyFormat = GetSchemaFormat(schema);
var format = propertyFormat == JsonFormatStrings.Integer ? JsonFormatStrings.Integer : JsonFormatStrings.Double;
var type = propertyFormat == JsonFormatStrings.Integer ? "int" : "double";
var format = GetRangeFormat(propertyFormat);
var type = GetRangeType(propertyFormat);

var maximum = schema.Maximum;
if (maximum.HasValue && schema.IsExclusiveMaximum)
Expand Down Expand Up @@ -311,5 +322,20 @@ public bool RenderRegularExpressionAttribute

return schema.Format;
}

private static string GetRangeFormat(string? propertyFormat) =>
RangeFormats.Contains(propertyFormat) ? propertyFormat! : JsonFormatStrings.Double;

private static string GetRangeType(string? propertyFormat) =>
propertyFormat switch
{
JsonFormatStrings.Integer => "int",
JsonFormatStrings.Float => "float",
JsonFormatStrings.Double => "double",
JsonFormatStrings.Long => "long",
JsonFormatStrings.ULong => "ulong",
JsonFormatStrings.Decimal => "decimal",
_ => "double",
};
}
}