Skip to content

Commit

Permalink
EnvironmentVariableHelper support for boolean (#3457)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kielek authored Jul 28, 2022
1 parent c1f376a commit f089ec7
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,5 +111,33 @@ public static bool LoadUri(string envVarKey, out Uri result)

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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,44 @@ public void LoadString_NoValue()
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)]
Expand Down

0 comments on commit f089ec7

Please sign in to comment.