1// +build go1.7
2
3package session
4
5import (
6	"os"
7	"path/filepath"
8	"strings"
9	"testing"
10
11	"github.com/aws/aws-sdk-go/internal/sdktesting"
12)
13
14func TestSession_loadCSMConfig(t *testing.T) {
15	defConfigFiles := []string{
16		filepath.Join("testdata", "csm_shared_config"),
17	}
18	cases := map[string]struct {
19		Envs        map[string]string
20		ConfigFiles []string
21		CSMProfile  string
22
23		Expect csmConfig
24		Err    string
25	}{
26		"no config": {
27			Envs:        map[string]string{},
28			Expect:      csmConfig{},
29			ConfigFiles: defConfigFiles,
30			CSMProfile:  "aws_csm_empty",
31		},
32		"env enabled": {
33			Envs: map[string]string{
34				"AWS_CSM_ENABLED":   "true",
35				"AWS_CSM_PORT":      "4321",
36				"AWS_CSM_HOST":      "ahost",
37				"AWS_CSM_CLIENT_ID": "client id",
38			},
39			Expect: csmConfig{
40				Enabled:  true,
41				Port:     "4321",
42				Host:     "ahost",
43				ClientID: "client id",
44			},
45		},
46		"shared cfg enabled": {
47			ConfigFiles: defConfigFiles,
48			Expect: csmConfig{
49				Enabled:  true,
50				Port:     "1234",
51				Host:     "bar",
52				ClientID: "foo",
53			},
54		},
55		"mixed cfg, use env": {
56			Envs: map[string]string{
57				"AWS_CSM_ENABLED": "true",
58			},
59			ConfigFiles: defConfigFiles,
60			Expect: csmConfig{
61				Enabled: true,
62			},
63		},
64		"mixed cfg, use env disabled": {
65			Envs: map[string]string{
66				"AWS_CSM_ENABLED": "false",
67			},
68			ConfigFiles: defConfigFiles,
69			Expect: csmConfig{
70				Enabled: false,
71			},
72		},
73		"mixed cfg, use shared config": {
74			Envs: map[string]string{
75				"AWS_CSM_PORT": "4321",
76			},
77			ConfigFiles: defConfigFiles,
78			Expect: csmConfig{
79				Enabled:  true,
80				Port:     "1234",
81				Host:     "bar",
82				ClientID: "foo",
83			},
84		},
85	}
86
87	for name, c := range cases {
88		t.Run(name, func(t *testing.T) {
89			restoreFn := sdktesting.StashEnv()
90			defer restoreFn()
91
92			if len(c.CSMProfile) != 0 {
93				csmProfile := csmProfileName
94				defer func() {
95					csmProfileName = csmProfile
96				}()
97				csmProfileName = c.CSMProfile
98			}
99
100			for name, v := range c.Envs {
101				os.Setenv(name, v)
102			}
103
104			envCfg, err := loadEnvConfig()
105			if err != nil {
106				t.Fatalf("failed to load the envcfg, %v", err)
107			}
108			csmCfg, err := loadCSMConfig(envCfg, c.ConfigFiles)
109			if len(c.Err) != 0 {
110				if err == nil {
111					t.Fatalf("expect error, got none")
112				}
113				if e, a := c.Err, err.Error(); !strings.Contains(a, e) {
114					t.Errorf("expect %v in error %v", e, a)
115				}
116				return
117			}
118
119			if e, a := c.Expect, csmCfg; e != a {
120				t.Errorf("expect %v CSM config got %v", e, a)
121			}
122		})
123	}
124}
125