File: machine_test.go

package info (click to toggle)
vagrant 2.3.7%2Bgit20230731.5fc64cde%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 17,616 kB
  • sloc: ruby: 111,820; sh: 462; makefile: 123; ansic: 34; lisp: 1
file content (393 lines) | stat: -rw-r--r-- 10,759 bytes parent folder | download | duplicates (2)
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package core

import (
	"testing"

	"github.com/hashicorp/vagrant-plugin-sdk/component"
	"github.com/hashicorp/vagrant-plugin-sdk/core"
	"github.com/hashicorp/vagrant-plugin-sdk/proto/vagrant_plugin_sdk"
	"github.com/hashicorp/vagrant/internal/plugin"
	"github.com/hashicorp/vagrant/internal/server/proto/vagrant_server"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
)

func TestMachineSetValidId(t *testing.T) {
	tm := TestMinimalMachine(t)

	// Set valid id
	tm.SetID("something")
	newId, err := tm.ID()
	if err != nil {
		t.Errorf("Failed to get id")
	}
	require.Equal(t, newId, "something")

	// Ensure new id is save to db
	dbTarget, err := tm.Client().GetTarget(tm.ctx,
		&vagrant_server.GetTargetRequest{
			Target: tm.Ref().(*vagrant_plugin_sdk.Ref_Target),
		},
	)
	if err != nil {
		t.Errorf("Failed to get target")
	}
	require.Equal(t, dbTarget.Target.Uuid, "something")
}

func TestMachineSetEmptyId(t *testing.T) {
	tm := TestMinimalMachine(t)
	oldId := tm.target.ResourceId

	// Set empty id
	tm.SetID("")
	newId, err := tm.ID()
	if err != nil {
		t.Errorf("Failed to get id")
	}
	require.Equal(t, newId, "")

	// Machine won't be deleted from db until project is closed, so close project first
	err = tm.project.Close()
	require.NoError(t, err)

	// Ensure machine is deleted from the db by checking for the old id
	dbTarget, err := tm.Client().GetTarget(tm.ctx,
		&vagrant_server.GetTargetRequest{
			Target: &vagrant_plugin_sdk.Ref_Target{
				ResourceId: oldId,
				Project:    tm.target.Project,
				Name:       tm.target.Name,
			},
		},
	)
	require.Nil(t, dbTarget)
	require.Error(t, err)

	// Verify the DataDir still exists (see below test for more detail on why)
	dir, err := tm.DataDir()
	require.NoError(t, err)
	require.DirExists(t, dir.DataDir().String())

	// Also check new id
	dbTarget, err = tm.Client().GetTarget(tm.ctx,
		&vagrant_server.GetTargetRequest{
			Target: &vagrant_plugin_sdk.Ref_Target{
				ResourceId: "",
				Project:    tm.target.Project,
				Name:       tm.target.Name,
			},
		},
	)
	require.Nil(t, dbTarget)
	require.Error(t, err)
}

func TestMachineSetIdBlankThenSomethingPreservesDataDir(t *testing.T) {
	tm := TestMinimalMachine(t)

	// Set empty id, followed by a temp id. This is the same thing that happens
	// in the Docker provider's InitState action
	require.NoError(t, tm.SetID(""))
	require.NoError(t, tm.SetID("preparing"))

	// The DataDir should still exist; the Docker provider relies on this
	// behavior in order for its provisioning sentinel file handling to work
	// properly.
	dir, err := tm.DataDir()
	require.NoError(t, err)
	require.DirExists(t, dir.DataDir().String())
}

func TestMachineGetNonExistentBox(t *testing.T) {
	tp := TestMinimalProject(t)
	tm := TestMachine(t, tp,
		WithTestTargetConfig(testBoxConfig("somebox")),
		WithTestTargetProvider("testprovider"),
	)

	box, err := tm.Box()
	require.NoError(t, err)
	name, err := box.Name()
	require.NoError(t, err)
	require.Equal(t, name, "somebox")
	provider, err := box.Provider()
	require.NoError(t, err)
	require.Equal(t, provider, "testprovider")
	metaurl, err := box.MetadataURL()
	require.NoError(t, err)
	require.Empty(t, metaurl)
}

