File: workunitbase_test.go

package info (click to toggle)
receptor 1.5.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,772 kB
  • sloc: python: 1,643; makefile: 305; sh: 174
file content (425 lines) | stat: -rw-r--r-- 13,000 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package workceptor_test

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"os"
	"path"
	"strings"
	"testing"
	"time"

	"github.com/ansible/receptor/pkg/logger"
	"github.com/ansible/receptor/pkg/randstr"
	"github.com/ansible/receptor/pkg/workceptor"
	"github.com/ansible/receptor/pkg/workceptor/mock_workceptor"
	"github.com/fsnotify/fsnotify"
	"go.uber.org/mock/gomock"
)

func TestIsComplete(t *testing.T) {
	testCases := []struct {
		name       string
		workState  int
		isComplete bool
	}{
		{"Pending Work is Incomplete", workceptor.WorkStatePending, false},
		{"Running Work is Incomplete", workceptor.WorkStateRunning, false},
		{"Succeeded Work is Complete", workceptor.WorkStateSucceeded, true},
		{"Failed Work is Complete", workceptor.WorkStateFailed, true},
		{"Unknown Work is Incomplete", 999, false},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			if result := workceptor.IsComplete(tc.workState); result != tc.isComplete {
				t.Errorf("expected %v, got %v", tc.isComplete, result)
			}
		})
	}
}

func TestWorkStateToString(t *testing.T) {
	testCases := []struct {
		name        string
		workState   int
		description string
	}{
		{"Pending Work Description", workceptor.WorkStatePending, "Pending"},
		{"Running Work Description", workceptor.WorkStateRunning, "Running"},
		{"Succeeded Work Description", workceptor.WorkStateSucceeded, "Succeeded"},
		{"Failed Work Description", workceptor.WorkStateFailed, "Failed"},
		{"Canceled Work Description", workceptor.WorkStateCanceled, "Canceled"},
		{"Unknown Work Description", 999, "Unknown: 999"},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			if result := workceptor.WorkStateToString(tc.workState); result != tc.description {
				t.Errorf("expected %s, got %s", tc.description, result)
			}
		})
	}
}

func TestIsPending(t *testing.T) {
	testCases := []struct {
		name      string
		err       error
		isPending bool
	}{
		{"Pending Error", workceptor.ErrPending, true},
		{"Non-pending Error", errors.New("test error"), false},
		{"Nil Error", nil, false},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			if result := workceptor.IsPending(tc.err); result != tc.isPending {
				t.Errorf("expected %v, got %v", tc.isPending, result)
			}
		})
	}
}

func setUp(t *testing.T) (*gomock.Controller, workceptor.BaseWorkUnit, *workceptor.Workceptor, *mock_workceptor.MockNetceptorForWorkceptor, *logger.ReceptorLogger) {
	ctrl := gomock.NewController(t)

	mockNetceptor := mock_workceptor.NewMockNetceptorForWorkceptor(ctrl)

	// attach logger to the mock netceptor and return any number of times
	logger.SetGlobalLogLevel(4)
	logger := logger.NewReceptorLogger("")
	mockNetceptor.EXPECT().GetLogger().AnyTimes().Return(logger)
	mockNetceptor.EXPECT().NodeID().Return("NodeID")
	ctx := context.Background()
	w, err := workceptor.New(ctx, mockNetceptor, "/tmp")
	if err != nil {
		t.Errorf("Error while creating Workceptor: %v", err)
	}

	bwu := workceptor.BaseWorkUnit{}

	return ctrl, bwu, w, mockNetceptor, logger
}

func TestInit(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, nil)
	ctrl.Finish()
}

func TestErrorLog(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	bwu.Error("test error")
	ctrl.Finish()
}

func TestWarningLog(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	bwu.Warning("test warning")
	ctrl.Finish()
}

func TestInfoLog(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	bwu.Info("test info")
	ctrl.Finish()
}

func TestDebugLog(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	bwu.Error("test debug")
	ctrl.Finish()
}

func TestSetFromParams(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	err := bwu.SetFromParams(nil)
	if err != nil {
		t.Errorf("SetFromParams should return nil: got %v", err)
	}
	ctrl.Finish()
}

const (
	rootDir  = "/tmp"
	testDir  = "NodeID/test"
	dirError = "no such file or directory"
)

func TestUnitDir(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	expectedUnitDir := path.Join(rootDir, testDir)
	if unitDir := bwu.UnitDir(); unitDir != expectedUnitDir {
		t.Errorf("UnitDir returned wrong value: got %s, want %s", unitDir, expectedUnitDir)
	}
	ctrl.Finish()
}

func TestID(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "test", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	if id := bwu.ID(); id != "test" {
		t.Errorf("ID returned wrong value: got %s, want %s", id, "test")
	}
	ctrl.Finish()
}

func TestStatusFileName(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	expectedUnitDir := path.Join(rootDir, testDir)
	expectedStatusFileName := path.Join(expectedUnitDir, "status")
	if statusFileName := bwu.StatusFileName(); statusFileName != expectedStatusFileName {
		t.Errorf("StatusFileName returned wrong value: got %s, want %s", statusFileName, expectedStatusFileName)
	}
	ctrl.Finish()
}

func TestStdoutFileName(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	expectedUnitDir := path.Join(rootDir, testDir)
	expectedStdoutFileName := path.Join(expectedUnitDir, "stdout")
	if stdoutFileName := bwu.StdoutFileName(); stdoutFileName != expectedStdoutFileName {
		t.Errorf("StdoutFileName returned wrong value: got %s, want %s", stdoutFileName, expectedStdoutFileName)
	}
	ctrl.Finish()
}

func TestBaseSave(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	err := bwu.Save()
	if !strings.Contains(err.Error(), dirError) {
		t.Errorf("Base Work Unit Save, no such file or directory expected, instead %s", err.Error())
	}
	ctrl.Finish()
}

func TestBaseLoad(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	err := bwu.Load()
	if !strings.Contains(err.Error(), dirError) {
		t.Errorf("TestBaseLoad, no such file or directory expected, instead %s", err.Error())
	}
	ctrl.Finish()
}

func TestBaseUpdateFullStatus(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	sf := func(sfd *workceptor.StatusFileData) {
		// Do nothing
	}
	bwu.UpdateFullStatus(sf)
	err := bwu.LastUpdateError()
	if !strings.Contains(err.Error(), dirError) {
		t.Errorf("TestBaseUpdateFullStatus, no such file or directory expected, instead %s", err.Error())
	}
	ctrl.Finish()
}

func TestBaseUpdateBasicStatus(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	bwu.UpdateBasicStatus(1, "Details", 0)
	err := bwu.LastUpdateError()
	if !strings.Contains(err.Error(), dirError) {
		t.Errorf("TestBaseUpdateBasicStatus, no such file or directory expected, instead %s", err.Error())
	}
	ctrl.Finish()
}

func TestBaseStatus(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	bwu.Init(w, "test", "", workceptor.FileSystem{}, &workceptor.RealWatcher{})
	status := bwu.Status()
	if status.State != workceptor.WorkStatePending {
		t.Errorf("TestBaseStatus, expected work state pending, received %d", status.State)
	}
	ctrl.Finish()
}

func TestBaseRelease(t *testing.T) {
	ctrl, bwu, w, _, _ := setUp(t)
	mockFileSystem := mock_workceptor.NewMockFileSystemer(ctrl)
	bwu.Init(w, "test12345", "", mockFileSystem, &workceptor.RealWatcher{})

	const removeError = "RemoveAll Error"
	testCases := []struct {
		name  string
		err   error
		force bool
		calls func()
	}{
		{
			name:  removeError,
			err:   errors.New(removeError),
			force: false,
			calls: func() { mockFileSystem.EXPECT().RemoveAll(gomock.Any()).Return(errors.New(removeError)).Times(3) },
		},
		{
			name:  "No remote error without force",
			err:   nil,
			force: false,
			calls: func() { mockFileSystem.EXPECT().RemoveAll(gomock.Any()).Return(nil) },
		},
		{
			name:  "No remote error with force",
			err:   nil,
			force: true,
			calls: func() { mockFileSystem.EXPECT().RemoveAll(gomock.Any()).Return(nil) },
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			tc.calls()
			err := bwu.Release(tc.force)
			if err != nil && err.Error() != tc.err.Error() {
				t.Errorf("Error returned dosent match, err received %s, expected %s", err, tc.err)
			}
		})
	}

	ctrl.Finish()
}

func TestMonitorLocalStatus(t *testing.T) {
	tests := []struct {
		name          string
		statObj       *Info
		statObjLater  *Info
		addWatcherErr error
		statErr       error
		fsNotifyEvent *fsnotify.Event // using pointer to allow nil
		logOutput     string
		sleepDuration time.Duration
	}{
		{
			name:          "Handle Write Event",
			statObj:       NewInfo("test", 1, 0, time.Now()),
			addWatcherErr: nil,
			statErr:       nil,
			fsNotifyEvent: &fsnotify.Event{Op: fsnotify.Write},
			logOutput:     "Watcher Events Error reading",
			sleepDuration: 100 * time.Millisecond,
		},
		{
			name:          "Error Adding Watcher",
			statObj:       NewInfo("test", 1, 0, time.Now()),
			addWatcherErr: fmt.Errorf("error adding watcher"),
			statErr:       nil,
			fsNotifyEvent: nil,
			logOutput:     "",
			sleepDuration: 100 * time.Millisecond,
		},
		{
			name:          "Error Reading Status",
			statObj:       nil,
			addWatcherErr: fmt.Errorf("error adding watcher"),
			statErr:       fmt.Errorf("stat error"),
			fsNotifyEvent: nil,
			logOutput:     "",
			sleepDuration: 100 * time.Millisecond,
		},
		{
			name:          "Handle Context Cancellation",
			statObj:       NewInfo("test", 1, 0, time.Now()),
			addWatcherErr: nil,
			statErr:       nil,
			fsNotifyEvent: &fsnotify.Event{Op: fsnotify.Write},
			logOutput:     "Watcher Events Error reading",
			sleepDuration: 100 * time.Millisecond,
		},
		{
			name:          "Handle File Update Without Event",
			statObj:       NewInfo("test", 1, 0, time.Now()),
			statObjLater:  NewInfo("test", 1, 0, time.Now().Add(10*time.Second)),
			addWatcherErr: nil,
			statErr:       nil,
			fsNotifyEvent: &fsnotify.Event{Op: fsnotify.Write},
			logOutput:     "Watcher Events Error reading",
			sleepDuration: 500 * time.Millisecond,
		},
		{
			name:          "Handle Remove Event",
			statObj:       NewInfo("test", 1, 0, time.Now()),
			addWatcherErr: nil,
			statErr:       nil,
			fsNotifyEvent: &fsnotify.Event{Op: fsnotify.Remove},
			logOutput:     "Watcher Events Remove reading",
			sleepDuration: 100 * time.Millisecond,
		},
		{
			name:          "Handle Rename Event",
			statObj:       NewInfo("test", 1, 0, time.Now()),
			addWatcherErr: nil,
			statErr:       nil,
			fsNotifyEvent: &fsnotify.Event{Op: fsnotify.Rename},
			logOutput:     "Watcher Events Rename reading",
			sleepDuration: 100 * time.Millisecond,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			ctrl, bwu, w, _, l := setUp(t)
			defer ctrl.Finish()
			randstring := randstr.RandomString(4)
			logFilePath := fmt.Sprintf("/tmp/monitorLocalStatusLog%s", randstring)

			mockWatcher := mock_workceptor.NewMockWatcherWrapper(ctrl)
			mockFileSystem := mock_workceptor.NewMockFileSystemer(ctrl)
			bwu.Init(w, "test", "", mockFileSystem, mockWatcher)

			mockFileSystem.EXPECT().Stat(gomock.Any()).Return(tc.statObj, tc.statErr).AnyTimes()
			if tc.statObjLater != nil {
				mockFileSystem.EXPECT().Stat(gomock.Any()).Return(tc.statObjLater, nil).AnyTimes()
			}
			mockWatcher.EXPECT().Add(gomock.Any()).Return(tc.addWatcherErr)
			mockWatcher.EXPECT().Remove(gomock.Any()).AnyTimes()
			mockWatcher.EXPECT().Close().AnyTimes()

			if tc.fsNotifyEvent != nil {
				logFile, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600)
				if err != nil {
					t.Error("error creating monitorLocalStatusLog file")
				}
				l.SetOutput(logFile)
				eventCh := make(chan fsnotify.Event, 1)
				mockWatcher.EXPECT().EventChannel().Return(eventCh).AnyTimes()
				go func() { eventCh <- *tc.fsNotifyEvent }()

				errorCh := make(chan error, 1)
				mockWatcher.EXPECT().ErrorChannel().Return(errorCh).AnyTimes()
			}

			go bwu.MonitorLocalStatus()
			time.Sleep(tc.sleepDuration)

			if tc.fsNotifyEvent != nil {
				logOutput, err := os.ReadFile(logFilePath)
				if err != nil && len(logOutput) == 0 {
					t.Errorf("error reading %s file", logFilePath)
				}
				if !bytes.Contains(logOutput, []byte(tc.logOutput)) {
					t.Errorf("expected log to be: %s, got %s", tc.logOutput, string(logOutput))
				}
			}

			bwu.CancelContext()
		})
	}
}