EnvironmentVariableHelper support for boolean (#3457)

This commit is contained in:
Piotr Kiełkowicz 2022-07-28 18:30:33 +02:00 committed by GitHub
parent c1f376ac8b
commit f089ec75bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 66 additions and 0 deletions

View File

@ -111,5 +111,33 @@ namespace OpenTelemetry.Internal
return true;
}
/// <summary>
/// Reads an environment variable and parses it as a <see cref="bool" />.
/// </summary>
/// <param name="envVarKey">The name of the environment variable.</param>
/// <param name="result">The parsed value of the environment variable.</param>
/// <returns>
/// Returns <c>true</c> when a non-empty value was read; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="FormatException">
/// Thrown when failed to parse the non-empty value.
/// </exception>
public static bool LoadBoolean(string envVarKey, out bool result)
{
result = default;
if (!LoadString(envVarKey, out string value))
{
return false;
}
if (!bool.TryParse(value, out result))
{
throw new FormatException($"{envVarKey} environment variable has an invalid value: '${value}'");
}
return true;
}
}
}

View File

@ -55,6 +55,44 @@ namespace OpenTelemetry.Internal.Tests
Assert.Null(actualValue);
}
[Theory]
[InlineData("true", true)]
[InlineData("TRUE", true)]
[InlineData("false", false)]
[InlineData("FALSE", false)]
[InlineData(" true ", true)]
[InlineData(" false ", false)]
public void LoadBoolean(string value, bool expectedValue)
{
Environment.SetEnvironmentVariable(EnvVar, value);
bool actualBool = EnvironmentVariableHelper.LoadBoolean(EnvVar, out bool actualValue);
Assert.True(actualBool);
Assert.Equal(expectedValue, actualValue);
}
[Fact]
public void LoadBoolean_NoValue()
{
bool actualBool = EnvironmentVariableHelper.LoadBoolean(EnvVar, out bool actualValue);
Assert.False(actualBool);
Assert.False(actualValue);
}
[Theory]
[InlineData("something")] // non true/false
[InlineData(" ")] // whitespaces
[InlineData("0")] // 0
[InlineData("1")] // 1
public void LoadBoolean_Invalid(string value)
{
Environment.SetEnvironmentVariable(EnvVar, value);
Assert.Throws<FormatException>(() => EnvironmentVariableHelper.LoadBoolean(EnvVar, out bool _));
}
[Theory]
[InlineData("123", 123)]
[InlineData("0", 0)]