Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/RicoSuter/NJsonSchema
Browse files Browse the repository at this point in the history
  • Loading branch information
RicoSuter committed Feb 26, 2021
2 parents f98ac01 + d8f5302 commit 3ff7d0d
Show file tree
Hide file tree
Showing 16 changed files with 163 additions and 13 deletions.
31 changes: 30 additions & 1 deletion src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand Down Expand Up @@ -132,5 +133,33 @@ public async Task When_property_references_any_schema_with_inheritance_then_prop
//// Assert
Assert.Contains("public Dog Dog { get; set; }", code);
}

[Fact]
public async Task When_definitions_inherit_from_root_schema()
{
//// Arrange
var path = GetTestDirectory() + "/References/Animal.json";

//// Act
var schema = await JsonSchema.FromFileAsync(path);
var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Record });

//// Act
var code = generator.GenerateFile();

//// Assert
Assert.Contains("public abstract partial class Animal", code);
Assert.Contains("public partial class Cat : Animal", code);
Assert.Contains("public partial class PersianCat : Cat", code);
Assert.Contains("[JsonInheritanceAttribute(\"Cat\", typeof(Cat))]", code);
Assert.Contains("[JsonInheritanceAttribute(\"PersianCat\", typeof(PersianCat))]", code);
}

private string GetTestDirectory()
{
var codeBase = Assembly.GetExecutingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
return Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<None Remove="References\A.json" />
<None Remove="References\Animal.json" />
<None Remove="References\B.json" />
<None Remove="References\C.json" />
<None Remove="References\D.json" />
Expand All @@ -16,6 +17,9 @@
<Content Include="References\A.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="References\Animal.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="References\B.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
Expand Down
25 changes: 25 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp.Tests/References/Animal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"title": "Animal",
"type": "object",
"x-abstract": true,
"discriminator": "discriminator",

"definitions": {
"Cat": {
"type": "object",
"allOf": [
{
"$ref": "Animal.json"
}
]
},
"PersianCat": {
"type": "object",
"allOf": [
{
"$ref": "#/definitions/Cat"
}
]
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ schema is JsonSchemaProperty property &&
var markAsNullableType = Settings.GenerateNullableReferenceTypes && isNullable;

if (schema.ActualTypeSchema.IsAnyType &&
schema.ActualDiscriminator == null &&
schema.InheritedSchema == null && // not in inheritance hierarchy
schema.AllOf.Count == 0 &&
!Types.Keys.Contains(schema) &&
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>10.3.7</Version>
<Version>10.3.8</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2020</Copyright>
<PackageProjectUrl>http://NJsonSchema.org</PackageProjectUrl>
Expand Down
8 changes: 4 additions & 4 deletions src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
/// <summary>{{ property.Description | csharpdocs }}</summary>
{% endif -%}
{% if UseSystemTextJson -%}
[System.Text.Json.Serialization.JsonPropertyName("{{ property.Name }}"]
[System.Text.Json.Serialization.JsonPropertyName("{{ property.Name }}")]
{% if property.IsStringEnumArray -%}
// TODO(system.text.json): Add string enum item converter
{% endif -%}
Expand All @@ -76,7 +76,7 @@
{% endif -%}
{% if property.IsStringEnum -%}
{% if UseSystemTextJson -%}
[System.Text.Json.Serialization.JsonConverter(System.Text.Json.Serialization.JsonStringEnumConverter)]
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
{% else -%}
[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
{% endif -%}
Expand All @@ -98,11 +98,11 @@
get { return {{ property.FieldName }}; }
{% if property.HasSetter -%}
{% if RenderInpc -%}
{{PropertySetterAccessModifier}}set
{{PropertySetterAccessModifier}}set
{
if ({{ property.FieldName }} != value)
{
{{ property.FieldName }} = value;
{{ property.FieldName }} = value;
RaisePropertyChanged();
}
}
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>10.3.7</Version>
<Version>10.3.8</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2020</Copyright>
<PackageProjectUrl>http://NJsonSchema.org</PackageProjectUrl>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,17 @@ protected ClassTemplateModelBase(TypeResolverBase resolver, JsonSchema schema, o
_schema = schema;
_rootObject = rootObject;
_resolver = resolver;

SchemaTitle = _schema?.Title;
}

/// <summary>Gets the class.</summary>
public abstract string ClassName { get; }

/// <summary>
/// Gets the original title of the class (schema title).
/// </summary>
public string SchemaTitle { get; }

/// <summary>Gets a value indicating whether this class represents a JSON object with fixed amount of properties.</summary>
public bool IsObject => _schema.ActualTypeSchema.IsObject;
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>10.3.7</Version>
<Version>10.3.8</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2020</Copyright>
<PackageProjectUrl>http://NJsonSchema.org</PackageProjectUrl>
Expand Down
46 changes: 46 additions & 0 deletions src/NJsonSchema.Tests/Validation/FormatUuidTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;
using System.Linq;
using Newtonsoft.Json.Linq;
using NJsonSchema.Validation;
using Xunit;

namespace NJsonSchema.Tests.Validation
{
public class FormatUuidTests
{
[Fact]
public void When_format_uuid_incorrect_then_validation_succeeds()
{
//// Arrange
var schema = new JsonSchema();
schema.Type = JsonObjectType.String;
schema.Format = JsonFormatStrings.Uuid;

var token = new JValue("test");

//// Act
var errors = schema.Validate(token);

//// Assert
Assert.Equal(ValidationErrorKind.UuidExpected, errors.First().Kind);
}

[Fact]
public void When_format_uuid_correct_then_validation_succeeds()
{
//// Arrange
var schema = new JsonSchema();
schema.Type = JsonObjectType.String;
schema.Format = JsonFormatStrings.Uuid;

var uuid = Guid.NewGuid().ToString();
var token = new JValue(uuid);

//// Act
var errors = schema.Validate(token);

//// Assert
Assert.Empty(errors);
}
}
}
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>10.3.7</Version>
<Version>10.3.8</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2020</Copyright>
<PackageProjectUrl>http://NJsonSchema.org</PackageProjectUrl>
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema/JsonSchemaAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public virtual void AppendSchema(JsonSchema schema, string typeNameHint)

if (schema == RootObject)
{
throw new ArgumentException("The root schema cannot be appended.");
return;
}

if (!RootSchema.Definitions.Values.Contains(schema))
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>10.3.7</Version>
<Version>10.3.8</Version>
<PackageTags>json schema validation generator .net</PackageTags>
<Copyright>Copyright © Rico Suter, 2020</Copyright>
<PackageProjectUrl>http://NJsonSchema.org</PackageProjectUrl>
Expand Down
34 changes: 34 additions & 0 deletions src/NJsonSchema/Validation/FormatValidators/UuidFormatValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//-----------------------------------------------------------------------
// <copyright file="UuidFormatValidator.cs" company="NJsonSchema">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

using Newtonsoft.Json.Linq;
using System;

namespace NJsonSchema.Validation.FormatValidators
{
/// <summary>Validator for "Uuid" format.</summary>
public class UuidFormatValidator : IFormatValidator
{
/// <summary>Gets the format attribute's value.</summary>
#pragma warning disable CS0618 // Type or member is obsolete
public string Format { get; } = JsonFormatStrings.Uuid;
#pragma warning restore CS0618 // Type or member is obsolete

/// <summary>Gets the kind of error produced by validator.</summary>
public ValidationErrorKind ValidationErrorKind { get; } = ValidationErrorKind.UuidExpected;

/// <summary>Validates format of given value.</summary>
/// <param name="value">String value.</param>
/// <param name="tokenType">Type of token holding the value.</param>
/// <returns>True if value is correct for given format, False - if not.</returns>
public bool IsValid(string value, JTokenType tokenType)
{
return Guid.TryParse(value, out Guid guid);
}
}
}
3 changes: 2 additions & 1 deletion src/NJsonSchema/Validation/JsonSchemaValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public class JsonSchemaValidator
new TimeSpanFormatValidator(),
new UriFormatValidator(),
new ByteFormatValidator(),
new Base64FormatValidator()
new Base64FormatValidator(),
new UuidFormatValidator()
};

private readonly IDictionary<string, IFormatValidator[]> _formatValidatorsMap;
Expand Down
5 changes: 4 additions & 1 deletion src/NJsonSchema/Validation/ValidationErrorKind.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ public enum ValidationErrorKind
Base64Expected,

/// <summary>No type of the types does validate (check error details in <see cref="MultiTypeValidationError"/>). </summary>
NoTypeValidates
NoTypeValidates,

/// <summary>A valid UUID is expected. </summary>
UuidExpected,
}
}

0 comments on commit 3ff7d0d

Please sign in to comment.