forked from knative/func
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
1655 lines (1409 loc) · 51.6 KB
/
client_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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build !integration
// +build !integration
package function_test
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"reflect"
"sync/atomic"
"testing"
"time"
cloudevents "github.com/cloudevents/sdk-go/v2"
fn "knative.dev/func"
"knative.dev/func/builders"
"knative.dev/func/mock"
. "knative.dev/func/testing"
)
const (
// TestRegistry for calculating destination image during tests.
// Will be optional once we support in-cluster container registries
// by default. See TestRegistryRequired for details.
TestRegistry = "example.com/alice"
// TestRuntime is currently Go, the "reference implementation" and is
// used for verifying functionality that should be runtime agnostic.
TestRuntime = "go"
)
// TestClient_New function completes without error using defaults and zero values.
// New is the superset of creating a new fully deployed function, and
// thus implicitly tests Create, Build and Deploy, which are exposed
// by the client API for those who prefer manual transmissions.
func TestClient_New(t *testing.T) {
root := "testdata/example.com/testNew"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry), fn.WithVerbose(true))
if err := client.New(context.Background(), fn.Function{Root: root, Runtime: TestRuntime}); err != nil {
t.Fatal(err)
}
}
// TestClient_New_RuntimeRequired ensures that the the runtime is an expected value.
func TestClient_New_RuntimeRequired(t *testing.T) {
// Create a root for the new function
root := "testdata/example.com/testRuntimeRequired"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
// Create a new function at root with all defaults.
err := client.New(context.Background(), fn.Function{Root: root})
if err == nil {
t.Fatalf("did not receive error creating a function without specifying runtime")
}
}
// TestClient_New_NameDefaults ensures that a newly created function has its name defaulted
// to a name which can be derived from the last part of the given root path.
func TestClient_New_NameDefaults(t *testing.T) {
root := "testdata/example.com/testNameDefaults"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
f := fn.Function{
Runtime: TestRuntime,
// NO NAME
Root: root,
}
if err := client.New(context.Background(), f); err != nil {
t.Fatal(err)
}
f, err := fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
expected := "testNameDefaults"
if f.Name != expected {
t.Fatalf("name was not defaulted. expected '%v' got '%v'", expected, f.Name)
}
}
// TestClient_New_WritesTemplate ensures the config file and files from the template
// are written on new.
func TestClient_New_WritesTemplate(t *testing.T) {
root := "testdata/example.com/testWritesTemplate"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
// Assert the standard config file was written
if _, err := os.Stat(filepath.Join(root, fn.FunctionFile)); os.IsNotExist(err) {
t.Fatalf("Initialize did not result in '%v' being written to '%v'", fn.FunctionFile, root)
}
// Assert a file from the template was written
if _, err := os.Stat(filepath.Join(root, "README.md")); os.IsNotExist(err) {
t.Fatalf("Initialize did not result in '%v' being written to '%v'", fn.FunctionFile, root)
}
}
// TestClient_New_ExtantAborts ensures that a directory which contains an extant
// function does not reinitialize.
func TestClient_New_ExtantAborts(t *testing.T) {
root := "testdata/example.com/testExtantAborts"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
// First .New should succeed...
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
// Calling again should abort...
if err := client.New(context.Background(), fn.Function{Root: root}); err == nil {
t.Fatal("error expected initilizing a path already containing an initialized function")
}
}
// TestClient_New_NonemptyAborts ensures that a directory which contains any
// (visible) files aborts.
func TestClient_New_NonemptyAborts(t *testing.T) {
root := "testdata/example.com/testNonemptyAborts"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
// Write a visible file which should cause an abort
visibleFile := filepath.Join(root, "file.txt")
if err := os.WriteFile(visibleFile, []byte{}, 0644); err != nil {
t.Fatal(err)
}
// Creation should abort due to the visible file
if err := client.New(context.Background(), fn.Function{Root: root}); err == nil {
t.Fatal("error expected initilizing a function in a nonempty directory")
}
}
// TestClient_New_HiddenFilesIgnored ensures that initializing in a directory that
// only contains hidden files does not error, protecting against the naive
// implementation of aborting initialization if any files exist, which would
// break functions tracked in source control (.git), or when used in
// conjunction with other tools (.envrc, etc)
func TestClient_New_HiddenFilesIgnored(t *testing.T) {
// Create a directory for the function
root := "testdata/example.com/testHiddenFilesIgnored"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
// Create a hidden file that should be ignored.
hiddenFile := filepath.Join(root, ".envrc")
if err := os.WriteFile(hiddenFile, []byte{}, 0644); err != nil {
t.Fatal(err)
}
// Should succeed without error, ignoring the hidden file.
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
}
// TestClient_New_RepositoriesExtensible ensures that templates are extensible
// using a custom path to template repositories on disk. The custom repositories
// location is not defined herein but expected to be provided because, for
// example, a CLI may want to use XDG_CONFIG_HOME. Assuming a repository path
// $FUNC_REPOSITORIES_PATH, a Go template named 'json' which is provided in the
// repository 'boson', would be expected to be in the location:
// $FUNC_REPOSITORIES_PATH/boson/go/json
// See the CLI for full details, but a standard default location is
// $HOME/.config/func/repositories/boson/go/json
func TestClient_New_RepositoriesExtensible(t *testing.T) {
root := "testdata/example.com/testRepositoriesExtensible"
defer Using(t, root)()
client := fn.New(
fn.WithRepositoriesPath("testdata/repositories"),
fn.WithRegistry(TestRegistry))
// Create a function specifying a template which only exists in the extensible set
if err := client.New(context.Background(), fn.Function{Root: root, Runtime: "test", Template: "customTemplateRepo/tplc"}); err != nil {
t.Fatal(err)
}
// Ensure that a file from that only exists in that template set was actually written 'json.js'
if _, err := os.Stat(filepath.Join(root, "customtpl.txt")); os.IsNotExist(err) {
t.Fatalf("Initializing a custom did not result in customtpl.txt being written to '%v'", root)
} else if err != nil {
t.Fatal(err)
}
}
// TestRuntime_New_RuntimeNotFoundError generates an error when the provided
// runtime is not fo0und (embedded default repository).
func TestClient_New_RuntimeNotFoundError(t *testing.T) {
root := "testdata/example.com/testRuntimeNotFound"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
// creating a function with an unsupported runtime should bubble
// the error generated by the underlying template initializer.
err := client.New(context.Background(), fn.Function{Root: root, Runtime: "invalid"})
if !errors.Is(err, fn.ErrRuntimeNotFound) {
t.Fatalf("Expected ErrRuntimeNotFound, got %T", err)
}
}
// TestClient_New_RuntimeNotFoundCustom ensures that the correct error is returned
// when the requested runtime is not found in a given custom repository
func TestClient_New_RuntimeNotFoundCustom(t *testing.T) {
root := "testdata/example.com/testRuntimeNotFoundCustom"
defer Using(t, root)()
// Create a new client with path to the extensible templates
client := fn.New(
fn.WithRepositoriesPath("testdata/repositories"),
fn.WithRegistry(TestRegistry))
// Create a function specifying a runtime, 'python' that does not exist
// in the custom (testdata) repository but does in the embedded.
f := fn.Function{Root: root, Runtime: "python", Template: "customTemplateRepo/event"}
// creating should error as runtime not found
err := client.New(context.Background(), f)
if !errors.Is(err, fn.ErrRuntimeNotFound) {
t.Fatalf("Expected ErrRuntimeNotFound, got %v", err)
}
}
// TestClient_New_TemplateNotFoundError generates an error (embedded default repository).
func TestClient_New_TemplateNotFoundError(t *testing.T) {
root := "testdata/example.com/testTemplateNotFound"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
// creating a function with an unsupported runtime should bubble
// the error generated by the unsderlying template initializer.
f := fn.Function{Root: root, Runtime: "go", Template: "invalid"}
err := client.New(context.Background(), f)
if !errors.Is(err, fn.ErrTemplateNotFound) {
t.Fatalf("Expected ErrTemplateNotFound, got %v", err)
}
}
// TestClient_New_TemplateNotFoundCustom ensures that the correct error is returned
// when the requested template is not found in the given custom repository.
func TestClient_New_TemplateNotFoundCustom(t *testing.T) {
root := "testdata/example.com/testTemplateNotFoundCustom"
defer Using(t, root)()
// Create a new client with path to extensible templates
client := fn.New(
fn.WithRepositoriesPath("testdata/repositories"),
fn.WithRegistry(TestRegistry))
// An invalid template, but a valid custom provider
f := fn.Function{Root: root, Runtime: "test", Template: "customTemplateRepo/invalid"}
// Creation should generate the correct error of template not being found.
err := client.New(context.Background(), f)
if !errors.Is(err, fn.ErrTemplateNotFound) {
t.Fatalf("Expected ErrTemplateNotFound, got %v", err)
}
}
// TestClient_New_Named ensures that an explicitly passed name is used in leau of the
// path derived name when provided, and persists through instantiations.
func TestClient_New_Named(t *testing.T) {
// Explicit name to use
name := "service.example.com"
// Path which would derive to testWithHame.example.com were it not for the
// explicitly provided name.
root := "testdata/example.com/testNamed"
defer Using(t, root)()
client := fn.New(fn.WithRegistry(TestRegistry))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root, Name: name}); err != nil {
t.Fatal(err)
}
f, err := fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
if f.Name != name {
t.Fatalf("expected name '%v' got '%v", name, f.Name)
}
}
// TestClient_New_RegistryRequired ensures that a registry is required, and is
// prepended with the DefaultRegistry if a single token.
// Registry is the namespace at the container image registry.
// If not prepended with the registry, it will be defaulted:
// Examples: "docker.io/alice"
//
// "quay.io/bob"
// "charlie" (becomes [DefaultRegistry]/charlie
//
// At this time a registry namespace is required as we rely on a third-party
// registry in all cases. When we support in-cluster container registries,
// this configuration parameter will become optional.
func TestClient_New_RegistryRequired(t *testing.T) {
// Create a root for the function
root := "testdata/example.com/testRegistryRequired"
defer Using(t, root)()
client := fn.New()
var err error
if err = client.New(context.Background(), fn.Function{Root: root}); err == nil {
t.Fatal("did not receive expected error creating a function without specifying Registry")
}
}
// TestClient_New_ImageNamePopulated ensures that the full image (tag) of the
// resultant OCI container is populated.
func TestClient_New_ImageNamePopulated(t *testing.T) {
// Create the root function directory
root := "testdata/example.com/testDeriveImage"
defer Using(t, root)()
// Create the function which calculates fields such as name and image.
client := fn.New(fn.WithRegistry(TestRegistry))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
// Load the function with the now-populated fields.
f, err := fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
// This opaque-box unit test ensures NewImageTag is invoked and applied.
// See the Test_NewImageTag clear-box unit test for an in-depth exploration of
// how the values of image and registry are treated to create, by default:
// [Default Registry]/[Registry Namespace]/[Service Name]:latest
imageTag, err := f.ImageName()
if err != nil {
t.Fatal(err)
}
if f.Image != imageTag {
t.Fatalf("expected image '%v' got '%v'", imageTag, f.Image)
}
}
// TestCleint_New_ImageRegistryDefaults ensures that a Registry which does not have
// a registry prefix has the DefaultRegistry prepended.
// For example "alice" becomes "docker.io/alice"
func TestClient_New_ImageRegistryDefaults(t *testing.T) {
// Create the root function directory
root := "testdata/example.com/testDeriveImageDefaultRegistry"
defer Using(t, root)()
// Create the function which calculates fields such as name and image.
// Rather than use TestRegistry, use a single-token name and expect
// the DefaultRegistry to be prepended.
client := fn.New(fn.WithRegistry("alice"))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
// Load the function with the now-populated fields.
f, err := fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
// Expected image is [DefaultRegistry]/[namespace]/[servicename]:latest
expected := fn.DefaultRegistry + "/alice/" + f.Name + ":latest"
if f.Image != expected {
t.Fatalf("expected image '%v' got '%v'", expected, f.Image)
}
}
// TestClient_New_Delegation ensures that Create invokes each of the individual
// subcomponents via delegation through Build, Push and
// Deploy (and confirms expected fields calculated).
func TestClient_New_Delegation(t *testing.T) {
var (
root = "testdata/example.com/testNewDelegates" // .. in which to initialize
expectedName = "testNewDelegates" // expected to be derived
expectedImage = "example.com/alice/testNewDelegates:latest"
builder = mock.NewBuilder()
pusher = mock.NewPusher()
deployer = mock.NewDeployer()
)
// Create a directory for the test
defer Using(t, root)()
// Create a client with mocks for each of the subcomponents.
client := fn.New(
fn.WithRegistry(TestRegistry),
fn.WithBuilder(builder), // builds an image
fn.WithPusher(pusher), // pushes images to a registry
fn.WithDeployer(deployer), // deploys images as a running service
)
// Register function delegates on the mocks which validate assertions
// -------------
// The builder should be invoked with a path to a function project's source
// An example image name is returned.
builder.BuildFn = func(f fn.Function) error {
if root != f.Root {
t.Fatalf("builder expected path %v, got '%v'", root, f.Root)
}
return nil
}
pusher.PushFn = func(f fn.Function) (string, error) {
if f.Image != expectedImage {
t.Fatalf("pusher expected image '%v', got '%v'", expectedImage, f.Image)
}
return "", nil
}
deployer.DeployFn = func(_ context.Context, f fn.Function) (res fn.DeploymentResult, err error) {
if f.Name != expectedName {
t.Fatalf("deployer expected name '%v', got '%v'", expectedName, f.Name)
}
if f.Image != expectedImage {
t.Fatalf("deployer expected image '%v', got '%v'", expectedImage, f.Image)
}
return
}
// Invocation
// -------------
// Invoke the creation, triggering the function delegates, and
// perform follow-up assertions that the functions were indeed invoked.
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
// Confirm that each delegate was invoked.
if !builder.BuildInvoked {
t.Fatal("builder was not invoked")
}
if !pusher.PushInvoked {
t.Fatal("pusher was not invoked")
}
if !deployer.DeployInvoked {
t.Fatal("deployer was not invoked")
}
}
// TestClient_Run ensures that the runner is invoked with the absolute path requested.
// Implicitly checks that the stop fn returned also is respected.
func TestClient_Run(t *testing.T) {
// Create the root function directory
root := "testdata/example.com/testRun"
defer Using(t, root)()
// client with the mock runner and the new test function
runner := mock.NewRunner()
client := fn.New(fn.WithRegistry(TestRegistry), fn.WithRunner(runner))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
// Run the newly created function
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
job, err := client.Run(ctx, root)
if err != nil {
t.Fatal(err)
}
defer job.Stop()
// Assert the runner was invoked, and with the expected root.
if !runner.RunInvoked {
t.Fatal("run did not invoke the runner")
}
if runner.RootRequested != root {
t.Fatalf("expected path '%v', got '%v'", root, runner.RootRequested)
}
}
// TestClient_Run_DataDir ensures that when a function is created, it also
// includes a .func (runtime data) directory which is registered as ignored for
// functions which will be tracked in git source control.
// Note that this test is somewhat testing an implementation detail of `.Run(`
// (it writes runtime data to files in .func) but since the feature of adding
// .func to .gitignore is an important externally visible "feature", an explicit
// test is warranted.
func TestClient_Run_DataDir(t *testing.T) {
root := "testdata/example.com/testRunDataDir"
defer Using(t, root)()
// Create a function at root
client := fn.New(fn.WithRegistry(TestRegistry))
if err := client.New(context.Background(), fn.Function{Root: root, Runtime: TestRuntime}); err != nil {
t.Fatal(err)
}
// Assert the directory exists
if _, err := os.Stat(filepath.Join(root, fn.RunDataDir)); os.IsNotExist(err) {
t.Fatal(err)
}
// Assert that .gitignore was also created and includes an ignore directove
// for the .func directory
if _, err := os.Stat(filepath.Join(root, ".gitignore")); os.IsNotExist(err) {
t.Fatal(err)
}
// Assert that .func is ignored
file, err := os.Open(filepath.Join(root, ".gitignore"))
if err != nil {
t.Fatal(err)
}
defer file.Close()
// Assert the directive exists
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() == "/"+fn.RunDataDir {
return // success
}
}
t.Errorf(".gitignore does not include '/%v' ignore directive", fn.RunDataDir)
}
// TestClient_Update ensures that updating invokes the build/push/deploy
// process, erroring if run on a directory uncreated.
func TestClient_Update(t *testing.T) {
var (
root = "testdata/example.com/testUpdate"
expectedName = "testUpdate"
expectedImage = "example.com/alice/testUpdate:latest"
builder = mock.NewBuilder()
pusher = mock.NewPusher()
deployer = mock.NewDeployerWithResult(fn.DeploymentResult{
Status: fn.Deployed,
URL: "example.com",
Namespace: "test-ns",
})
deployerUpdated = mock.NewDeployerWithResult(fn.DeploymentResult{
Status: fn.Updated,
URL: "example.com",
Namespace: "test-ns",
})
)
// Create the root function directory
defer Using(t, root)()
// A client with mocks whose implementaton will validate input.
client := fn.New(
fn.WithRegistry(TestRegistry),
fn.WithBuilder(builder),
fn.WithPusher(pusher),
fn.WithDeployer(deployer))
// create the new function which will be updated
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
// Builder whose implementation verifies the expected root
builder.BuildFn = func(f fn.Function) error {
rootPath, err := filepath.Abs(root)
if err != nil {
t.Fatal(err)
}
if f.Root != rootPath {
t.Fatalf("builder expected path %v, got '%v'", rootPath, f.Root)
}
return nil
}
// Pusher whose implementaiton verifies the expected image
pusher.PushFn = func(f fn.Function) (string, error) {
if f.Image != expectedImage {
t.Fatalf("pusher expected image '%v', got '%v'", expectedImage, f.Image)
}
// image of given name wouold be pushed to the configured registry.
return "", nil
}
// Update whose implementaiton verifed the expected name and image
deployer.DeployFn = func(_ context.Context, f fn.Function) (res fn.DeploymentResult, err error) {
if f.Name != expectedName {
t.Fatalf("updater expected name '%v', got '%v'", expectedName, f.Name)
}
if f.Image != expectedImage {
t.Fatalf("updater expected image '%v', got '%v'", expectedImage, f.Image)
}
return
}
// Invoke the creation, triggering the function delegates, and
// perform follow-up assertions that the functions were indeed invoked.
if err := client.Deploy(context.Background(), root); err != nil {
t.Fatal(err)
}
if !builder.BuildInvoked {
t.Fatal("builder was not invoked")
}
if !pusher.PushInvoked {
t.Fatal("pusher was not invoked")
}
if !deployer.DeployInvoked {
t.Fatal("deployer was not invoked")
}
client = fn.New(
fn.WithRegistry(TestRegistry),
fn.WithBuilder(builder),
fn.WithPusher(pusher),
fn.WithDeployer(deployerUpdated))
// Invoke the update, triggering the function delegates, and
// perform follow-up assertions that the functions were indeed invoked during the update.
if err := client.Deploy(context.Background(), root); err != nil {
t.Fatal(err)
}
if !builder.BuildInvoked {
t.Fatal("builder was not invoked")
}
if !pusher.PushInvoked {
t.Fatal("pusher was not invoked")
}
if !deployerUpdated.DeployInvoked {
t.Fatal("deployer was not invoked")
}
}
// TestClient_Deploy_RegistryUpdate ensures that deploying a Function updates
// its image member on initial deploy, and on subsequent deploys only
// if reset to it zero value.
func TestClient_Deploy_RegistryUpdate(t *testing.T) {
root, rm := Mktemp(t)
defer rm()
client := fn.New(fn.WithRegistry("example.com/alice"))
// New runs build and deploy, thus the initial instantiation should result in
// the member being populated from the client's registry and function name.
if err := client.New(context.Background(), fn.Function{Runtime: "go", Name: "f", Root: root}); err != nil {
t.Fatal(err)
}
f, err := fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
if f.Image != "example.com/alice/f:latest" {
t.Error("image name was not initially set")
}
// Updating the registry and performing a subsequent update should not result
// in the image member being updated to the new value: registry is only used
// when calculating a nonexistent value
f.Registry = "example.com/bob"
if err := f.Write(); err != nil {
t.Fatal(err)
}
if err := client.Build(context.Background(), root); err != nil {
t.Fatal(err)
}
if err := client.Deploy(context.Background(), root); err != nil {
t.Fatal(err)
}
expected := "example.com/alice/f:latest"
f, err = fn.NewFunction(root) // reload and check
if err != nil {
t.Fatal(err)
}
if f.Image != expected { // NOT changed to bob
t.Errorf("expected image name to stay '%v' and not be updated, but got '%v'", expected, f.Image)
}
// Reset the value of .Image to default "" and ensure this triggers recalc.
f.Image = ""
f.Registry = "example.com/bob"
if err := f.Write(); err != nil {
t.Fatal(err)
}
if err := client.Build(context.Background(), root); err != nil {
t.Fatal(err)
}
if err := client.Deploy(context.Background(), root); err != nil {
t.Fatal(err)
}
expected = "example.com/bob/f:latest"
f, err = fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
if f.Image != expected { // DOES change to bob
t.Errorf("expected image name to stay '%v' and not be updated, but got '%v'", expected, f.Image)
}
}
// TestClient_Remove_ByPath ensures that the remover is invoked to remove
// the function with the name of the function at the provided root.
func TestClient_Remove_ByPath(t *testing.T) {
var (
root = "testdata/example.com/testRemoveByPath"
expectedName = "testRemoveByPath"
remover = mock.NewRemover()
)
defer Using(t, root)()
client := fn.New(
fn.WithRegistry(TestRegistry),
fn.WithRemover(remover))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
remover.RemoveFn = func(name string) error {
if name != expectedName {
t.Fatalf("Expected to remove '%v', got '%v'", expectedName, name)
}
return nil
}
if err := client.Remove(context.Background(), fn.Function{Root: root}, false); err != nil {
t.Fatal(err)
}
if !remover.RemoveInvoked {
t.Fatal("remover was not invoked")
}
}
// TestClient_Remove_DeleteAll ensures that the remover is invoked to remove
// and that dependent resources are removed as well -> pipeline provider is invoked
// the function with the name of the function at the provided root.
func TestClient_Remove_DeleteAll(t *testing.T) {
var (
root = "testdata/example.com/testRemoveDeleteAll"
expectedName = "testRemoveDeleteAll"
remover = mock.NewRemover()
pipelinesProvider = mock.NewPipelinesProvider()
deleteAll = true
)
defer Using(t, root)()
client := fn.New(
fn.WithRegistry(TestRegistry),
fn.WithRemover(remover),
fn.WithPipelinesProvider(pipelinesProvider))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
remover.RemoveFn = func(name string) error {
if name != expectedName {
t.Fatalf("Expected to remove '%v', got '%v'", expectedName, name)
}
return nil
}
if err := client.Remove(context.Background(), fn.Function{Root: root}, deleteAll); err != nil {
t.Fatal(err)
}
if !remover.RemoveInvoked {
t.Fatal("remover was not invoked")
}
if !pipelinesProvider.RemoveInvoked {
t.Fatal("pipelinesprovider was not invoked")
}
}
// TestClient_Remove_Dont_DeleteAll ensures that the remover is invoked to remove
// and that dependent resources are not removed as well -> pipeline provider not is invoked
// the function with the name of the function at the provided root.
func TestClient_Remove_Dont_DeleteAll(t *testing.T) {
var (
root = "testdata/example.com/testRemoveDontDeleteAll"
expectedName = "testRemoveDontDeleteAll"
remover = mock.NewRemover()
pipelinesProvider = mock.NewPipelinesProvider()
deleteAll = false
)
defer Using(t, root)()
client := fn.New(
fn.WithRegistry(TestRegistry),
fn.WithRemover(remover),
fn.WithPipelinesProvider(pipelinesProvider))
if err := client.New(context.Background(), fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
remover.RemoveFn = func(name string) error {
if name != expectedName {
t.Fatalf("Expected to remove '%v', got '%v'", expectedName, name)
}
return nil
}
if err := client.Remove(context.Background(), fn.Function{Root: root}, deleteAll); err != nil {
t.Fatal(err)
}
if !remover.RemoveInvoked {
t.Fatal("remover was not invoked")
}
if pipelinesProvider.RemoveInvoked {
t.Fatal("pipelinesprovider was invoked, but should not")
}
}
// TestClient_Remove_ByName ensures that the remover is invoked to remove the function
// of the name provided, with precedence over a provided root path.
func TestClient_Remove_ByName(t *testing.T) {
var (
root = "testdata/example.com/testRemoveByName"
expectedName = "explicitName.example.com"
remover = mock.NewRemover()
)
defer Using(t, root)()
client := fn.New(
fn.WithRegistry(TestRegistry),
fn.WithRemover(remover))
if err := client.Create(fn.Function{Runtime: TestRuntime, Root: root}); err != nil {
t.Fatal(err)
}
remover.RemoveFn = func(name string) error {
if name != expectedName {
t.Fatalf("Expected to remove '%v', got '%v'", expectedName, name)
}
return nil
}
// Run remove with only a name
if err := client.Remove(context.Background(), fn.Function{Name: expectedName}, false); err != nil {
t.Fatal(err)
}
// Run remove with a name and a root, which should be ignored in favor of the name.
if err := client.Remove(context.Background(), fn.Function{Name: expectedName, Root: root}, false); err != nil {
t.Fatal(err)
}
if !remover.RemoveInvoked {
t.Fatal("remover was not invoked")
}
}
// TestClient_Remove_UninitializedFails ensures that removing a function
// by path only (no name) fails unless the function has been initialized. I.e.
// the name will not be derived from path and the function removed by this
// derived name; which could be unexpected and destructive.
func TestClient_Remove_UninitializedFails(t *testing.T) {
var (
root = "testdata/example.com/testRemoveUninitializedFails"
remover = mock.NewRemover()
)
defer Using(t, root)()
// remover fails if invoked
remover.RemoveFn = func(name string) error {
return fmt.Errorf("remove invoked for unitialized function %v", name)
}
// Instantiate the client with the failing remover.
client := fn.New(
fn.WithRegistry(TestRegistry),
fn.WithRemover(remover))
// Attempt to remove by path (uninitialized), expecting an error.
if err := client.Remove(context.Background(), fn.Function{Root: root}, false); err == nil {
t.Fatalf("did not received expeced error removing an uninitialized func")
}
}
// TestClient_List merely ensures that the client invokes the configured lister.
func TestClient_List(t *testing.T) {
lister := mock.NewLister()
client := fn.New(fn.WithLister(lister)) // lists deployed functions.
if _, err := client.List(context.Background()); err != nil {
t.Fatal(err)
}
if !lister.ListInvoked {
t.Fatal("list did not invoke lister implementation")
}
}
// TestClient_List_OutsideRoot ensures that a call to a function (in this case list)
// that is not contextually dependent on being associated with a function,
// can be run from anywhere, thus ensuring that the client itself makes
// a distinction between function-scoped methods and not.
func TestClient_List_OutsideRoot(t *testing.T) {
lister := mock.NewLister()
// Instantiate in the current working directory, with no name.
client := fn.New(fn.WithLister(lister))
if _, err := client.List(context.Background()); err != nil {
t.Fatal(err)
}
if !lister.ListInvoked {
t.Fatal("list did not invoke lister implementation")
}
}
// TestClient_Deploy_Image ensures that initially the function's image
// member has no value (not initially deployed); the value is populated
// upon deployment with a value derived from the function's name and currently
// effective client registry; that the value of f.Image will take precedence
// over .Registry, which is used to calculate a default value for image.
func TestClient_Deploy_Image(t *testing.T) {
root, rm := Mktemp(t)
defer rm()
client := fn.New(
fn.WithBuilder(mock.NewBuilder()),
fn.WithDeployer(mock.NewDeployer()),
fn.WithRegistry("example.com/alice"))
err := client.Create(fn.Function{Name: "myfunc", Runtime: "go", Root: root})
if err != nil {
t.Fatal(err)
}
f, err := fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
// Upon initial creation, the value of .Image is empty
if f.Image != "" {
t.Fatalf("new function should have no image, got '%v'", f.Image)
}
// Upon deployment, the function should be populated;
if err = client.Build(context.Background(), root); err != nil {
t.Fatal(err)
}
if err = client.Deploy(context.Background(), root); err != nil {
t.Fatal(err)
}
f, err = fn.NewFunction(root)
if err != nil {
t.Fatal(err)
}
expected := "example.com/alice/myfunc:latest"
if f.Image != expected {
t.Fatalf("expected image '%v', got '%v'", expected, f.Image)
}
expected = "example.com/alice"
if f.Registry != "example.com/alice" {
t.Fatalf("expected registry '%v', got '%v'", expected, f.Registry)
}