|
| 1 | +package env |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +// resolve returns the effective value of key in e, mirroring how os/exec |
| 9 | +// dedups duplicate keys: the last occurrence wins. |
| 10 | +func resolve(e Environ, key Key) (string, bool) { |
| 11 | + value, found := "", false |
| 12 | + prefix := string(key) + "=" |
| 13 | + for _, entry := range e { |
| 14 | + if strings.HasPrefix(entry, prefix) { |
| 15 | + value, found = strings.TrimPrefix(entry, prefix), true |
| 16 | + } |
| 17 | + } |
| 18 | + return value, found |
| 19 | +} |
| 20 | + |
| 21 | +// Guards against telemetry from integration tests reaching the production |
| 22 | +// analytics backend: the base env helpers must default the analytics endpoint |
| 23 | +// to an unreachable address unless a test explicitly overrides it. |
| 24 | +func TestBaseEnvDefaultsAnalyticsEndpointToUnreachable(t *testing.T) { |
| 25 | + cases := map[string]Environ{ |
| 26 | + "With": With("SOME_VAR", "value"), |
| 27 | + "Without": Without(AuthToken), |
| 28 | + } |
| 29 | + for name, e := range cases { |
| 30 | + t.Run(name, func(t *testing.T) { |
| 31 | + got, found := resolve(e, AnalyticsEndpoint) |
| 32 | + if !found { |
| 33 | + t.Fatalf("%s did not set %s", name, AnalyticsEndpoint) |
| 34 | + } |
| 35 | + if got != UnreachableAnalyticsEndpoint { |
| 36 | + t.Fatalf("%s analytics endpoint = %q, want %q", name, got, UnreachableAnalyticsEndpoint) |
| 37 | + } |
| 38 | + }) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func TestExplicitAnalyticsEndpointOverridesDefault(t *testing.T) { |
| 43 | + const mock = "http://127.0.0.1:54321" |
| 44 | + e := With(APIEndpoint, "http://example").With(AnalyticsEndpoint, mock) |
| 45 | + got, _ := resolve(e, AnalyticsEndpoint) |
| 46 | + if got != mock { |
| 47 | + t.Fatalf("analytics endpoint = %q, want %q (explicit override must win over default)", got, mock) |
| 48 | + } |
| 49 | +} |
0 commit comments