Skip to content

Commit

Permalink
Change default of DefaultResponseReferenceTypeNullHandling to NotNull (
Browse files Browse the repository at this point in the history
…#2215)

* Change default of DefaultResponseReferenceTypeNullHandling to NotNull

* Add support for nullable response xml docs attribute
  • Loading branch information
RicoSuter authored Jun 10, 2019
1 parent 1c730aa commit 0987a1a
Show file tree
Hide file tree
Showing 45 changed files with 374 additions and 293 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"apiGroupNames": null,
"defaultPropertyNameHandling": "Default",
"defaultReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "Integer",
"flattenInheritanceHierarchy": false,
"generateKnownTypes": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"type": "array",
Expand Down Expand Up @@ -82,7 +82,7 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"type": "string"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"apiGroupNames": null,
"defaultPropertyNameHandling": "Default",
"defaultReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "Integer",
"flattenInheritanceHierarchy": false,
"generateKnownTypes": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"type": "array",
Expand Down Expand Up @@ -82,7 +82,7 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"type": "string"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"apiGroupNames": null,
"defaultPropertyNameHandling": "Default",
"defaultReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "Integer",
"flattenInheritanceHierarchy": false,
"generateKnownTypes": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"type": "array",
Expand Down Expand Up @@ -82,7 +82,7 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"type": "string"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"includedVersions": null,
"defaultPropertyNameHandling": "Default",
"defaultReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "Null",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "Integer",
"flattenInheritanceHierarchy": false,
"generateKnownTypes": true,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace NSwag.Generation.AspNetCore.Tests.Web.Controllers.Responses
{
[ApiController]
[Route("api/[controller]")]
public class NullableResponseController : Controller
{
/// <summary>
/// Gets an order.
/// </summary>
/// <response code="200" nullable="true">Order created.</response>
/// <response code="404">Order not found.</response>
[HttpPost("OperationWithNullableResponse")]
[Produces("application/json")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(SerializableError), StatusCodes.Status400BadRequest)]
public ActionResult<string> OperationWithNullableResponse()
{
return Ok();
}

/// <summary>
/// Gets an order.
/// </summary>
/// <response code="200" nullable="false">Order created.</response>
/// <response code="404">Order not found.</response>
[HttpPost("OperationWithNonNullableResponse")]
[Produces("application/json")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(SerializableError), StatusCodes.Status400BadRequest)]
public ActionResult<string> OperationWithNonNullableResponse()
{
return Ok();
}

[HttpPost("OperationWithNoXmlDocs")]
[Produces("application/json")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(SerializableError), StatusCodes.Status400BadRequest)]
public ActionResult<string> OperationWithNoXmlDocs()
{
return Ok();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using NJsonSchema;
using NJsonSchema.Generation;
using NSwag.Generation.AspNetCore.Tests.Web.Controllers;
using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Responses;
using Xunit;

namespace NSwag.Generation.AspNetCore.Tests.Responses
Expand Down Expand Up @@ -46,5 +47,81 @@ public async Task When_handling_is_Null_then_response_is_nullable()

Assert.True(operation.ActualResponses.First().Value.Schema.IsNullable(SchemaType.OpenApi3));
}

[Fact]
public async Task When_nullable_xml_docs_is_set_to_true_then_response_is_nullable()
{
// Arrange
var settings = new AspNetCoreOpenApiDocumentGeneratorSettings
{
SchemaType = SchemaType.OpenApi3,
DefaultResponseReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull
};

// Act
var document = await GenerateDocumentAsync(settings, typeof(NullableResponseController));

// Assert
var operation = document.Operations.First(o => o.Path.Contains(nameof(NullableResponseController.OperationWithNullableResponse))).Operation;

Assert.True(operation.ActualResponses.First().Value.Schema.IsNullable(SchemaType.OpenApi3));
}

[Fact]
public async Task When_nullable_xml_docs_is_set_to_false_then_response_is_not_nullable()
{
// Arrange
var settings = new AspNetCoreOpenApiDocumentGeneratorSettings
{
SchemaType = SchemaType.OpenApi3,
DefaultResponseReferenceTypeNullHandling = ReferenceTypeNullHandling.Null
};

// Act
var document = await GenerateDocumentAsync(settings, typeof(NullableResponseController));

// Assert
var operation = document.Operations.First(o => o.Path.Contains(nameof(NullableResponseController.OperationWithNonNullableResponse))).Operation;

Assert.False(operation.ActualResponses.First().Value.Schema.IsNullable(SchemaType.OpenApi3));
}

