From f089ec75bdb3630ee3c77635727ea0c5c4144436 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Thu, 28 Jul 2022 18:30:33 +0200 Subject: [PATCH] EnvironmentVariableHelper support for boolean (#3457) --- .../Internal/EnvironmentVariableHelper.cs | 28 ++++++++++++++ .../EnvironmentVariableHelperTests.cs | 38 +++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs b/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs index df3f89df0aa..f6ea9783590 100644 --- a/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs +++ b/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs @@ -111,5 +111,33 @@ public static bool LoadUri(string envVarKey, out Uri result) return true; } + + /// + /// Reads an environment variable and parses it as a . + /// + /// The name of the environment variable. + /// The parsed value of the environment variable. + /// + /// Returns true when a non-empty value was read; otherwise, false. + /// + /// + /// Thrown when failed to parse the non-empty value. + /// + 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; + } } } diff --git a/test/OpenTelemetry.Tests/Internal/EnvironmentVariableHelperTests.cs b/test/OpenTelemetry.Tests/Internal/EnvironmentVariableHelperTests.cs index 290e5ceb77b..738fa27b9b3 100644 --- a/test/OpenTelemetry.Tests/Internal/EnvironmentVariableHelperTests.cs +++ b/test/OpenTelemetry.Tests/Internal/EnvironmentVariableHelperTests.cs @@ -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(() => EnvironmentVariableHelper.LoadBoolean(EnvVar, out bool _)); + } + [Theory] [InlineData("123", 123)] [InlineData("0", 0)]