File: env_extractor_test.go

package info (click to toggle)
golang-gitlab-gitlab-org-labkit 1.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,092 kB
  • sloc: sh: 210; javascript: 49; makefile: 4
file content (97 lines) | stat: -rw-r--r-- 2,161 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package tracing

import (
	"context"
	"os"
	"reflect"
	"testing"

	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/labkit/correlation"
)

func TestExtractFromEnv(t *testing.T) {
	tests := []struct {
		name              string
		ctx               context.Context
		opts              []ExtractFromEnvOption
		additionalEnv     map[string]string
		wantCorrelationID string
	}{
		{
			name: "no_options",
			ctx:  context.Background(),
			opts: []ExtractFromEnvOption{},
		},
		{
			name: "pass_correlation_id",
			ctx:  context.Background(),
			opts: []ExtractFromEnvOption{},
			additionalEnv: map[string]string{
				envCorrelationIDKey: "abc123",
			},
			wantCorrelationID: "abc123",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			resetEnvironment := addAdditionalEnv(tt.additionalEnv)
			defer resetEnvironment()

			ctx, finished := ExtractFromEnv(tt.ctx, tt.opts...)
			require.NotNil(t, ctx, "ctx is nil")
			require.NotNil(t, finished, "finished is nil")
			gotCorrelationID := correlation.ExtractFromContext(ctx)
			require.Equal(t, tt.wantCorrelationID, gotCorrelationID)
			defer finished()
		})
	}
}

func Test_environAsMap(t *testing.T) {
	tests := []struct {
		name string
		env  []string
		want map[string]string
	}{
		{
			name: "trivial",
			env:  nil,
			want: map[string]string{},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := environAsMap(tt.env); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("environAsMap() = %v, want %v", got, tt.want)
			}
		})
	}
}

// addAdditionalEnv will configure additional environment values
// and return a deferrable function to reset the environment to
// it's original state after the test.
func addAdditionalEnv(envMap map[string]string) func() {
	prevValues := map[string]string{}
	unsetValues := []string{}
	for k, v := range envMap {
		value, exists := os.LookupEnv(k)
		if exists {
			prevValues[k] = value
		} else {
			unsetValues = append(unsetValues, k)
		}
		os.Setenv(k, v)
	}

	return func() {
		for k, v := range prevValues {
			os.Setenv(k, v)
		}

		for _, k := range unsetValues {
			os.Unsetenv(k)
		}
	}
}