1
0
mirror of https://github.com/nginxinc/nginx-prometheus-exporter.git synced 2025-08-08 05:02:04 +03:00

Add Environment Variable options to flags managed in exporter-toolkit (#607)

* add env var options to flags managed in exporter-toolkit
This commit is contained in:
oseoin
2024-01-25 10:18:06 +00:00
committed by GitHub
parent c41546fdaf
commit aa81230e53
3 changed files with 89 additions and 2 deletions

View File

@@ -4,6 +4,9 @@ import (
"reflect"
"testing"
"time"
"github.com/alecthomas/kingpin/v2"
"github.com/prometheus/exporter-toolkit/web/kingpinflag"
)
func TestParsePositiveDuration(t *testing.T) {
@@ -103,3 +106,61 @@ func TestParseUnixSocketAddress(t *testing.T) {
})
}
}
func TestAddMissingEnvironmentFlags(t *testing.T) {
expectedMatches := map[string]string{
"non-matching-flag": "",
"web.missing-env": "MISSING_ENV",
"web.has-env": "HAS_ENV_ALREADY",
"web.listen-address": "LISTEN_ADDRESS",
"web.config.file": "CONFIG_FILE",
}
kingpinflag.AddFlags(kingpin.CommandLine, ":9113")
kingpin.Flag("non-matching-flag", "").String()
kingpin.Flag("web.missing-env", "").String()
kingpin.Flag("web.has-env", "").Envar("HAS_ENV_ALREADY").String()
addMissingEnvironmentFlags(kingpin.CommandLine)
// using Envar() on a flag returned from GetFlag()
// adds an additional flag, which is processed correctly
// at runtime but means that we need to check for a match
// instead of checking the envar of each matching flag name
for k, v := range expectedMatches {
matched := false
for _, f := range kingpin.CommandLine.Model().FlagGroupModel.Flags {
if f.Name == k && f.Envar == v {
matched = true
}
}
if !matched {
t.Errorf("missing %s envar for %s", v, k)
}
}
}
func TestConvertFlagToEnvar(t *testing.T) {
cases := []struct {
input string
output string
}{
{
input: "dot.separate",
output: "DOT_SEPARATE",
},
{
input: "underscore_separate",
output: "UNDERSCORE_SEPARATE",
},
{
input: "mixed_separate_options",
output: "MIXED_SEPARATE_OPTIONS",
},
}
for _, c := range cases {
res := convertFlagToEnvar(c.input)
if res != c.output {
t.Errorf("expected %s to resolve to %s but got %s", c.input, c.output, res)
}
}
}