-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathe2e_test.go
More file actions
1333 lines (1162 loc) · 45.8 KB
/
Copy pathe2e_test.go
File metadata and controls
1333 lines (1162 loc) · 45.8 KB
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 e2e
/*
Package e2e provides an end-to-end test suite for the Functions CLI "func".
See README.md for more details.
*/
package e2e
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"text/template"
"time"
fn "knative.dev/func/pkg/functions"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"knative.dev/func/pkg/k8s"
)
const (
// DefaultBin is the default binary to run, relative to this test file.
// This is the binary built by default when running 'make'.
// This can be customized with FUNC_E2E_BIN.
// Note this is always relative to this test file.
DefaultBin = "../func"
// DefaultClean indicates whether or not tests should clean up after
// themselves by deleting Function instances created during run.
// Setting this to false significantly increases testing speed, but
// results in lingering function instances after at test run. Set to
// "false" when expecting the test cluster to be removed after a test run,
// such as in CI, but set to "true" for development, when the same test
// cluster may be used across multiple test runs during debugging.
DefaultClean = true
// DefaultCleanImages indicates whether or not tests should clean up container
// images and volumes after themselves. This is separate from DefaultClean
// which handles cluster resources. This is necessary in CI which quickly
// runs out of disk space during Quarkus and Springboot builds.
// Disable with FUNC_E2E_CLEAN_IMAGES="false".
DefaultCleanImages = true
// DefaultGocoverdir defines the default path to use for the GOCOVERDIR
// while executing tests. This value can be altered using
// FUNC_E2E_GOCOVERDIR. While this value could be passed through using
// its original environment variable name "GOCOVERDIR", to keep with the
// isolation of environment provided for all other values, this one is
// likewise also isolated using the "FUNC_E2E_" prefix.
DefaultGocoverdir = "../.coverage"
// DefaultKubeconfig is the default path (relative to this test file) at
// which the kubeconfig can be found which was created when setting up
// a local test cluster using the cluster.sh script. This can be
// overridden using FUNC_E2E_KUBECONFIG.
DefaultKubeconfig = "../hack/bin/kubeconfig.yaml"
// DefaultNamespace for E2E tests. Defaults to "default" but can be
// overridden using FUNC_E2E_NAMESPACE environment variable.
DefaultNamespace = "default"
// DefaultBrokerHost is the hostname of the Knative broker ingress.
// Defaults to "broker.localtest.me" but can be overridden using
// FUNC_E2E_BROKER_HOST environment variable.
DefaultBrokerHost = "broker.localtest.me"
// DefaultDomain for E2E tests. Defaults to "localtest.me" but can be
// overridden using FUNC_E2E_DOMAIN environment variable. This domain
// must be properly configured in the cluster's DNS and Knative serving.
DefaultDomain = "localtest.me"
// DefaultRegistry to use when running the e2e tests. This is the URL
// of the registry created by default when using the cluster.sh script
// to set up a local testing cluster, but can be customized with
// FUNC_E2E_REGISTRY.
DefaultRegistry = "registry.localtest.me/func"
// DefaultClusterRegistry to use for in-cluster (remote) builds.
// This is the cluster-internal registry URL accessible from within
// the cluster for Tekton builds. Can be customized with
// FUNC_E2E_CLUSTER_REGISTRY.
DefaultClusterRegistry = "registry.localtest.me/func"
// DefaultVerbose sets the default for the --verbose flag of all commands.
DefaultVerbose = false
// DefaultTools is the path to supporting tools.
DefaultTools = "../hack/bin"
// DefaultTestdata is the path to supporting testdata
DefaultTestdata = "./testdata"
)
// Final Settings
// Populated during init phase (see init func in Helpers below)
var (
// Bin is the absolute path to the binary to use when testing.
// Can be set with FUNC_E2E_BIN.
Bin string
// Clean instructs the system to remove resources created during testing.
// Defaults to true. Can be disabled with FUNC_E2E_CLEAN to speed up tests,
// if the cluster is expected to be removed upon completion (such as in CI)
Clean bool
// CleanImages instructs the system to remove container images and volumes
// created during testing. Separate from Clean which handles cluster resources.
CleanImages bool
// DockerHost is the DOCKER_HOST value to use for tests.
// Can be set with FUNC_E2E_DOCKER_HOST.
DockerHost string
// Domain is the DNS domain suffix used for constructing function URLs
// during tests. Defaults to "localtest.me". When using a custom domain,
// ensure it is configured in the cluster's CoreDNS and Knative serving
// config-domain. The pattern is: http://{function}.{namespace}.{domain}
// Can be set with FUNC_E2E_DOMAIN
Domain string
// Gocoverdir is the path to the directory which will be used for Go's
// coverage reporting, provided to the test binary as GOCOVERDIR. By
// default the current user's environment is not used, and by default this
// is set to ../.coverage (as relative to this test file). This value
// can be overridden with FUNC_E2E_GOCOVERDIR.
Gocoverdir string
// Kubeconfig is the path at which a kubeconfig suitable for running
// E2E tests can be found. By default the config located in
// hack/bin/kubeconfig.yaml will be used. This is created when running
// hack/cluster.sh to set up a local test cluster.
// To avoid confusion, the current user's KUBECONFIG will not be used.
// Instead, this can be set explicitly using FUNC_E2E_KUBECONFIG.
Kubeconfig string
// Matrix indicates a full matrix test should be run. Defaults to false.
// Enable with FUNC_E2E_MATRIX=true
Matrix bool
// MatrixBuilders specifies builders to check during matrix tests.
// Can be set with FUNC_E2E_MATRIX_BUILDERS.
MatrixBuilders = []string{"host", "s2i", "pack"}
// MatrixRuntimes for which runtime-specific tests should be run. Defaults
// to all core language runtimes. Can be set with FUNC_E2E_MATRIX_RUNTIMES
MatrixRuntimes = []string{"go", "python", "node", "typescript", "rust", "quarkus", "springboot"}
// MatrixTemplates specifies the templates to check during matrix tests.
MatrixTemplates = []string{"http", "cloudevents"}
// BrokerHost is the hostname of the Knative broker ingress.
// Defaults to "broker.localtest.me". Can be set with FUNC_E2E_BROKER_HOST.
BrokerHost string
// Namespace is the Kubernetes namespace where functions will be deployed
// during tests. Defaults to "default". When using a custom namespace,
// ensure DNS is configured for {function}.{namespace}.{domain} patterns.
// Can be set with FUNC_E2E_NAMESPACE
Namespace string
// Plugin indicates func is being run as a plugin within Bin, and
// the value of this argument is the subcommand. For example, when
// running e2e tests as a plugin to `kn`, Bin will be /path/to/kn and
// 'Plugin' would be 'func'. The resultant commands would then be
// /path/to/kn func {command}
// Can be set with FUNC_E2E_PLUGIN
Plugin string
// PodmanHost is the DOCKER_HOST value to use specifically for Podman tests.
// Can be set with FUNC_E2E_PODMAN_HOST.
PodmanHost string
// Registry is the container registry to use by default for tests;
// defaulting to the local container registry set up by the allocation
// script running on localhost:5000.
// Can be set with FUNC_E2E_REGISTRY
Registry string
// ClusterRegistry is the cluster-internal container registry to use
// for in-cluster (remote) builds with Tekton. This is the registry
// accessible from within the cluster.
// Can be set with FUNC_E2E_CLUSTER_REGISTRY
ClusterRegistry string
// Podman indicates that the Pack and S2I builders should be used and
// checked with the Podman container engine.
// Set with FUNC_E2E_PODMAN
Podman bool = false
// ConfigCI enables Config CI tests which deploy functions via
// generated GitHub Actions workflows using nektos/act.
// Set with FUNC_E2E_CONFIG_CI
ConfigCI bool = false
// Verbose mode for all command runs.
// Set with FUNC_E2E_VERBOSE
Verbose bool
// Tools is the path to tools which the E2E tests should use with
// precedence. It's a path, and is prepended to PATH. By default this
// is ./hack/bin which contains commands installed via ./hack/binaries.sh
// (and should be of a known compatible version). Set with FUNC_E2E_TOOLS
Tools string
// Testdata is the path to the testdata directory, defaulting to ./testdata
// Set with FUNC_E2E_TESTDATA
Testdata string
)
// ----------------------------------------------------------------------------
// Test Initialization
// ----------------------------------------------------------------------------
//
// NOTE: Deprecated ENVS for backwards compatibility are mapped as follows:
// OLD New Final Variable
// ---------------------------------------------------
// E2E_FUNC_BIN => FUNC_E2E_BIN => Bin
// E2E_USE_KN_FUNC => FUNC_E2E_PLUGIN => Plugin
// E2E_REGISTRY_URL => FUNC_E2E_REGISTRY => Registry
// E2E_RUNTIMES => FUNC_E2E_MATRIX_RUNTIMES => MatrixRuntimes
//
// init global settings for the current run from environment
// we read E2E config settings passed via the FUNC_E2E_* environment
// variables. These globals are used when creating test cases.
// Some tests pass these values as flags, sometimes as environment variables,
// sometimes not at all; hence why the actual environment setup is deferred
// into each test, merely reading them in here during E2E process init.
func init() {
fmt.Fprintln(os.Stderr, "Initializing E2E Tests")
fmt.Fprintln(os.Stderr, "----------------------")
// Dump full environment when CI_DEBUGGING is set
// (useful primarily when debugging a CI environment)
if os.Getenv("CI_DEBUGGING") != "" {
fmt.Fprintln(os.Stderr, "-- Initial Environment: ")
for _, env := range os.Environ() {
fmt.Fprintln(os.Stderr, " ", env)
}
fmt.Fprintln(os.Stderr, "---------------------")
}
fmt.Fprintln(os.Stderr, "-- Preserved Environment: ")
fmt.Fprintf(os.Stderr, " HOME=%v\n", os.Getenv("HOME"))
fmt.Fprintf(os.Stderr, " PATH=%v\n", os.Getenv("PATH"))
fmt.Fprintf(os.Stderr, " XDG_CONFIG_HOME=%v\n", os.Getenv("XDG_CONFIG_HOME"))
fmt.Fprintf(os.Stderr, " XDG_RUNTIME_DIR=%v\n", os.Getenv("XDG_RUNTIME_DIR"))
fmt.Fprintln(os.Stderr, "-- Config Provided: ")
fmt.Fprintf(os.Stderr, " FUNC_E2E_BIN=%v\n", os.Getenv("FUNC_E2E_BIN"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_CLEAN=%v\n", os.Getenv("FUNC_E2E_CLEAN"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_CLEAN_IMAGES=%v\n", os.Getenv("FUNC_E2E_CLEAN_IMAGES"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_DOCKER_HOST=%v\n", os.Getenv("FUNC_E2E_DOCKER_HOST"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_BROKER_HOST=%v\n", os.Getenv("FUNC_E2E_BROKER_HOST"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_DOMAIN=%v\n", os.Getenv("FUNC_E2E_DOMAIN"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_GOCOVERDIR=%v\n", os.Getenv("FUNC_E2E_GOCOVERDIR"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_HOME=%v\n", os.Getenv("FUNC_E2E_HOME"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_KUBECONFIG=%v\n", os.Getenv("FUNC_E2E_KUBECONFIG"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_MATRIX=%v\n", os.Getenv("FUNC_E2E_MATRIX"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_MATRIX_BUILDERS=%v\n", os.Getenv("FUNC_E2E_MATRIX_BUILDERS"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_MATRIX_RUNTIMES=%v\n", os.Getenv("FUNC_E2E_MATRIX_RUNTIMES"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_NAMESPACE=%v\n", os.Getenv("FUNC_E2E_NAMESPACE"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_PLUGIN=%v\n", os.Getenv("FUNC_E2E_PLUGIN"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_PODMAN_HOST=%v\n", os.Getenv("FUNC_E2E_PODMAN_HOST"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_REGISTRY=%v\n", os.Getenv("FUNC_E2E_REGISTRY"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_PODMAN=%v\n", os.Getenv("FUNC_E2E_PODMAN"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_CONFIG_CI=%v\n", os.Getenv("FUNC_E2E_CONFIG_CI"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_TOOLS=%v\n", os.Getenv("FUNC_E2E_TOOLS"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_TESTDATA=%v\n", os.Getenv("FUNC_E2E_TESTDATA"))
fmt.Fprintf(os.Stderr, " FUNC_E2E_VERBOSE=%v\n", os.Getenv("FUNC_E2E_VERBOSE"))
fmt.Fprintf(os.Stderr, " (deprecated) E2E_FUNC_BIN=%v\n", os.Getenv("E2E_FUNC_BIN"))
fmt.Fprintf(os.Stderr, " (deprecated) E2E_REGISTRY_URL=%v\n", os.Getenv("E2E_REGISTRY_URL"))
fmt.Fprintf(os.Stderr, " (deprecated) E2E_RUNTIMES=%v\n", os.Getenv("E2E_RUNTIMES"))
fmt.Fprintf(os.Stderr, " (deprecated) E2E_USE_KN_FUNC=%v\n", os.Getenv("E2E_USE_KN_FUNC"))
fmt.Fprintln(os.Stderr, "---------------------")
// Read all envs into their final variables
readEnvs()
fmt.Fprintln(os.Stderr, "Final Config:")
fmt.Fprintf(os.Stderr, " Bin=%v\n", Bin)
fmt.Fprintf(os.Stderr, " BrokerHost=%v\n", BrokerHost)
fmt.Fprintf(os.Stderr, " Clean=%v\n", Clean)
fmt.Fprintf(os.Stderr, " CleanImages=%v\n", CleanImages)
fmt.Fprintf(os.Stderr, " DockerHost=%v\n", DockerHost)
fmt.Fprintf(os.Stderr, " Domain=%v\n", Domain)
fmt.Fprintf(os.Stderr, " Gocoverdir=%v\n", Gocoverdir)
fmt.Fprintf(os.Stderr, " Kubeconfig=%v\n", Kubeconfig)
fmt.Fprintf(os.Stderr, " Matrix=%v\n", Matrix)
fmt.Fprintf(os.Stderr, " MatrixBuilders=%v\n", toCSV(MatrixBuilders))
fmt.Fprintf(os.Stderr, " MatrixRuntimes=%v\n", toCSV(MatrixRuntimes))
fmt.Fprintf(os.Stderr, " MatrixTemplates=%v\n", toCSV(MatrixTemplates))
fmt.Fprintf(os.Stderr, " Namespace=%v\n", Namespace)
fmt.Fprintf(os.Stderr, " Plugin=%v\n", Plugin)
fmt.Fprintf(os.Stderr, " PodmanHost=%v\n", PodmanHost)
fmt.Fprintf(os.Stderr, " Registry=%v\n", Registry)
fmt.Fprintf(os.Stderr, " ClusterRegistry=%v\n", ClusterRegistry)
fmt.Fprintf(os.Stderr, " Podman=%v\n", Podman)
fmt.Fprintf(os.Stderr, " Tools=%v\n", Tools)
fmt.Fprintf(os.Stderr, " Testdata=%v\n", Testdata)
fmt.Fprintf(os.Stderr, " Verbose=%v\n", Verbose)
// Coverage
// --------
// Create Gocoverdir if it does not already exist
if err := os.MkdirAll(Gocoverdir, 0755); err != nil {
fmt.Fprintf(os.Stderr, "error creating coverage directory %q: %v\n", Gocoverdir, err)
}
// Version
fmt.Fprintln(os.Stderr, "---------------------")
fmt.Fprintln(os.Stderr, "Func Version:")
printVersion()
fmt.Fprintln(os.Stderr, "--- init complete ---")
}
// readEnvs and apply defaults, populating the named global variables with
// the final values which will be used by all tests.
func readEnvs() {
// Bin - path to binary which will be used when running the tests.
Bin = getEnvPath("FUNC_E2E_BIN", "E2E_FUNC_BIN", DefaultBin)
// Final = current ENV, deprecated ENV, default
// BrokerHost - the hostname of the Knative broker ingress
BrokerHost = getEnv("FUNC_E2E_BROKER_HOST", "", DefaultBrokerHost)
// Clean up deployed functions before starting next test
Clean = getEnvBool("FUNC_E2E_CLEAN", "", DefaultClean)
// Clean up container images and volumes after tests
CleanImages = getEnvBool("FUNC_E2E_CLEAN_IMAGES", "", DefaultCleanImages)
// DockerHost - the DOCKER_HOST to use for container operations (not including podman-specific tests)
DockerHost = getEnv("FUNC_E2E_DOCKER_HOST", "", "")
// Domain - the DNS domain suffix for function URLs
Domain = getEnv("FUNC_E2E_DOMAIN", "", DefaultDomain)
// Gocoverdir - the coverage directory to use while testing the go binary.
Gocoverdir = getEnvPath("FUNC_E2E_GOCOVERDIR", "", DefaultGocoverdir)
// Kubeconfig - the kubeconfig to pass ass KUBECONFIG env to test
// environments.
Kubeconfig = getEnvPath("FUNC_E2E_KUBECONFIG", "", DefaultKubeconfig)
// Matrix - optionally enable matrix test
Matrix = getEnvBool("FUNC_E2E_MATRIX", "", false)
// Builders - can optionally pass a list of builders to test, overriding
// the default of testing all. Example "FUNC_E2E_MATRIX_BUILDERS=pack,s2i"
MatrixBuilders = getEnvList("FUNC_E2E_MATRIX_BUILDERS", "", toCSV(MatrixBuilders))
// Runtimes - can optionally pass a list of runtimes to test, overriding
// the default of testing all builtin runtimes.
// Example "FUNC_E2E_MATRIX_RUNTIMES=go,python"
MatrixRuntimes = getEnvList("FUNC_E2E_MATRIX_RUNTIMES", "E2E_RUNTIMES", toCSV(MatrixRuntimes))
// Templates
MatrixTemplates = getEnvList("FUNC_E2E_MATRIX_TEMPLATES", "", toCSV(MatrixTemplates))
// Namespace - the Kubernetes namespace where functions will be deployed
Namespace = getEnv("FUNC_E2E_NAMESPACE", "", DefaultNamespace)
// Plugin - if set, func is a plugin and Bin is the one plugging. The value
// is the name of the subcommand.
Plugin = getEnv("FUNC_E2E_PLUGIN", "E2E_USE_KN_FUNC", "")
// Plugin Backwards compatibility:
// If set to "true", the default value is "func" because the deprecated
// value was literal string "true".
if Plugin == "true" {
Plugin = "func"
}
// Podman - optionally enable Podman S2I and Builder test
Podman = getEnvBool("FUNC_E2E_PODMAN", "", false)
// ConfigCI - optionally enable Config CI tests
ConfigCI = getEnvBool("FUNC_E2E_CONFIG_CI", "", false)
// PodmanHost - the DOCKER_HOST to use specifically during Podman tests
// If FUNC_E2E_PODMAN is enabled but FUNC_E2E_PODMAN_HOST is not set,
// try to auto-detect the Podman socket path
PodmanHost = getEnv("FUNC_E2E_PODMAN_HOST", "", "")
if Podman && PodmanHost == "" {
PodmanHost = detectPodmanSocket()
if PodmanHost != "" {
fmt.Fprintf(os.Stderr, " Auto-detected Podman socket: %s\n", PodmanHost)
}
}
// Registry - the registry URL including any account/repository at that
// registry. Example: docker.io/alice. Default is the local registry.
Registry = getEnv("FUNC_E2E_REGISTRY", "E2E_REGISTRY_URL", DefaultRegistry)
// ClusterRegistry - the cluster-internal registry URL for in-cluster builds
ClusterRegistry = getEnv("FUNC_E2E_CLUSTER_REGISTRY", "", DefaultClusterRegistry)
// Verbose env as a truthy boolean
Verbose = getEnvBool("FUNC_E2E_VERBOSE", "", DefaultVerbose)
// Tools - the path to supporting tools.
Tools = getEnvPath("FUNC_E2E_TOOLS", "", DefaultTools)
// Testdata - the path to supporting testdata
Testdata = getEnvPath("FUNC_E2E_TESTDATA", "", DefaultTestdata)
}
// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
// fromCleanEnv provides a clean environment for a function E2E test.
func fromCleanEnv(t *testing.T, name string) (root string) {
root = cdTemp(t, name)
setupEnv(t)
return
}
// cdTmp changes to a new temporary directory for running the test.
// Essentially equivalent to creating a new directory before beginning to
// use func. The path created is returned.
func cdTemp(t *testing.T, name string) string {
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
tmp := filepath.Join(t.TempDir(), name)
if err := os.MkdirAll(tmp, 0755); err != nil {
panic(err)
}
if err := os.Chdir(tmp); err != nil {
panic(err)
}
t.Cleanup(func() {
if err := os.Chdir(pwd); err != nil {
panic(err)
}
})
return tmp
}
// setupEnv before running a test to remove all environment variables and
// set the required environment variables to those specified during
// initialization.
//
// Every test must be run with a nearly completely isolated environment,
// otherwise a developer's local environment will affect the E2E tests when
// run locally outside of CI. Some environment variables, provided via
// FUNC_E2E_* or other settings, are explicitly set here.
func setupEnv(t *testing.T) {
t.Helper()
// Preserve HOME, PATH and some XDG paths, and PATH
home := os.Getenv("HOME")
path := Tools + ":" + os.Getenv("PATH") // Prepend E2E tools
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
// Preserve SSH environment variables for git operations (needed when
// git configs rewrite HTTPS URLs to SSH URLs)
sshAuthSock := os.Getenv("SSH_AUTH_SOCK")
sshAgentPid := os.Getenv("SSH_AGENT_PID")
// Clear everything else
os.Clearenv()
os.Setenv("HOME", home)
os.Setenv("PATH", path)
os.Setenv("XDG_CONFIG_HOME", xdgConfigHome)
os.Setenv("XDG_RUNTIME_DIR", xdgRuntimeDir)
if sshAuthSock != "" {
os.Setenv("SSH_AUTH_SOCK", sshAuthSock)
}
if sshAgentPid != "" {
os.Setenv("SSH_AGENT_PID", sshAgentPid)
}
os.Setenv("KUBECONFIG", Kubeconfig)
os.Setenv("GOCOVERDIR", Gocoverdir)
os.Setenv("FUNC_VERBOSE", fmt.Sprintf("%t", Verbose))
// The Registry will be set either during first-time setup using the
// global config, or already defaulted by the user via environment variable.
os.Setenv("FUNC_REGISTRY", Registry)
// When using the default registry (registry.localtest.me), mark it as
// insecure since it serves plain HTTP.
if strings.Contains(Registry, "registry.localtest.me") {
os.Setenv("FUNC_REGISTRY_INSECURE", "true")
}
// If the docker host is set, it should affect any tests which perform
// container operations except for podman-specific tests. These use
// the FUNC_E2E_PODMAN_HOST value during test execution directly.
os.Setenv("DOCKER_HOST", DockerHost)
// The following host-builder related settings will become the defaults
// once the host builder supports the core runtimes. Setting them here in
// order to futureproof individual tests.
os.Setenv("FUNC_BUILDER", "host") // default to host builder
os.Setenv("FUNC_CONTAINER", "false") // "run" uses host builder
}
// setupPodmanEnvs
// - configures VM to treat registry.localtest.me as an insecure registry
// - creates an XDG_CONFIG_HOME and XDG_DATA_HOME
func setupPodman(t *testing.T) error {
t.Helper()
// Podman Socket
os.Setenv("DOCKER_HOST", PodmanHost)
// Podman Config
// NOTE: the unqualified-search-registries and short-name-mode may be
// unnecessary.
cfg := `unqualified-search-registries = ["docker.io", "quay.io", "registry.fedoraproject.org", "registry.access.redhat.com"]
short-name-mode="permissive"
[[registry]]
location="registry.localtest.me"
insecure=true
`
cfgPath := filepath.Join(t.TempDir(), "registries.conf")
if err := os.WriteFile(cfgPath, []byte(cfg), 0644); err != nil {
return fmt.Errorf("failed to create registries.conf: %v", err)
}
os.Setenv("CONTAINERS_REGISTRIES_CONF", cfgPath)
// Done if Linux
if runtime.GOOS == "linux" {
// Podman machine setup is only needed on macOS/Windows
// On Linux, Podman runs natively without a VM
t.Log("Running on Linux - Podman machine setup not needed")
return nil
}
// Windows and Darwin must run Podman in a VM.
// connect the pipes
// List available machines (debug)
t.Log("Available Podman Machines:")
listCmd := exec.Command("podman", "machine", "list")
output, err := listCmd.CombinedOutput()
if err != nil {
return err
}
t.Logf("%s", output)
// Check if a Podman machine is running
// The output contains "Currently running" or similar text when a machine is active
if !strings.Contains(string(output), "Currently running") && !strings.Contains(string(output), "Running") {
return fmt.Errorf("Podman machine is not running. Please start it with: podman machine start podman-machine-default")
}
return nil
}
// newCmd returns an *exec.Cmd
// bin will be FUNC_E2E_BIN, and if FUNC_E2E_PLUGIN is set, the subcommand
// will be set as well. Arguments are set to those provided.
func newCmd(t *testing.T, args ...string) *exec.Cmd {
t.Helper()
bin := Bin
// If Plugin provided, it is a subcommand so prepend it to args.
if Plugin != "" {
args = append([]string{Plugin}, args...)
}
// Add verbose flag if Verbose is set
if Verbose {
args = append(args, "-v")
}
// Debug
b := strings.Builder{}
for _, arg := range args {
b.WriteString(arg + " ")
}
base := filepath.Base(bin)
t.Logf("$ %v %v\n", base, b.String())
cmd := exec.Command(bin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd
}
type waitOption func(*waitCfg)
type waitCfg struct {
timeout time.Duration // total time to wait
interval time.Duration // time between retries
warnThreshold time.Duration // start warning after this long
warnInterval time.Duration // only warn this often
content string // match content vs default HTTP OK
template string // template name
}
func withWaitTimeout(t time.Duration) waitOption {
return func(cfg *waitCfg) {
cfg.timeout = t
}
}
func withTemplate(t string) waitOption {
return func(cfg *waitCfg) {
cfg.template = t
}
}
func withContentMatch(c string) waitOption {
return func(cfg *waitCfg) {
cfg.content = c
}
}
func waitFor(t *testing.T, address string, options ...waitOption) (ok bool) {
t.Helper()
cfg := waitCfg{}
for _, o := range options {
o(&cfg)
}
if cfg.template == "cloudevents" {
return waitForCloudevent(t, address, options...)
} else if cfg.content != "" {
return waitForContent(t, address, cfg.content, "expected content not found", options...)
} else {
return waitForContent(t, address, "OK", "expected OK response", options...)
}
}
// waitForCloudevent returns true if there is a service at the given address
// which accepts CloudEvents and responds with HTTP 200 when given a cloudevent
func waitForCloudevent(t *testing.T, address string, options ...waitOption) (ok bool) {
t.Helper()
cfg := waitCfg{
timeout: 2 * time.Minute,
interval: 5 * time.Second,
warnThreshold: 30 * time.Second,
warnInterval: 10 * time.Second,
}
for _, o := range options {
o(&cfg)
}
client := &http.Client{}
startTime := time.Now()
lastWarnTime := time.Time{}
attemptCount := 0
for time.Since(startTime) < cfg.timeout {
attemptCount++
time.Sleep(cfg.interval)
req, err := http.NewRequest("POST", address, strings.NewReader(`{"message": "test"}`))
if err != nil {
t.Fatalf("error creating request: %v", err)
return false
}
// Set CloudEvents headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Ce-Id", "test-event-1")
req.Header.Set("Ce-Type", "test.event.type")
req.Header.Set("Ce-Source", "e2e-test")
req.Header.Set("Ce-Specversion", "1.0")
res, err := client.Do(req)
if err != nil {
elapsed := time.Since(startTime)
if elapsed > cfg.warnThreshold && time.Since(lastWarnTime) >= cfg.warnInterval {
t.Logf("unable to contact function (attempt %v, elapsed %v). %v", attemptCount, elapsed.Round(time.Second), err)
lastWarnTime = time.Now()
}
continue
}
defer res.Body.Close()
if res.StatusCode == 200 {
// Validate that the response is a proper CloudEvent
// CloudEvents can be in either binary or structured mode
// Read the response body first
body, err := io.ReadAll(res.Body)
if err != nil {
t.Logf("Error reading response body: %v", err)
continue
}
// Ensure body is valid JSON
var jsonBody any
if err := json.Unmarshal(body, &jsonBody); err != nil {
elapsed := time.Since(startTime)
if elapsed > cfg.warnThreshold && time.Since(lastWarnTime) >= cfg.warnInterval {
t.Logf("Function returned 200 but invalid JSON body (attempt %v, elapsed %v): %v", attemptCount, elapsed.Round(time.Second), err)
lastWarnTime = time.Now()
}
continue
}
// Check for CloudEvent response (either mode)
contentType := res.Header.Get("Content-Type")
ceSpecVersion := res.Header.Get("Ce-Specversion")
if contentType == "application/cloudevents+json" {
// Valid structured CloudEvent
t.Logf("Received valid structured CloudEvent response")
return true
} else if ceSpecVersion != "" {
// Valid binary CloudEvent
t.Logf("Received valid binary CloudEvent response")
return true
}
// Neither structured nor binary CloudEvent
elapsed := time.Since(startTime)
if elapsed > cfg.warnThreshold && time.Since(lastWarnTime) >= cfg.warnInterval {
t.Logf("Function returned 200 but response is not a CloudEvent (attempt %v, elapsed %v)", attemptCount, elapsed.Round(time.Second))
t.Logf("Content-Type: %s, Ce-Specversion: %s", contentType, ceSpecVersion)
lastWarnTime = time.Now()
}
continue
}
if res.StatusCode == 500 {
body, _ := io.ReadAll(res.Body)
t.Log("500 response received; canceling retries.")
t.Logf("Response: %s\n", body)
return false
}
elapsed := time.Since(startTime)
if elapsed > cfg.warnThreshold && time.Since(lastWarnTime) >= cfg.warnInterval {
t.Logf("Function responded with status %d (attempt %v, elapsed %v)", res.StatusCode, attemptCount, elapsed.Round(time.Second))
lastWarnTime = time.Now()
}
}
t.Logf("Could not validate CloudEvents function after %v (timeout %v)", time.Since(startTime).Round(time.Second), cfg.timeout)
return false
}
// waitFor an endpoint to return an OK response which includes the given
// content.
//
// If the Function returns a 500, it is considered a positive test failure
// by the implementation and retries are discontinued.
//
// Reasoning: This will be a false negative if port 8080 is being used
// by another process. This will fail because, if a service is already running
// on port 8080, Functions will automatically choose to run the next higher
// unused port. And this will be a false positive if there happens to be
// a service not already running on the port which happens to implement an
// echo. For example there is another process outside the E2Es which is
// currently executing a `func run`
// Note that until this is implemented, this temporary implementation also
// forces single-threaded test execution.
func waitForContent(t *testing.T, address, content, errMsg string, options ...waitOption) (ok bool) {
t.Helper()
cfg := waitCfg{
timeout: 2 * time.Minute,
interval: 5 * time.Second,
warnThreshold: 30 * time.Second,
warnInterval: 10 * time.Second,
}
for _, o := range options {
o(&cfg)
}
var (
mismatchLast = "" // cache the last content for squelching purposes.
mismatchReported = false // note that the given content was reported
)
startTime := time.Now()
lastWarnTime := time.Time{}
attemptCount := 0
for time.Since(startTime) < cfg.timeout {
attemptCount++
time.Sleep(cfg.interval)
res, err := http.Get(address)
if err != nil {
elapsed := time.Since(startTime)
if elapsed > cfg.warnThreshold && time.Since(lastWarnTime) >= cfg.warnInterval {
t.Logf("unable to contact function (attempt %v, elapsed %v). %v", attemptCount, elapsed.Round(time.Second), err)
lastWarnTime = time.Now()
}
continue
}
body, err := io.ReadAll(res.Body)
if err != nil {
t.Logf("error reading function response. %v", err)
continue
}
defer res.Body.Close()
if res.StatusCode == 500 {
t.Log("500 response received; canceling retries.")
t.Logf("Response: %s\n", body)
return false
}
if !strings.Contains(string(body), content) {
if string(body) != mismatchLast || !mismatchReported {
if errMsg == "" {
errMsg = "expected content not found"
}
t.Log("Response received, but " + errMsg)
t.Logf("Response: %s\n", body)
mismatchLast = string(body)
mismatchReported = true
}
continue
}
return true
}
t.Logf("Could not validate function after %v (timeout %v)", time.Since(startTime).Round(time.Second), cfg.timeout)
return
}
// isAbnormalExit checks an error returned from a cmd.Wait and returns true
// if the error is something other than a known exit 130 from a SIGINT.
func isAbnormalExit(t *testing.T, err error) bool {
t.Helper()
if err == nil {
return false // no error is not an abnormal error.
}
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode := exitErr.ExitCode()
// When interrupted, the exit will exit with an ExitError, but
// should be exit code 130 (the code for SIGINT)
if exitCode != 0 && exitCode != 130 {
t.Fatalf("Function exited code %v", exitErr.ExitCode())
return true
}
} else {
t.Fatalf("Function errored during execution. %v", err)
return true
}
return false
}
// setSecret creates or replaces a secret.
func setSecret(t *testing.T, name, ns string, data map[string][]byte) {
t.Helper()
ctx := t.Context()
config, err := k8s.GetClientConfig().ClientConfig()
if err != nil {
t.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
_ = clientset.CoreV1().Secrets(ns).Delete(ctx, name, metav1.DeleteOptions{})
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{Name: name},
Data: data,
}
_, err = clientset.CoreV1().Secrets(ns).Create(ctx, secret, metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
}
// setConfigMap creates or replaces a configMap
func setConfigMap(t *testing.T, name, ns string, data map[string]string) {
t.Helper()
ctx := t.Context()
config, err := k8s.GetClientConfig().ClientConfig()
if err != nil {
t.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
t.Fatal(err)
}
_ = clientset.CoreV1().ConfigMaps(ns).Delete(ctx, name, metav1.DeleteOptions{})
configMap := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{Name: name},
Data: data,
}
_, err = clientset.CoreV1().ConfigMaps(ns).Create(ctx, &configMap, metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
}
// containsInstance checks if the list includes the given instance.
func containsInstance(t *testing.T, list []fn.ListItem, name, namespace string) bool {
t.Helper()
for _, v := range list {
if v.Name == name && v.Namespace == namespace {
return true
}
}
return false
}
// clean up by deleting the named function (via defers)
func clean(t *testing.T, name, ns string) {
t.Helper()
// Log committed CPU before cleanup (this test's pods are still up), so the
// suite output carries a timeline of cluster load and we can see whether it
// creeps toward the node's allocatable and triggers "Insufficient cpu".
logClusterCPU(t)
if !Clean {
return
}
if err := newCmd(t, "delete", name, "--namespace", ns).Run(); err != nil {
t.Logf("Error deleting function. %v", err)
}
}
// logClusterCPU logs the cluster's committed CPU *requests* vs the node's
// allocatable — the figure the scheduler uses for its "Insufficient cpu"
// decision (not actual utilization). Best-effort; never fails a test.
func logClusterCPU(t *testing.T) {
t.Helper()
cmd := exec.Command("kubectl", "describe", "node")
cmd.Env = append(os.Environ(), "KUBECONFIG="+Kubeconfig)
out, err := cmd.CombinedOutput()
if err != nil {
return
}
inAlloc := false
for _, line := range strings.Split(string(out), "\n") {
if strings.Contains(line, "Allocated resources:") {
inAlloc = true
continue
}
if inAlloc && strings.HasPrefix(strings.TrimSpace(line), "cpu") {
t.Logf("[cluster-cpu] %s", strings.TrimSpace(line)) // e.g. "cpu 1500m (75%) 2 (100%)"
break
}
}
// Break the total down into pod count + the biggest CPU requesters, so we can
// see WHAT holds the CPU and whether pods/replicas accumulate across the run.
logTopPodsCPU(t)
}
// logTopPodsCPU logs the number of non-terminal pods (only those count toward
// scheduling) and the top CPU requesters (namespace/name -> millicores). This
// reveals which workloads make up the committed CPU and what grows over a run.
func logTopPodsCPU(t *testing.T) {
t.Helper()
cmd := exec.Command("kubectl", "get", "pods", "-A",
"--field-selector=status.phase!=Succeeded,status.phase!=Failed",
"-o", `jsonpath={range .items[*]}{.metadata.namespace}/{.metadata.name}{range .spec.containers[*]}{" "}{.resources.requests.cpu}{end}{"\n"}{end}`)
cmd.Env = append(os.Environ(), "KUBECONFIG="+Kubeconfig)
out, err := cmd.CombinedOutput()
if err != nil {
return
}
type pod struct {
name string
milli int
}
var pods []pod
total := 0
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
f := strings.Fields(line)
if len(f) == 0 {
continue
}
sum := 0
for _, v := range f[1:] {
sum += parseMilliCPU(v)
}
pods = append(pods, pod{f[0], sum})
total += sum
}
sort.Slice(pods, func(i, j int) bool { return pods[i].milli > pods[j].milli })
t.Logf("[cluster-cpu] %d non-terminal pods, %dm requested (sum)", len(pods), total)
for i, p := range pods {
if i >= 10 || p.milli == 0 {
break
}
t.Logf("[cluster-cpu] %4dm %s", p.milli, p.name)
}
}
// parseMilliCPU parses a Kubernetes CPU quantity ("100m", "1", "0.5") to millicores.
func parseMilliCPU(s string) int {