forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_test.go
310 lines (251 loc) · 8.39 KB
/
config_test.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/plugin"
)
func newConfig() config {
var conf config
conf.PluginMinPort = 10000
conf.PluginMaxPort = 25000
conf.Builders = packer.MapOfBuilder{}
conf.PostProcessors = packer.MapOfPostProcessor{}
conf.Provisioners = packer.MapOfProvisioner{}
return conf
}
func TestDiscoverReturnsIfMagicCookieSet(t *testing.T) {
config := newConfig()
os.Setenv(plugin.MagicCookieKey, plugin.MagicCookieValue)
defer os.Unsetenv(plugin.MagicCookieKey)
err := config.Discover()
if err != nil {
t.Fatalf("Should not have errored: %s", err)
}
if len(config.Builders) != 0 {
t.Fatalf("Should not have tried to find builders")
}
}
func TestEnvVarPackerPluginPath(t *testing.T) {
// Create a temporary directory to store plugins in
dir, _, cleanUpFunc, err := generateFakePlugins("custom_plugin_dir",
[]string{"packer-provisioner-partyparrot"})
if err != nil {
t.Fatalf("Error creating fake custom plugins: %s", err)
}
defer cleanUpFunc()
// Add temp dir to path.
os.Setenv("PACKER_PLUGIN_PATH", dir)
defer os.Unsetenv("PACKER_PLUGIN_PATH")
config := newConfig()
err = config.Discover()
if err != nil {
t.Fatalf("Should not have errored: %s", err)
}
if len(config.Provisioners) == 0 {
t.Fatalf("Should have found partyparrot provisioner")
}
if _, ok := config.Provisioners["partyparrot"]; !ok {
t.Fatalf("Should have found partyparrot provisioner.")
}
}
func TestEnvVarPackerPluginPath_MultiplePaths(t *testing.T) {
// Create a temporary directory to store plugins in
dir, _, cleanUpFunc, err := generateFakePlugins("custom_plugin_dir",
[]string{"packer-provisioner-partyparrot"})
if err != nil {
t.Fatalf("Error creating fake custom plugins: %s", err)
}
defer cleanUpFunc()
pathsep := ":"
if runtime.GOOS == "windows" {
pathsep = ";"
}
// Create a second dir to look in that will be empty
decoyDir, err := ioutil.TempDir("", "decoy")
if err != nil {
t.Fatalf("Failed to create a temporary test dir.")
}
defer os.Remove(decoyDir)
pluginPath := dir + pathsep + decoyDir
// Add temp dir to path.
os.Setenv("PACKER_PLUGIN_PATH", pluginPath)
defer os.Unsetenv("PACKER_PLUGIN_PATH")
config := newConfig()
err = config.Discover()
if err != nil {
t.Fatalf("Should not have errored: %s", err)
}
if len(config.Provisioners) == 0 {
t.Fatalf("Should have found partyparrot provisioner")
}
if _, ok := config.Provisioners["partyparrot"]; !ok {
t.Fatalf("Should have found partyparrot provisioner.")
}
}
func TestDecodeConfig(t *testing.T) {
packerConfig := `
{
"PluginMinPort": 10,
"PluginMaxPort": 25,
"disable_checkpoint": true,
"disable_checkpoint_signature": true,
"provisioners": {
"super-shell": "packer-provisioner-super-shell"
}
}`
var cfg config
err := decodeConfig(strings.NewReader(packerConfig), &cfg)
if err != nil {
t.Fatalf("error encountered decoding configuration: %v", err)
}
var expectedCfg config
json.NewDecoder(strings.NewReader(packerConfig)).Decode(&expectedCfg)
if !reflect.DeepEqual(cfg, expectedCfg) {
t.Errorf("failed to load custom configuration data; expected %v got %v", expectedCfg, cfg)
}
}
func TestLoadExternalComponentsFromConfig(t *testing.T) {
packerConfigData, cleanUpFunc, err := generateFakePackerConfigData()
if err != nil {
t.Fatalf("error encountered while creating fake Packer configuration data %v", err)
}
defer cleanUpFunc()
var cfg config
cfg.Builders = packer.MapOfBuilder{}
cfg.PostProcessors = packer.MapOfPostProcessor{}
cfg.Provisioners = packer.MapOfProvisioner{}
if err := decodeConfig(strings.NewReader(packerConfigData), &cfg); err != nil {
t.Fatalf("error encountered decoding configuration: %v", err)
}
cfg.LoadExternalComponentsFromConfig()
if len(cfg.Builders) != 1 || !cfg.Builders.Has("cloud-xyz") {
t.Errorf("failed to load external builders; got %v as the resulting config", cfg.Builders)
}
if len(cfg.PostProcessors) != 1 || !cfg.PostProcessors.Has("noop") {
t.Errorf("failed to load external post-processors; got %v as the resulting config", cfg.PostProcessors)
}
if len(cfg.Provisioners) != 1 || !cfg.Provisioners.Has("super-shell") {
t.Errorf("failed to load external provisioners; got %v as the resulting config", cfg.Provisioners)
}
}
func TestLoadExternalComponentsFromConfig_onlyProvisioner(t *testing.T) {
packerConfigData, cleanUpFunc, err := generateFakePackerConfigData()
if err != nil {
t.Fatalf("error encountered while creating fake Packer configuration data %v", err)
}
defer cleanUpFunc()
var cfg config
cfg.Provisioners = packer.MapOfProvisioner{}
if err := decodeConfig(strings.NewReader(packerConfigData), &cfg); err != nil {
t.Fatalf("error encountered decoding configuration: %v", err)
}
/* Let's clear out any custom Builders or PostProcessors that were part of the config.
This step does not remove them from disk, it just removes them from of plugins Packer knows about.
*/
cfg.RawBuilders = nil
cfg.RawPostProcessors = nil
cfg.LoadExternalComponentsFromConfig()
if len(cfg.Builders) != 0 {
t.Errorf("loaded external builders when it wasn't supposed to; got %v as the resulting config", cfg.Builders)
}
if len(cfg.PostProcessors) != 0 {
t.Errorf("loaded external post-processors when it wasn't supposed to; got %v as the resulting config", cfg.PostProcessors)
}
if len(cfg.Provisioners) != 1 || !cfg.Provisioners.Has("super-shell") {
t.Errorf("failed to load external provisioners; got %v as the resulting config", cfg.Provisioners)
}
}
func TestLoadSingleComponent(t *testing.T) {
// .exe will work everyone for testing purpose, but mostly here to help Window's test runs.
tmpFile, err := ioutil.TempFile(".", "packer-builder-*.exe")
if err != nil {
t.Fatalf("failed to create test file with error: %s", err)
}
defer os.Remove(tmpFile.Name())
tt := []struct {
pluginPath string
errorExpected bool
}{
{pluginPath: tmpFile.Name(), errorExpected: false},
{pluginPath: "./non-existing-file", errorExpected: true},
}
var cfg config
cfg.Builders = packer.MapOfBuilder{}
cfg.PostProcessors = packer.MapOfPostProcessor{}
cfg.Provisioners = packer.MapOfProvisioner{}
for _, tc := range tt {
tc := tc
_, err := cfg.loadSingleComponent(tc.pluginPath)
if tc.errorExpected && err == nil {
t.Errorf("expected loadSingleComponent(%s) to error but it didn't", tc.pluginPath)
continue
}
if err != nil && !tc.errorExpected {
t.Errorf("expected loadSingleComponent(%s) to load properly but got an error: %v", tc.pluginPath, err)
}
}
}
func generateFakePlugins(dirname string, pluginNames []string) (string, []string, func(), error) {
dir, err := ioutil.TempDir("", dirname)
if err != nil {
return "", nil, nil, fmt.Errorf("failed to create temporary test directory: %v", err)
}
cleanUpFunc := func() {
os.RemoveAll(dir)
}
var suffix string
if runtime.GOOS == "windows" {
suffix = ".exe"
}
plugins := make([]string, len(pluginNames))
for i, plugin := range pluginNames {
plug := filepath.Join(dir, plugin+suffix)
plugins[i] = plug
_, err := os.Create(plug)
if err != nil {
cleanUpFunc()
return "", nil, nil, fmt.Errorf("failed to create temporary plugin file (%s): %v", plug, err)
}
}
return dir, plugins, cleanUpFunc, nil
}
/* generateFakePackerConfigData creates a collection of mock plugins along with a basic packerconfig.
The return packerConfigData is a valid packerconfig file that can be used for configuring external plugins, cleanUpFunc is a function that should be called for cleaning up any generated mock data.
This function will only clean up if there is an error, on successful runs the caller
is responsible for cleaning up the data via cleanUpFunc().
*/
func generateFakePackerConfigData() (packerConfigData string, cleanUpFunc func(), err error) {
_, plugins, cleanUpFunc, err := generateFakePlugins("random-testdata",
[]string{"packer-builder-cloud-xyz",
"packer-provisioner-super-shell",
"packer-post-processor-noop"})
if err != nil {
cleanUpFunc()
return "", nil, err
}
packerConfigData = fmt.Sprintf(`
{
"PluginMinPort": 10,
"PluginMaxPort": 25,
"disable_checkpoint": true,
"disable_checkpoint_signature": true,
"builders": {
"cloud-xyz": %q
},
"provisioners": {
"super-shell": %q
},
"post-processors": {
"noop": %q
}
}`, plugins[0], plugins[1], plugins[2])
return
}