func TestMachineGetExistentBox(t *testing.T) {
	tp := TestMinimalProject(t)
	tm := TestMachine(t, tp,
		WithTestTargetConfig(testBoxConfig("test/box")),
		WithTestTargetProvider("virtualbox"),
	)
	testBox := newFullBox(t, testboxBoxData(), tp.basis)
	testBox.Save()

	box, err := tm.Box()
	require.NoError(t, err)
	name, err := box.Name()
	require.NoError(t, err)
	require.Equal(t, name, "test/box")
	provider, err := box.Provider()
	require.NoError(t, err)
	require.NotEmpty(t, provider)
	metaurl, err := box.MetadataURL()
	require.NoError(t, err)
	require.NotEmpty(t, metaurl)
}

func TestMachineConfigedGuest(t *testing.T) {
	commMock := BuildTestCommunicatorPlugin("ssh")
	commMock.On("Ready", mock.AnythingOfType("*core.Machine")).Return(true, nil)
	commPlugin := plugin.TestPlugin(t,
		commMock,
		plugin.WithPluginName("ssh"),
		plugin.WithPluginTypes(component.CommunicatorType),
	)

	type test struct {
		config *component.ConfigData
		errors bool
	}

	tests := []test{
		{config: testGuestConfig("myguest"), errors: false},
		{config: testGuestConfig("idontexist"), errors: true},
	}
	guestMock := BuildTestGuestPlugin("myguest", "")
	guestMock.On("Detect", mock.AnythingOfType("*core.Machine")).Return(true, nil)
	guestMock.On("Parent").Return("", nil)

	pluginManager := plugin.TestManager(t,
		plugin.TestPlugin(t,
			guestMock,
			plugin.WithPluginName("myguest"),
			plugin.WithPluginTypes(component.GuestType),
		),
		commPlugin,
	)

	for _, tc := range tests {
		tp := TestProject(t, WithPluginManager(pluginManager))
		tm := TestMachine(t, tp,
			WithTestTargetConfig(tc.config),
		)
		guest, err := tm.Guest()
		if tc.errors {
			require.Error(t, err)
			require.Nil(t, guest)
			require.Nil(t, tm.cache.Get("guest"))
		} else {
			require.NoError(t, err)
			require.NotNil(t, guest)
			require.NotNil(t, tm.cache.Get("guest"))
		}
	}
}

func TestMachineNoConfigGuest(t *testing.T) {
	commMock := BuildTestCommunicatorPlugin("ssh")
	commMock.On("Ready", mock.AnythingOfType("*core.Machine")).Return(true, nil)
	commPlugin := plugin.TestPlugin(t,
		commMock,
		plugin.WithPluginName("ssh"),
		plugin.WithPluginTypes(component.CommunicatorType),
	)

	guestMock := BuildTestGuestPlugin("myguest", "")
	guestMock.On("Detect", mock.AnythingOfType("*core.Machine")).Return(true, nil)
	guestMock.On("Parent").Return("", nil)
	detectingPlugin := plugin.TestPlugin(t,
		guestMock,
		plugin.WithPluginName("myguest"),
		plugin.WithPluginTypes(component.GuestType),
	)

	notGuestMock := BuildTestGuestPlugin("mynondetectingguest", "")
	notGuestMock.On("Detect", mock.AnythingOfType("*core.Machine")).Return(false, nil)
	nonDetectingPlugin := plugin.TestPlugin(t,
		notGuestMock,
		plugin.WithPluginName("mynondetectingguest"),
		plugin.WithPluginTypes(component.GuestType),
	)

	guestChildMock := BuildTestGuestPlugin("myguest-child", "myguest")
	guestChildMock.On("Detect", mock.AnythingOfType("*core.Machine")).Return(true, nil)
	guestChildMock.SetParentComponent(guestMock)
	detectingChildPlugin := plugin.TestPlugin(t,
		guestChildMock,
		plugin.WithPluginName("myguest-child"),
		plugin.WithPluginTypes(component.GuestType),
	)

	type test struct {
		plugins            []*plugin.Plugin
		errors             bool
		expectedPluginName string
	}

	tests := []test{
		{plugins: []*plugin.Plugin{commPlugin, detectingPlugin}, errors: false, expectedPluginName: "myguest"},
		{plugins: []*plugin.Plugin{commPlugin, detectingChildPlugin}, errors: true, expectedPluginName: "myguest-child"},
		{plugins: []*plugin.Plugin{commPlugin, detectingChildPlugin, detectingPlugin}, errors: false, expectedPluginName: "myguest-child"},
		{plugins: []*plugin.Plugin{commPlugin, detectingPlugin, nonDetectingPlugin}, errors: false, expectedPluginName: "myguest"},
		{plugins: []*plugin.Plugin{commPlugin, nonDetectingPlugin}, errors: true},
		{plugins: []*plugin.Plugin{commPlugin}, errors: true},
	}

	for _, tc := range tests {
		pluginManager := plugin.TestManager(t, tc.plugins...)
		tp := TestProject(t, WithPluginManager(pluginManager))

		tm := TestMachine(t, tp)
		guest, err := tm.Guest()
		if tc.errors {
			require.Error(t, err)
			require.Nil(t, guest)
			require.Nil(t, tm.cache.Get("guest"))
		} else {
			require.NoError(t, err)
			require.NotNil(t, guest)
			require.NotNil(t, tm.cache.Get("guest"))
			n, _ := guest.PluginName()
			if n != tc.expectedPluginName {
				t.Error("Found unexpected plugin, ", n)
			}
		}
	}
}