[Fact]
public async Task When_nullable_xml_docs_is_not_set_then_default_setting_NotNull_is_used()
{
// Arrange
var settings = new AspNetCoreOpenApiDocumentGeneratorSettings
{
SchemaType = SchemaType.OpenApi3,
DefaultResponseReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull
};

// Act
var document = await GenerateDocumentAsync(settings, typeof(NullableResponseController));

// Assert
var operation = document.Operations.First(o => o.Path.Contains(nameof(NullableResponseController.OperationWithNoXmlDocs))).Operation;

Assert.False(operation.ActualResponses.First().Value.Schema.IsNullable(SchemaType.OpenApi3));
}

[Fact]
public async Task When_nullable_xml_docs_is_not_set_then_default_setting_Null_is_used()
{
// Arrange
var settings = new AspNetCoreOpenApiDocumentGeneratorSettings
{
SchemaType = SchemaType.OpenApi3,
DefaultResponseReferenceTypeNullHandling = ReferenceTypeNullHandling.Null
};

// Act
var document = await GenerateDocumentAsync(settings, typeof(NullableResponseController));

// Assert
var operation = document.Operations.First(o => o.Path.Contains(nameof(NullableResponseController.OperationWithNoXmlDocs))).Operation;

Assert.True(operation.ActualResponses.First().Value.Schema.IsNullable(SchemaType.OpenApi3));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,14 @@ public bool Process(OperationProcessorContext operationProcessorContext)
var returnTypeAttributes = context.MethodInfo.ReturnParameter?.GetCustomAttributes(false).OfType<Attribute>();
var contextualReturnType = returnType.ToContextualType(returnTypeAttributes);

var typeDescription = _settings.ReflectionService.GetDescription(
contextualReturnType, _settings.DefaultResponseReferenceTypeNullHandling, _settings);
var nullableXmlAttribute = GetResponseXmlDocsElement(context.MethodInfo, httpStatusCode)?.Attribute("nullable");
var isResponseNullable = nullableXmlAttribute != null ?
nullableXmlAttribute.Value.ToLowerInvariant() == "true" :
_settings.ReflectionService.GetDescription(contextualReturnType, _settings.DefaultResponseReferenceTypeNullHandling, _settings).IsNullable;

response.IsNullableRaw = typeDescription.IsNullable;
response.Schema = context.SchemaGenerator
.GenerateWithReferenceAndNullability<JsonSchema>(contextualReturnType, typeDescription.IsNullable, context.SchemaResolver);
response.IsNullableRaw = isResponseNullable;
response.Schema = context.SchemaGenerator.GenerateWithReferenceAndNullability<JsonSchema>(
contextualReturnType, isResponseNullable, context.SchemaResolver);
}

context.OperationDescription.Operation.Responses[httpStatusCode] = response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NJsonSchema;
using NJsonSchema.Annotations;
using NJsonSchema.Generation;
using NSwag.Annotations;

