Skip to content
Merged
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 @@ -44,11 +44,12 @@ public DataContract GetDataContractForType(Type type)
if (effectiveType.IsEnum)
{
var enumValues = effectiveType.GetEnumValues();
var serializationType = GetEnumSerializationType(type, effectiveType);

// Test to determine if the serializer will treat as string
var serializeAsString =
enumValues.Length > 0 &&
JsonConverterFunc(enumValues.GetValue(0), type).StartsWith('\"');
JsonConverterFunc(enumValues.GetValue(0), serializationType).StartsWith('\"');

var exampleType = serializeAsString ?
typeof(string) :
Expand All @@ -60,7 +61,7 @@ public DataContract GetDataContractForType(Type type)
underlyingType: effectiveType,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: (value) => JsonConverterFunc(value, type));
jsonConverter: (value) => JsonConverterFunc(value, serializationType));
}

if (IsSupportedDictionary(effectiveType, out Type keyType, out Type valueType))
Expand Down Expand Up @@ -103,6 +104,29 @@ public DataContract GetDataContractForType(Type type)
jsonConverter: (value) => JsonConverterFunc(value, effectiveType));
}

private Type GetEnumSerializationType(Type type, Type effectiveType)
{
// Without an explicit resolver the serializer falls back to reflection, which
// supports the nullable type, so there is nothing to probe.
if (type == effectiveType || _serializerOptions.TypeInfoResolver is null)
{
return type;
}

// Prefer the nullable contract so that converters registered for Nullable<T> are honored,
// but fall back to the enum itself when the serializer has no metadata for the nullable
// type (for example a source-generated context that only registers the enum).
try
{
_serializerOptions.GetTypeInfo(type);
return type;
}
catch (NotSupportedException)
{
return effectiveType;
}
}

private string JsonConverterFunc(object value, Type type)
{
return JsonSerializer.Serialize(value, type, _serializerOptions);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Microsoft.OpenApi;

namespace Swashbuckle.AspNetCore.SwaggerGen.Test;

public class JsonSourceGenerationSchemaGeneratorTests
{
[Fact]
public void GenerateSchema_GeneratesEnumValues_ForIntegerEnumResolvedBySourceGeneration()
{
var schema = GenerateSchemaFor(typeof(SourceGeneratedTimeRange));

Assert.Equal(JsonSchemaTypes.Integer, schema.Type);
Assert.Equal(["0", "1", "2"], schema.Enum.Select((p) => p.ToJsonString()));
}

[Fact]
public void GenerateSchema_GeneratesEnumValues_ForNullableIntegerEnumResolvedBySourceGeneration()
{
var schema = GenerateSchemaFor(typeof(SourceGeneratedTimeRange?));

Assert.Equal(JsonSchemaTypes.Integer, schema.Type);
Assert.Equal(["0", "1", "2"], schema.Enum.Select((p) => p.ToJsonString()));
}

[Fact]
public void GenerateSchema_GeneratesEnumValues_ForStringEnumResolvedBySourceGeneration()
{
var schema = GenerateSchemaFor(typeof(SourceGeneratedLevel));

Assert.Equal(JsonSchemaTypes.String, schema.Type);
Assert.Equal(["\"Low\"", "\"High\""], schema.Enum.Select((p) => p.ToJsonString()));
}

[Fact]
public void GenerateSchema_GeneratesEnumValues_ForEnumPropertyResolvedBySourceGeneration()
{
var repository = new SchemaRepository();

Subject().GenerateSchema(typeof(SourceGeneratedForecast), repository);

var schema = Assert.IsType<OpenApiSchema>(repository.Schemas[nameof(SourceGeneratedTimeRange)]);

Assert.Equal(JsonSchemaTypes.Integer, schema.Type);
Assert.Equal(["0", "1", "2"], schema.Enum.Select((p) => p.ToJsonString()));
}

[Fact]
public void GenerateSchema_UsesNullableEnumConverter_WhenNullableMetadataIsAvailable()
{
var serializerOptions = new JsonSerializerOptions()
{
TypeInfoResolver = NullableSourceGenerationContext.Default,
Converters = { new PrefixedNullableLevelConverter() },
};

var generatorOptions = new SchemaGeneratorOptions();
var subject = new SchemaGenerator(generatorOptions, new JsonSerializerDataContractResolver(serializerOptions, generatorOptions));
var repository = new SchemaRepository();

subject.GenerateSchema(typeof(SourceGeneratedLevel?), repository);

var schema = Assert.IsType<OpenApiSchema>(repository.Schemas[nameof(SourceGeneratedLevel)]);

Assert.Equal(JsonSchemaTypes.String, schema.Type);
Assert.Equal(["\"nullable-Low\"", "\"nullable-High\""], schema.Enum.Select((p) => p.ToJsonString()));
}

[Fact]
public void GenerateSchema_UsesNullableEnumConverter_WithDefaultSerializerOptions()
{
var serializerOptions = new JsonSerializerOptions()
{
Converters = { new PrefixedNullableLevelConverter() },
};

var generatorOptions = new SchemaGeneratorOptions();
var subject = new SchemaGenerator(generatorOptions, new JsonSerializerDataContractResolver(serializerOptions, generatorOptions));
var repository = new SchemaRepository();

subject.GenerateSchema(typeof(SourceGeneratedLevel?), repository);

var schema = Assert.IsType<OpenApiSchema>(repository.Schemas[nameof(SourceGeneratedLevel)]);

Assert.Equal(JsonSchemaTypes.String, schema.Type);
Assert.Equal(["\"nullable-Low\"", "\"nullable-High\""], schema.Enum.Select((p) => p.ToJsonString()));
}

private static OpenApiSchema GenerateSchemaFor(Type type)
{
var repository = new SchemaRepository();

Subject().GenerateSchema(type, repository);

var name = (Nullable.GetUnderlyingType(type) ?? type).Name;

return Assert.IsType<OpenApiSchema>(repository.Schemas[name]);
}

private static SchemaGenerator Subject()
{
// Reproduces an application that has disabled reflection-based serialization
// by only resolving JSON metadata through a source-generated context.
var serializerOptions = new JsonSerializerOptions()
{
TypeInfoResolver = SourceGenerationContext.Default,
};

var generatorOptions = new SchemaGeneratorOptions();

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

public enum SourceGeneratedTimeRange
{
Daily,
Weekly,
Monthly,
}

[JsonConverter(typeof(JsonStringEnumConverter<SourceGeneratedLevel>))]
public enum SourceGeneratedLevel
{
Low,
High,
}

public class SourceGeneratedForecast
{
public SourceGeneratedTimeRange Range { get; set; }

public int TemperatureC { get; set; }
}

public sealed class PrefixedNullableLevelConverter : JsonConverter<SourceGeneratedLevel?>
{
public override SourceGeneratedLevel? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> throw new NotSupportedException();

public override void Write(Utf8JsonWriter writer, SourceGeneratedLevel? value, JsonSerializerOptions options)
=> writer.WriteStringValue($"nullable-{value}");
}

[JsonSerializable(typeof(SourceGeneratedTimeRange))]
[JsonSerializable(typeof(SourceGeneratedLevel))]
[JsonSerializable(typeof(SourceGeneratedForecast))]
internal sealed partial class SourceGenerationContext : JsonSerializerContext;

[JsonSerializable(typeof(SourceGeneratedLevel))]
[JsonSerializable(typeof(SourceGeneratedLevel?))]
internal sealed partial class NullableSourceGenerationContext : JsonSerializerContext;
Loading