GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — func/cmd/root_test.go at main · stackbuilders/func

Expand file tree

/

root_test.go

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
528 lines (482 loc) · 14.1 KB
/

root_test.go

Copy path

File metadata and controls

528 lines (482 loc) · 14.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package cmd
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/ory/viper"
"knative.dev/client/pkg/util"
fn "knative.dev/func/pkg/functions"
. "knative.dev/func/pkg/testing"
)
const TestRegistry = "example.com/alice"
func TestRoot_mergeEnvMaps(t *testing.T) {
a := "A"
b := "B"
v1 := "x"
v2 := "y"
type args struct {
envs []fn.Env
toUpdate *util.OrderedMap
toRemove []string
}
tests := []struct {
name string
args args
want []fn.Env
}{
{
"add new var to empty list",
args{
[]fn.Env{},
util.NewOrderedMapWithKVStrings([][]string{{a, v1}}),
[]string{},
},
[]fn.Env{{Name: &a, Value: &v1}},
},
{
"add new var",
args{
[]fn.Env{{Name: &b, Value: &v2}},
util.NewOrderedMapWithKVStrings([][]string{{a, v1}}),
[]string{},
},
[]fn.Env{{Name: &b, Value: &v2}, {Name: &a, Value: &v1}},
},
{
"update var",
args{
[]fn.Env{{Name: &a, Value: &v1}},
util.NewOrderedMapWithKVStrings([][]string{{a, v2}}),
[]string{},
},
[]fn.Env{{Name: &a, Value: &v2}},
},
{
"update multiple vars",
args{
[]fn.Env{{Name: &a, Value: &v1}, {Name: &b, Value: &v2}},
util.NewOrderedMapWithKVStrings([][]string{{a, v2}, {b, v1}}),
[]string{},
},
[]fn.Env{{Name: &a, Value: &v2}, {Name: &b, Value: &v1}},
},
{
"remove var",
args{
[]fn.Env{{Name: &a, Value: &v1}},
util.NewOrderedMap(),
[]string{a},
},
[]fn.Env{},
},
{
"remove multiple vars",
args{
[]fn.Env{{Name: &a, Value: &v1}, {Name: &b, Value: &v2}},
util.NewOrderedMap(),
[]string{a, b},
},
[]fn.Env{},
},
{
"update and remove vars",
args{
[]fn.Env{{Name: &a, Value: &v1}, {Name: &b, Value: &v2}},
util.NewOrderedMapWithKVStrings([][]string{{a, v2}}),
[]string{b},
},
[]fn.Env{{Name: &a, Value: &v2}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, _, err := mergeEnvs(tt.args.envs, tt.args.toUpdate, tt.args.toRemove)
if err != nil {
t.Errorf("mergeEnvs() for initial vars %v and toUpdate %v and toRemove %v got error %v",
tt.args.envs, tt.args.toUpdate, tt.args.toRemove, err)
}
if !reflect.DeepEqual(got, tt.want) {
gotString := "{ "
for _, e := range got {
gotString += fmt.Sprintf("{ %s: %s } ", *e.Name, *e.Value)
}
gotString += "}"
wantString := "{ "
for _, e := range tt.want {
wantString += fmt.Sprintf("{ %s: %s } ", *e.Name, *e.Value)
}
wantString += "}"
t.Errorf("mergeEnvs() = got: %s, want %s", gotString, wantString)
}
})
}
}
// TestRoot_CommandNameParameterized confirmst that the command name, as
// printed in help text, is parameterized based on the constructor parameters
// of the root command. This allows, for example, to have help text correct
// when both embedded as a plugin or standalone.
func TestRoot_CommandNameParameterized(t *testing.T) {
expectedSynopsis := "%v is the command line interface for"
tests := []string{
"func", // standalone
"kn func", // kn plugin
}
for _, testName := range tests {
var (
cmd = NewRootCmd(RootCommandConfig{Name: testName})
out = strings.Builder{}
)
cmd.SetArgs([]string{}) // Do not use test command args
cmd.SetOut(&out)
if err := cmd.Help(); err != nil {
t.Fatal(err)
}
if cmd.Use != testName {
t.Fatalf("expected command Use '%v', got '%v'", testName, cmd.Use)
}
if !strings.HasPrefix(out.String(), fmt.Sprintf(expectedSynopsis, testName)) {
t.Logf("Testing '%v'\n", testName)
t.Log(out.String())
t.Fatalf("Help text does not include substituted name '%v'", testName)
}
}
}
func TestVerbose(t *testing.T) {
t.Run("no verbose", func(t *testing.T) {
viper.Reset()
var out bytes.Buffer
cmd := NewRootCmd(RootCommandConfig{
Name: "func",
Version: Version{Vers: "v0.42.0"},
})
cmd.SetArgs([]string{"version"})
cmd.SetOut(&out)
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if got := strings.TrimRight(out.String(), "\n"); got != "v0.42.0" {
t.Errorf("expected %q but got %q", "v0.42.0", got)
}
})
t.Run("verbose includes populated fields", func(t *testing.T) {
viper.Reset()
var out bytes.Buffer
cmd := NewRootCmd(RootCommandConfig{
Name: "func",
Version: Version{
Vers: "v0.42.0",
Hash: "cafe",
Kver: "v1.10.0",
},
})
cmd.SetArgs([]string{"version", "-v"})
cmd.SetOut(&out)
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
output := out.String()
for _, want := range []string{
"Version: v0.42.0",
"Knative: v1.10.0",
"Commit: cafe",
} {
if !strings.Contains(output, want) {
t.Errorf("expected output to contain %q but got:\n%s", want, output)
}
}
})
t.Run("verbose omits empty fields", func(t *testing.T) {
viper.Reset()
var out bytes.Buffer
cmd := NewRootCmd(RootCommandConfig{
Name: "func",
// All fields except Vers are intentionally left empty.
Version: Version{Vers: "v0.42.0"},
})
cmd.SetArgs([]string{"version", "-v"})
cmd.SetOut(&out)
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
output := out.String()
for _, absent := range []string{"Knative:", "Commit:"} {
if strings.Contains(output, absent) {
t.Errorf("expected output to omit %q but got:\n%s", absent, output)
}
}
if !strings.HasPrefix(output, "Version: v0.42.0\n") {
t.Errorf("expected output to start with %q but got:\n%s", "Version: v0.42.0\n", output)
}
})
// kver prefix stripped verifies that a Knative version tag with the
// "knative-" prefix is stripped correctly for an exact release tag.
t.Run("kver prefix stripped exact tag", func(t *testing.T) {
v := Version{Vers: "v0.42.0", Kver: "knative-v1.10.0"}
output := v.StringVerbose()
if !strings.Contains(output, "Knative: v1.10.0") {
t.Errorf("expected 'knative-' prefix stripped for exact tag, got:\n%s", output)
}
})
// kver prefix stripped also verifies commit-distance suffixes are preserved
// (e.g. knative-v1.10.0-5-gabcdef1 → v1.10.0-5-gabcdef1).
t.Run("kver prefix stripped with commit distance", func(t *testing.T) {
v := Version{Vers: "v0.42.0", Kver: "knative-v1.10.0-5-gabcdef1"}
output := v.StringVerbose()
if !strings.Contains(output, "Knative: v1.10.0-5-gabcdef1") {
t.Errorf("expected 'knative-' prefix stripped with commit distance preserved, got:\n%s", output)
}
})
t.Run("output json", func(t *testing.T) {
viper.Reset()
var out bytes.Buffer
cmd := NewRootCmd(RootCommandConfig{
Name: "func",
Version: Version{Vers: "v0.42.0"},
})
cmd.SetArgs([]string{"version", "--output", "json"})
cmd.SetOut(&out)
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
output := out.String()
if !strings.Contains(output, `"version": "v0.42.0"`) {
t.Errorf("expected JSON to contain version field, got:\n%s", output)
}
})
t.Run("output yaml", func(t *testing.T) {
viper.Reset()
var out bytes.Buffer
cmd := NewRootCmd(RootCommandConfig{
Name: "func",
Version: Version{Vers: "v0.42.0"},
})
cmd.SetArgs([]string{"version", "--output", "yaml"})
cmd.SetOut(&out)
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "version: v0.42.0") {
t.Errorf("expected YAML to contain version field, got:\n%s", out.String())
}
})
t.Run("url unsupported", func(t *testing.T) {
v := Version{Vers: "v0.42.0"}
var buf bytes.Buffer
if err := v.URL(&buf); err == nil {
t.Error("expected URL format to return an error, got nil")
}
})
// exact output guards against extra blank lines or whitespace being
// reintroduced between populated fields.
t.Run("verbose exact output", func(t *testing.T) {
v := Version{
Vers: "v0.42.0",
Kver: "knative-v1.10.0",
Hash: "cafe",
SocatImage: "ghcr.io/knative/func-utils:v2",
TarImage: "ghcr.io/knative/func-utils:v2",
}
want := "Version: v0.42.0\n" +
"Knative: v1.10.0\n" +
"Commit: cafe\n" +
"SocatImage: ghcr.io/knative/func-utils:v2\n" +
"TarImage: ghcr.io/knative/func-utils:v2"
if got := v.StringVerbose(); got != want {
t.Errorf("unexpected verbose output:\nwant:\n%s\ngot:\n%s", want, got)
}
})
t.Run("middleware versions omitted when empty", func(t *testing.T) {
v := Version{
Vers: "v0.42.0",
MiddlewareVersions: MiddlewareVersions{},
}
output := v.StringVerbose()
if strings.Contains(output, "Middleware Versions:") {
t.Errorf("expected empty MiddlewareVersions to be omitted, got:\n%s", output)
}
})
t.Run("socat and tar images omitted when empty", func(t *testing.T) {
v := Version{Vers: "v0.42.0"}
output := v.StringVerbose()
for _, absent := range []string{"SocatImage:", "TarImage:"} {
if strings.Contains(output, absent) {
t.Errorf("expected %q to be omitted when empty, got:\n%s", absent, output)
}
}
})
t.Run("socat and tar images present when populated", func(t *testing.T) {
v := Version{
Vers: "v0.42.0",
SocatImage: "ghcr.io/knative/func-utils:v2",
TarImage: "ghcr.io/knative/func-utils:v2",
}
output := v.StringVerbose()
for _, want := range []string{
"SocatImage: ghcr.io/knative/func-utils:v2",
"TarImage: ghcr.io/knative/func-utils:v2",
} {
if !strings.Contains(output, want) {
t.Errorf("expected output to contain %q, got:\n%s", want, output)
}
}
})
}
// TestRoot_effectivePath ensures that the path method returns the effective path
// to use with the following precedence: empty by default, then FUNC_PATH
// environment variable, -p flag, or finally --path with the highest precedence.
func TestRoot_effectivePath(t *testing.T) {
args := os.Args
t.Cleanup(func() { os.Args = args })
t.Run("default", func(t *testing.T) {
if effectivePath() != "" {
t.Fatalf("the default path should be '.', got '%v'", effectivePath())
}
})
t.Run("FUNC_PATH", func(t *testing.T) {
t.Setenv("FUNC_PATH", "p1")
if effectivePath() != "p1" {
t.Fatalf("the effetive path did not load the environment variable. Expected 'p1', got '%v'", effectivePath())
}
})
t.Run("--path", func(t *testing.T) {
os.Args = []string{"test", "--path=p2"}
if effectivePath() != "p2" {
t.Fatalf("the effective path did not load the --path flag. Expected 'p2', got '%v'", effectivePath())
}
})
t.Run("-p", func(t *testing.T) {
os.Args = []string{"test", "-p=p3"}
if effectivePath() != "p3" {
t.Fatalf("the effective path did not load the -p flag. Expected 'p3', got '%v'", effectivePath())
}
})
t.Run("short flag precedence", func(t *testing.T) {
t.Setenv("FUNC_PATH", "p1")
os.Args = []string{"test", "-p=p3"}
if effectivePath() != "p3" {
t.Fatalf("the effective path did not load the -p flag with precedence over FUNC_PATH. Expected 'p3', got '%v'", effectivePath())
}
})
t.Run("-p highest precedence", func(t *testing.T) {
t.Setenv("FUNC_PATH", "p1")
os.Args = []string{"test", "--path=p2", "-p=p3"}
if effectivePath() != "p3" {
t.Fatalf("the effective path did not take -p with highest precedence over --path and FUNC_PATH. Expected 'p3', got '%v'", effectivePath())
}
})
t.Run("continues on unrecognized flags", func(t *testing.T) {
os.Args = []string{"test", "-r=repo.example.com/bob", "-p=p3"}
if effectivePath() != "p3" {
t.Fatalf("the effective path did not evaluate when unexpected flags were present")
}
})
}
// Test_defaultNamespace ensures that the order of precedence for
// determining the effective namespace is followed.
// to use for the next deployment.
func Test_defaultNamespace(t *testing.T) {
// Clear non-test envs and set the test KUBECONFIG to nonexistent, but
// save the current working directory for setting kube context in some
// test cases.
cwd := Cwd()
_ = FromTempDirectory(t) // clears non-test envs and enters a temp dir.
t.Setenv("KUBECONFIG", filepath.Join(t.TempDir(), "nonexistent"))
// also clear the test KUBECONFIG env
tests := []struct {
name string
context bool
global bool
f fn.Function
expected string
}{
{
name: "function namespace overrides",
context: true,
global: true,
expected: "functionns",
f: fn.Function{
Namespace: "functionns",
Deploy: fn.DeploySpec{
Namespace: "deployns",
},
},
}, {
name: "function already deployed override",
context: true,
global: true,
expected: "deployns",
f: fn.Function{
Deploy: fn.DeploySpec{
Namespace: "deployns",
},
},
}, {
name: "static default",
context: false, // no active kube context
global: false, // no global
expected: DefaultNamespace, // expect static default
}, {
name: "global config",
context: false,
global: true, // see the global defined in FUNC_HOME testdata
expected: "globaldefault", // expect global to override static
}, {
name: "active context",
context: true, // see the config in KUBECONFIG testdata
global: true,
expected: "mynamespace", // active context overrides global default
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.global { // enable a global config setting
t.Setenv("XDG_CONFIG_HOME", filepath.Join(cwd, "testdata", "Test_defaultNamespace"))
}
if test.context { // enable an active kube context
t.Setenv("KUBECONFIG", filepath.Join(cwd, "testdata", "Test_defaultNamespace", "kubeconfig"))
}
namespace := defaultNamespace(test.f, false)
if namespace != test.expected {
t.Fatalf("%v: expected namespace %q, got %q", test.name, test.expected, namespace)
}
})
}
}
// Helpers
// -------
// pipe the output of stdout to a buffer whose value is returned
// from the returned function. Call pipe() to start piping output
// to the buffer, call the returned function to access the data in
// the buffer.
func piped(t *testing.T) func() string {
t.Helper()
var (
o = os.Stdout
c = make(chan error, 1)
b strings.Builder
)
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout = w
go func() {
_, err := io.Copy(&b, r)
r.Close()
c <- err
}()
return func() string {
os.Stdout = o
w.Close()
err := <-c
if err != nil {
t.Fatal(err)
}
return strings.TrimSpace(b.String())
}
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.