Skip to content

Binding of empty string is inconsistent between reflection and source generator configuration binders #132968

Description

@svick

The following tests fail for the source generated configuration binder, but succeed for the reflection binder, showing inconsistencies between the two binders. I think these should be fixed. It's likely that some fixes will require changing the source generator, and others changing the reflection binder. (In other words, one of these tests succeeding doesn't necessarily mean it's the correct behavior.)

[Fact]
public void GetValue_EmptyStringForString_ReturnsEmptyString()
{
    IConfiguration config = TestHelpers.GetConfigurationFromJsonString("""{ "Value": "" }""");

    Assert.Equal(string.Empty, config.GetValue<string>("Value"));
}

[Fact]
public void GetValue_EmptyStringForInt32_Throws()
{
    IConfiguration config = TestHelpers.GetConfigurationFromJsonString("""{ "Value": "" }""");

    Assert.Throws<InvalidOperationException>(() => config.GetValue<int>("Value"));
}

[Fact]
public void GetValue_EmptyStringForByteArray_ReturnsEmptyArray()
{
    IConfiguration config = TestHelpers.GetConfigurationFromJsonString("""{ "Value": "" }""");

    Assert.Empty(Assert.IsType<byte[]>(config.GetValue<byte[]>("Value")));
}

[Fact]
public void Get_EmptyStringForNullableInt32_ReturnsNull()
{
    IConfiguration config = TestHelpers.GetConfigurationFromJsonString("""{ "Value": "" }""");

    Assert.Null(config.GetSection("Value").Get<int?>());
}

[Fact]
public void Get_EmptyStringForInt32_ThrowsConversionException()
{
    IConfiguration config = TestHelpers.GetConfigurationFromJsonString("""{ "Value": "" }""");

    Assert.Throws<InvalidOperationException>(() => config.GetSection("Value").Get<int>());
}

[Fact]
public void Get_EmptyStringArrayElementWithErrorOnUnknownConfiguration_Throws()
{
    IConfiguration config = TestHelpers.GetConfigurationFromJsonString("""{ "Values": [ "" ] }""");

    Assert.Throws<InvalidOperationException>(
        () => config.GetSection("Values").Get<int[]>(o => o.ErrorOnUnknownConfiguration = true));
}

[Fact]
public void Get_EmptyStringDictionaryValueWithErrorOnUnknownConfiguration_Throws()
{
    IConfiguration config = TestHelpers.GetConfigurationFromJsonString("""{ "Values": { "Key": "" } }""");

    Assert.Throws<InvalidOperationException>(
        () => config.GetSection("Values").Get<Dictionary<string, int>>(o => o.ErrorOnUnknownConfiguration = true));
}

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions