-
Notifications
You must be signed in to change notification settings - Fork 34
/
commands_test.go
464 lines (400 loc) · 13.6 KB
/
commands_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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"testing"
"github.com/creativeprojects/resticprofile/config"
"github.com/creativeprojects/resticprofile/constants"
"github.com/creativeprojects/resticprofile/schedule"
"github.com/creativeprojects/resticprofile/util/collect"
"github.com/stretchr/testify/assert"
)
func TestPanicCommand(t *testing.T) {
assert.Panics(t, func() {
_ = panicCommand(nil, commandContext{})
})
}
func TestRandomKeyOfInvalidSize(t *testing.T) {
assert.Error(t, randomKey(os.Stdout, commandContext{
Context: Context{
flags: commandLineFlags{resticArgs: []string{"restic", "size"}},
},
}))
}
func TestRandomKeyOfZeroSize(t *testing.T) {
assert.Error(t, randomKey(os.Stdout, commandContext{
Context: Context{
flags: commandLineFlags{resticArgs: []string{"restic", "0"}},
},
}))
}
func TestRandomKey(t *testing.T) {
// doesn't look like much, but it's testing the random generator is not throwing an error
assert.NoError(t, randomKey(os.Stdout, commandContext{}))
}
func TestRemovableSchedules(t *testing.T) {
testConfig := `
[default.check]
schedule = "daily"
[default.backup]
`
parsedConfig, err := config.Load(bytes.NewBufferString(testConfig), "toml")
assert.Nil(t, err)
// Test that errors from getScheduleJobs are passed through
_, _, notFoundErr := getRemovableScheduleJobs(parsedConfig, commandLineFlags{name: "non-existent"})
assert.ErrorIs(t, notFoundErr, config.ErrNotFound)
// Test that declared and declarable job configs are returned
_, schedules, err := getRemovableScheduleJobs(parsedConfig, commandLineFlags{name: "default"})
assert.Nil(t, err)
assert.NotEmpty(t, schedules)
assert.Len(t, schedules, len(config.NewProfile(parsedConfig, "test").SchedulableCommands()))
declaredCount := 0
for _, jobConfig := range schedules {
configOrigin := jobConfig.ScheduleOrigin()
scheduler := schedule.NewScheduler(schedule.NewHandler(schedule.SchedulerDefaultOS{}), configOrigin.Name)
defer func(s *schedule.Scheduler) { s.Close() }(scheduler) // Capture current ref to scheduler to be able to close it when function returns.
if configOrigin.Command == constants.CommandCheck {
assert.False(t, scheduler.NewJob(scheduleToConfig(jobConfig)).RemoveOnly())
declaredCount++
} else {
assert.True(t, scheduler.NewJob(scheduleToConfig(jobConfig)).RemoveOnly())
}
}
assert.Equal(t, 1, declaredCount)
}
func TestSchedules(t *testing.T) {
testConfig := `
[default.check]
schedule = "daily"
[default.backup]
[other.backup]
`
cfg, err := config.Load(bytes.NewBufferString(testConfig), "toml")
assert.Nil(t, err)
// Test that non-existent profiles causes an error
_, _, notFoundErr := getProfileScheduleJobs(cfg, commandLineFlags{name: "non-existent"})
assert.ErrorIs(t, notFoundErr, config.ErrNotFound)
// Test that non-existent schedule causes no error at first
{
flags := commandLineFlags{name: "other"}
_, schedules, err := getProfileScheduleJobs(cfg, flags)
assert.Nil(t, err)
err = requireScheduleJobs(schedules, flags)
assert.EqualError(t, err, "no schedule found for profile 'other'")
}
// Test that only declared job configs are returned
{
flags := commandLineFlags{name: "default"}
profile, schedules, err := getProfileScheduleJobs(cfg, flags)
assert.Nil(t, err)
err = requireScheduleJobs(schedules, flags)
assert.Nil(t, err)
assert.NotNil(t, profile)
assert.NotEmpty(t, schedules)
assert.Len(t, schedules, 1)
assert.Equal(t, "check", schedules[0].ScheduleOrigin().Command)
}
}
func TestSelectProfiles(t *testing.T) {
testConfig := `
[global]
[groups]
others = ["2nd", "3rd"]
default = ["2nd", "default"] # name collision with default profile
[default.check]
schedule = "daily"
[default.backup]
_ = 0
[2nd.backup]
_ = 0
[3rd.backup]
_ = 0
`
allProfiles := []string{"default", "2nd", "3rd"}
allGroups := []string{"others", "default"}
allProfilesAndGroups := append(allProfiles, allGroups...)
cfg, err := config.Load(bytes.NewBufferString(testConfig), "toml")
assert.Nil(t, err)
for _, p := range allProfiles {
assert.True(t, cfg.HasProfile(p))
}
for _, g := range allGroups {
assert.True(t, cfg.HasProfileGroup(g))
}
// Select --all
assert.ElementsMatch(t, allProfilesAndGroups, selectProfilesAndGroups(cfg, commandLineFlags{}, []string{"--all"}))
// Select profiles by name
for _, p := range allProfiles {
assert.ElementsMatch(t, []string{p}, selectProfilesAndGroups(cfg, commandLineFlags{name: p}, nil))
}
// Select groups by name
for _, g := range allGroups {
assert.ElementsMatch(t, []string{g}, selectProfilesAndGroups(cfg, commandLineFlags{name: g}, nil))
}
// Select non-existing profile or group
assert.ElementsMatch(t, []string{"non-existing"}, selectProfilesAndGroups(cfg, commandLineFlags{name: "non-existing"}, nil))
}
func TestFlagsForProfile(t *testing.T) {
flags := commandLineFlags{name: "_"}
profileFlags := flagsForProfile(flags, "test")
assert.NotEqual(t, flags, profileFlags)
assert.Equal(t, "_", flags.name)
assert.Equal(t, "test", profileFlags.name)
}
func TestCompleteCall(t *testing.T) {
completer := NewCompleter(ownCommands.All(), DefaultFlagsLoader)
completer.init(nil)
newline := fmt.Sprintln("")
expectedFlags := strings.Join(completer.completeFlagSet(""), newline) + newline
visibleCommands := collect.Not(func(c ownCommand) bool { return c.hideInCompletion || c.hide })
commandName := func(c ownCommand) string { return c.name }
commandNames := collect.From(collect.All(ownCommands.All(), visibleCommands), commandName)
sort.Strings(commandNames)
expectedCommands := strings.Join(commandNames, newline) + newline +
RequestResticCompletion + newline
testTable := []struct {
args []string
expected string
}{
{args: []string{"--"}, expected: expectedFlags},
{args: []string{"--config=does-not-exist", ""}, expected: expectedCommands},
{args: []string{"bash:v1", "--"}, expected: expectedFlags},
{args: []string{"bash:v10", "--"}, expected: ""},
{args: []string{"zsh:v1", "--"}, expected: ""},
}
for _, test := range testTable {
t.Run(strings.Join(test.args, " "), func(t *testing.T) {
buffer := &strings.Builder{}
assert.Nil(t, completeCommand(buffer, commandContext{
ownCommands: ownCommands,
Context: Context{request: Request{arguments: test.args}},
}))
assert.Equal(t, test.expected, buffer.String())
})
}
}
func TestGenerateCommand(t *testing.T) {
buffer := &strings.Builder{}
contextWithArguments := func(args []string) commandContext {
t.Helper()
return commandContext{Context: Context{request: Request{arguments: args}}}
}
t.Run("--bash-completion", func(t *testing.T) {
buffer.Reset()
assert.Nil(t, generateCommand(buffer, contextWithArguments([]string{"--bash-completion"})))
assert.Equal(t, strings.TrimSpace(bashCompletionScript), strings.TrimSpace(buffer.String()))
assert.Contains(t, bashCompletionScript, "#!/usr/bin/env bash")
})
t.Run("--zsh-completion", func(t *testing.T) {
buffer.Reset()
assert.Nil(t, generateCommand(buffer, contextWithArguments([]string{"--zsh-completion"})))
assert.Equal(t, strings.TrimSpace(zshCompletionScript), strings.TrimSpace(buffer.String()))
assert.Contains(t, zshCompletionScript, "#!/usr/bin/env zsh")
})
t.Run("--config-reference", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, contextWithArguments([]string{"--config-reference"})))
ref := buffer.String()
assert.Contains(t, ref, "generating reference.gomd")
assert.Contains(t, ref, "generating profile section")
assert.Contains(t, ref, "generating nested section")
})
t.Run("--json-schema global", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, contextWithArguments([]string{"--json-schema", "global"})))
ref := buffer.String()
assert.Contains(t, ref, `"$schema"`)
assert.Contains(t, ref, "/jsonschema/config-1.json")
assert.Contains(t, ref, "/jsonschema/config-2.json")
decoder := json.NewDecoder(strings.NewReader(ref))
content := make(map[string]any)
assert.NoError(t, decoder.Decode(&content))
assert.Contains(t, content, `$schema`)
})
t.Run("--json-schema no-option", func(t *testing.T) {
buffer.Reset()
assert.Error(t, generateCommand(buffer, contextWithArguments([]string{"--json-schema"})))
})
t.Run("--json-schema invalid-option", func(t *testing.T) {
buffer.Reset()
assert.Error(t, generateCommand(buffer, contextWithArguments([]string{"--json-schema", "_invalid_"})))
})
t.Run("--json-schema v1", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, contextWithArguments([]string{"--json-schema", "v1"})))
ref := buffer.String()
assert.Contains(t, ref, "/jsonschema/config-1.json")
})
t.Run("--json-schema v2", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, contextWithArguments([]string{"--json-schema", "v2"})))
ref := buffer.String()
assert.Contains(t, ref, "\"profiles\":")
assert.Contains(t, ref, "/jsonschema/config-2.json")
})
t.Run("--json-schema --version 0.13 v1", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, contextWithArguments([]string{"--json-schema", "--version", "0.13", "v1"})))
ref := buffer.String()
assert.Contains(t, ref, "/jsonschema/config-1-restic-0-13.json")
})
t.Run("--random-key", func(t *testing.T) {
buffer.Reset()
assert.Nil(t, generateCommand(buffer, contextWithArguments([]string{"--random-key", "512"})))
assert.Equal(t, 684, len(strings.TrimSpace(buffer.String())))
})
t.Run("invalid-option", func(t *testing.T) {
buffer.Reset()
opts := []string{"", "invalid", "--unknown"}
for _, option := range opts {
buffer.Reset()
err := generateCommand(buffer, contextWithArguments([]string{option}))
assert.EqualError(t, err, fmt.Sprintf("nothing to generate for: %s", option))
assert.Equal(t, 0, buffer.Len())
}
})
}
func TestShowSchedules(t *testing.T) {
buffer := &bytes.Buffer{}
create := func(command string, at ...string) *config.Schedule {
origin := config.ScheduleOrigin("default", command)
return config.NewDefaultSchedule(nil, origin, at...)
}
schedules := []*config.Schedule{
create("check", "weekly"),
create("backup", "daily"),
}
expected := strings.TrimSpace(`
schedule backup@default:
at: daily
permission: auto
command-output: auto
priority: standard
lock-mode: default
capture-environment: RESTIC_*
schedule check@default:
at: weekly
permission: auto
command-output: auto
priority: standard
lock-mode: default
capture-environment: RESTIC_*
`)
showSchedules(buffer, schedules)
assert.Equal(t, expected, strings.TrimSpace(buffer.String()))
}
func TestCreateScheduleWhenNoneAvailable(t *testing.T) {
// loads an (almost) empty config
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = createSchedule(nil, commandContext{
Context: Context{
config: cfg,
flags: commandLineFlags{
name: "default",
},
},
})
assert.Error(t, err)
}
func TestCreateScheduleAll(t *testing.T) {
// loads an (almost) empty config
// note that a default (or specific) profile is needed to load all schedules:
// TODO: we should be able to load them all without a default profile
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = createSchedule(nil, commandContext{
Context: Context{
config: cfg,
flags: commandLineFlags{
name: "default",
},
request: Request{arguments: []string{"--all"}},
},
})
assert.NoError(t, err)
}
func TestPreRunScheduleNoScheduleName(t *testing.T) {
// loads an (almost) empty config
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = preRunSchedule(&Context{
config: cfg,
flags: commandLineFlags{
name: "default",
},
})
assert.Error(t, err)
t.Log(err)
}
func TestPreRunScheduleWrongScheduleName(t *testing.T) {
// loads an (almost) empty config
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = preRunSchedule(&Context{
request: Request{arguments: []string{"wrong"}},
config: cfg,
flags: commandLineFlags{
name: "default",
},
})
assert.Error(t, err)
t.Log(err)
}
func TestPreRunScheduleProfileUnknown(t *testing.T) {
// loads an (almost) empty config
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = preRunSchedule(&Context{
request: Request{arguments: []string{"backup@profile"}},
config: cfg,
})
assert.ErrorIs(t, err, config.ErrNotFound)
}
func TestRunScheduleNoScheduleName(t *testing.T) {
// loads an (almost) empty config
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = runSchedule(nil, commandContext{
Context: Context{
config: cfg,
flags: commandLineFlags{
name: "default",
},
},
})
assert.Error(t, err)
t.Log(err)
}
func TestRunScheduleWrongScheduleName(t *testing.T) {
// loads an (almost) empty config
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = runSchedule(nil, commandContext{
Context: Context{
request: Request{arguments: []string{"wrong"}},
config: cfg,
flags: commandLineFlags{
name: "default",
},
},
})
assert.Error(t, err)
t.Log(err)
}
func TestRunScheduleProfileUnknown(t *testing.T) {
// loads an (almost) empty config
cfg, err := config.Load(bytes.NewBufferString("[default]"), "toml")
assert.NoError(t, err)
err = runSchedule(nil, commandContext{
Context: Context{
request: Request{arguments: []string{"backup@profile"}},
config: cfg,
},
})
assert.ErrorIs(t, err, ErrProfileNotFound)
}