namespace NSwag.Generation.WebApi.Tests.Nullability
Expand Down Expand Up @@ -41,7 +42,10 @@ public object Ghi()
public async Task When_response_is_not_nullable_then_nullable_is_false_in_spec()
{
/// Arrange
var generator = new WebApiOpenApiDocumentGenerator(new WebApiOpenApiDocumentGeneratorSettings());
var generator = new WebApiOpenApiDocumentGenerator(new WebApiOpenApiDocumentGeneratorSettings
{
DefaultResponseReferenceTypeNullHandling = ReferenceTypeNullHandling.Null
});

/// Act
var document = await generator.GenerateForControllerAsync<NotNullResponseTestController>();
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Generation/OpenApiDocumentGeneratorSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class OpenApiDocumentGeneratorSettings : JsonSchemaGeneratorSettings
public OpenApiDocumentGeneratorSettings()
{
SchemaGenerator = new OpenApiSchemaGenerator(this);
DefaultResponseReferenceTypeNullHandling = ReferenceTypeNullHandling.Null;
DefaultResponseReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull;
SchemaType = SchemaType.Swagger2;
}

Expand Down
40 changes: 29 additions & 11 deletions src/NSwag.Generation/Processors/OperationResponseProcessorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ protected void UpdateResponseDescription(OperationProcessorContext operationProc
{
var returnParameter = operationProcessorContext.MethodInfo.ReturnParameter.ToContextualParameter();

var operationXmlDocs = operationProcessorContext.MethodInfo.GetXmlDocsElement();
var operationXmlDocsNodes = operationXmlDocs?.Nodes()?.OfType<XElement>();
var returnParameterXmlDocs = returnParameter.GetDescription() ?? string.Empty;
var operationXmlDocsNodes = GetResponseXmlDocsNodes(operationProcessorContext.MethodInfo);

if (!string.IsNullOrEmpty(returnParameterXmlDocs) || operationXmlDocsNodes?.Any() == true)
{
Expand All @@ -69,10 +68,7 @@ protected void UpdateResponseDescription(OperationProcessorContext operationProc
if (string.IsNullOrEmpty(response.Value.Description))
{
// Support for <response code="201">Order created</response> tags
var responseXmlDocs = operationXmlDocsNodes?.SingleOrDefault(n =>
n.Name == "response" &&
n.Attributes().Any(a => a.Name == "code" && a.Value == response.Key))?.Value;

var responseXmlDocs = GetResponseXmlDocsElement(operationProcessorContext.MethodInfo, response.Key)?.Value;
if (!string.IsNullOrEmpty(responseXmlDocs))
{
response.Value.Description = responseXmlDocs;
Expand All @@ -86,6 +82,22 @@ protected void UpdateResponseDescription(OperationProcessorContext operationProc
}
}

/// <summary>Gets the XML documentation element for the given response code or null.</summary>
/// <param name="methodInfo">The method info.</param>
/// <param name="responseCode">The response code.</param>
/// <returns>The XML element or null.</returns>
protected XElement GetResponseXmlDocsElement(MethodInfo methodInfo, string responseCode)
{
var operationXmlDocsNodes = GetResponseXmlDocsNodes(methodInfo);
return operationXmlDocsNodes?.SingleOrDefault(n => n.Name == "response" && n.Attributes().Any(a => a.Name == "code" && a.Value == responseCode));
}

private IEnumerable<XElement> GetResponseXmlDocsNodes(MethodInfo methodInfo)
{
var operationXmlDocs = methodInfo.GetXmlDocsElement();
return operationXmlDocs?.Nodes()?.OfType<XElement>();
}

private IEnumerable<OperationResponseDescription> GetOperationResponseDescriptions(IEnumerable<Attribute> responseTypeAttributes, string successResponseDescription)
{
foreach (var attribute in responseTypeAttributes)
Expand Down Expand Up @@ -165,12 +177,18 @@ private void ProcessOperationDescriptions(IEnumerable<OperationResponseDescripti

if (IsVoidResponse(returnType) == false)
{
var isNullable = statusCodeGroup.Any(r => r.IsNullable) && typeDescription.IsNullable;

response.IsNullableRaw = isNullable;
response.ExpectedSchemas = GenerateExpectedSchemas(statusCodeGroup, context);
response.Schema = context.SchemaGenerator
.GenerateWithReferenceAndNullability<JsonSchema>(contextualReturnType, isNullable, context.SchemaResolver);

var nullableXmlAttribute = GetResponseXmlDocsElement(context.MethodInfo, httpStatusCode)?.Attribute("nullable");

var isResponseNullable = nullableXmlAttribute != null ?
nullableXmlAttribute.Value.ToLowerInvariant() == "true" :
statusCodeGroup.Any(r => r.IsNullable) &&
_settings.ReflectionService.GetDescription(contextualReturnType, _settings.DefaultResponseReferenceTypeNullHandling, _settings).IsNullable;

response.IsNullableRaw = isResponseNullable;
response.Schema = context.SchemaGenerator.GenerateWithReferenceAndNullability<JsonSchema>(
contextualReturnType, isResponseNullable, context.SchemaResolver);
}

context.OperationDescription.Operation.Responses[httpStatusCode] = response;
Expand Down
12 changes: 6 additions & 6 deletions src/NSwag.Integration.ClientPCL/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@
"description": ""
},
"450": {
"x-nullable": true,
"x-nullable": false,
"description": "A custom error occured.",
"schema": {
"$ref": "#/definitions/Exception"
Expand Down Expand Up @@ -445,7 +445,7 @@
],
"responses": {
"500": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"$ref": "#/definitions/PersonNotFoundException"
Expand Down Expand Up @@ -528,14 +528,14 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"$ref": "#/definitions/Person"
}
},
"500": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"$ref": "#/definitions/PersonNotFoundException"
Expand Down Expand Up @@ -564,14 +564,14 @@
],
"responses": {
"200": {
"x-nullable": true,
"x-nullable": false,
"description": "The person's name.",
"schema": {
"type": "string"
}
},
"500": {
"x-nullable": true,
"x-nullable": false,
"description": "",
"schema": {
"$ref": "#/definitions/PersonNotFoundException"
Expand Down
Loading

0 comments on commit 0987a1a

Please sign in to comment.