Skip to content

Commit

Permalink
[WIP]Update Client.Class.liquid - issue 2736. AllowEmptyInputInBodyMo…
Browse files Browse the repository at this point in the history
…delBinding (RicoSuter#3195)

* Update Client.Class.liquid - issue 2736. Fix for AllowEmptyInputInBodyModelBinding

* Update Client.Class.liquid

Co-authored-by: Vitaly Melnik <[email protected]>
Co-authored-by: Rico Suter <[email protected]>
  • Loading branch information
3 people authored Dec 18, 2020
1 parent 1ffae3a commit e5d6903
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NSwag.Generation.WebApi;
using Xunit;

namespace NSwag.CodeGeneration.CSharp.Tests
{
public class AllowNullableBodyParametersTests
{
[Fact]
public async Task TestNullableBodyWithAllowNullableBodyParameters()
{
//// Arrange
var generator = await GenerateCode(true);

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

//// Assert
Assert.False(HasGuardForBodyIsNull(code));
}

[Fact]
public async Task TestNullableBodyWithoutAllowNullableBodyParameters()
{
//// Arrange
var generator = await GenerateCode(false);

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

//// Assert
Assert.True(HasGuardForBodyIsNull(code));
}

private static async Task<CSharpClientGenerator> GenerateCode(bool allowNullableBodyParameters)
{
var swaggerGenerator = new WebApiOpenApiDocumentGenerator(new WebApiOpenApiDocumentGeneratorSettings
{
AllowNullableBodyParameters = allowNullableBodyParameters
});
var document = await swaggerGenerator.GenerateForControllerAsync<TestController>();

var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings
{
InjectHttpClient = false,
ConfigurationClass = "MyConfig",
ClientBaseClass = "MyBaseClass"
});
return generator;
}

private static bool HasGuardForBodyIsNull(string code)
{
return code.Contains("throw new System.ArgumentNullException");
}

public class TestController : Controller
{
[Route("Foo")]
public string Foo([FromBody] [Required] T requiredBody)
{
return string.Empty;
}

[Route("Bar")]
public void Bar([FromBody] T notRequiredBody)
{
}

public class T
{
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@

{% endif -%}
{% endfor -%}
{% if operation.HasContent and operation.ContentParameter.IsRequired -%}
{% if operation.HasContent and operation.ContentParameter.IsNullable != true -%}
if ({{ operation.ContentParameter.VariableName }} == null)
throw new System.ArgumentNullException("{{ operation.ContentParameter.VariableName }}");

Expand Down

0 comments on commit e5d6903

Please sign in to comment.