func TestMachineSetState(t *testing.T) {
	tm := TestMinimalMachine(t)

	type test struct {
		id    string
		state vagrant_server.Operation_PhysicalState
	}

	tests := []test{
		{id: "running", state: vagrant_server.Operation_CREATED},
		{id: "not_created", state: vagrant_server.Operation_NOT_CREATED},
		{id: "whakhgldksj", state: vagrant_server.Operation_UNKNOWN},
	}

	for _, tc := range tests {
		// Set MachineState
		desiredState := &core.MachineState{ID: tc.id}
		tm.SetMachineState(desiredState)
		require.Equal(t, tc.id, tm.machine.State.Id)
		require.Equal(t, tc.state, tm.target.State)

		// Ensure new id is save to db
		dbTarget, err := tm.Client().GetTarget(tm.ctx,
			&vagrant_server.GetTargetRequest{
				Target: tm.Ref().(*vagrant_plugin_sdk.Ref_Target),
			},
		)
		require.NoError(t, err)
		require.Equal(t, tc.state, dbTarget.Target.State)
	}
}

func TestMachineSyncedFolders(t *testing.T) {
	mySyncedFolder := syncedFolderPlugin(t, "mysyncedfolder")
	myOtherSyncedFolder := syncedFolderPlugin(t, "myothersyncedfolder")

	type test struct {
		plugins         []*plugin.Plugin
		config          *component.ConfigData
		errors          bool
		expectedFolders int
	}
	tests := []test{
		// One synced folder and plugin available
		{
			plugins: []*plugin.Plugin{mySyncedFolder},
			errors:  false,
			config: testSyncedFolderConfig(
				[]*testSyncedFolder{
					{
						source:      ".",
						destination: "/vagrant",
						kind:        "mysyncedfolder",
					},
				},
			),
			expectedFolders: 1,
		},
		// Many synced folders and available plugins
		{
			plugins: []*plugin.Plugin{mySyncedFolder, myOtherSyncedFolder},
			errors:  false,
			config: testSyncedFolderConfig(
				[]*testSyncedFolder{
					{
						source:      ".",
						destination: "/vagrant",
						kind:        "mysyncedfolder",
					},
					{
						source:      "./two",
						destination: "/vagrant-two",
						kind:        "mysyncedfolder",
					},
					{
						source:      "./three",
						destination: "/vagrant-three",
						kind:        "myothersyncedfolder",
					},
				},
			),
			expectedFolders: 3,
		},
		// Synced folder with unavailable plugin
		{
			plugins: []*plugin.Plugin{mySyncedFolder, myOtherSyncedFolder},
			errors:  true,
			config: testSyncedFolderConfig(
				[]*testSyncedFolder{
					{
						source:      ".",
						destination: "/vagrant",
						kind:        "idontexist",
					},
					{
						source:      "./two",
						destination: "/vagrant-two",
						kind:        "mysyncedfolder",
					},
					{
						source:      "./three",
						destination: "/vagrant-three",
						kind:        "myothersyncedfolder",
					},
				},
			),
		},
	}

	for _, tc := range tests {
		pluginManager := plugin.TestManager(t, tc.plugins...)
		tp := TestProject(t, WithPluginManager(pluginManager))
		tm := TestMachine(t, tp,
			WithTestTargetConfig(tc.config),
		)
		folders, err := tm.SyncedFolders()
		if tc.errors {
			require.Error(t, err)
		} else {
			require.NoError(t, err)
			require.NotNil(t, folders)
			require.Len(t, folders, tc.expectedFolders)
		}
	}
}

func stringPtr(s string) *string {
	return &s
}