-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathrunner.go
More file actions
636 lines (562 loc) · 17.9 KB
/
runner.go
File metadata and controls
636 lines (562 loc) · 17.9 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
// Copyright 2021,2026 The kpt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runner
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/kptdev/kpt/internal/fnruntime"
)
// Runner runs an e2e test
type Runner struct {
pkgName string
testCase TestCase
cmd string
t *testing.T
initialCommit string
kptBin string
}
func getKptBin() (string, error) {
p, err := exec.Command("which", "kpt").CombinedOutput()
if err != nil {
return "", fmt.Errorf("cannot find command 'kpt' in $PATH: %w", err)
}
return strings.TrimSpace(string(p)), nil
}
const (
// If this env is set to "true", this e2e test framework will update the
// expected diff and results if they already exist. If will not change
// config.yaml.
updateExpectedEnv string = "KPT_E2E_UPDATE_EXPECTED"
expectedDir string = ".expected"
expectedResultsFile string = "results.yaml"
expectedDiffFile string = "diff.patch"
expectedConfigFile string = "config.yaml"
outDir string = "out"
setupScript string = "setup.sh"
teardownScript string = "teardown.sh"
execScript string = "exec.sh"
CommandFnEval string = "eval"
CommandFnRender string = "render"
allowWasmFlag string = "--allow-alpha-wasm"
)
// NewRunner returns a new runner for pkg
func NewRunner(t *testing.T, testCase TestCase, c string) (*Runner, error) {
info, err := os.Stat(testCase.Path)
if err != nil {
return nil, fmt.Errorf("cannot open path %s: %w", testCase.Path, err)
}
if !info.IsDir() {
return nil, fmt.Errorf("path %s is not a directory", testCase.Path)
}
kptBin, err := getKptBin()
if err != nil {
t.Logf("failed to find kpt binary: %v", err)
}
if kptBin != "" {
t.Logf("Using kpt binary: %s", kptBin)
}
return &Runner{
pkgName: filepath.Base(testCase.Path),
testCase: testCase,
cmd: c,
t: t,
kptBin: kptBin,
}, nil
}
// Run runs the test.
func (r *Runner) Run() error {
switch r.cmd {
case CommandFnEval:
return r.runFnEval()
case CommandFnRender:
return r.runFnRender()
default:
return fmt.Errorf("invalid command %s", r.cmd)
}
}
// runSetupScript runs the setup script if the test has it
func (r *Runner) runSetupScript(pkgPath string) error {
p, err := filepath.Abs(filepath.Join(r.testCase.Path, expectedDir, setupScript))
if err != nil {
return err
}
if _, err := os.Stat(p); os.IsNotExist(err) {
return nil
}
cmd := getCommand(pkgPath, "bash", []string{p})
r.t.Logf("running setup script: %q", cmd.String())
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to run setup script %q.\nOutput: %q\n: %w", p, string(output), err)
}
return nil
}
// runTearDownScript runs the teardown script if the test has it
func (r *Runner) runTearDownScript(pkgPath string) error {
p, err := filepath.Abs(filepath.Join(r.testCase.Path, expectedDir, teardownScript))
if err != nil {
return err
}
if _, err := os.Stat(p); os.IsNotExist(err) {
return nil
}
cmd := getCommand(pkgPath, "bash", []string{p})
r.t.Logf("running teardown script: %q", cmd.String())
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to run teardown script %q.\nOutput: %q\n: %w", p, string(output), err)
}
return nil
}
func (r *Runner) runFnEval() error {
// run function
for i := 0; i < r.testCase.Config.RunCount(); i++ {
r.t.Logf("Running test against package %s, iteration %d \n", r.pkgName, i+1)
tmpDir, err := os.MkdirTemp("", "krm-fn-e2e-*")
if err != nil {
return fmt.Errorf("failed to create temporary dir: %w", err)
}
pkgPath := filepath.Join(tmpDir, r.pkgName)
if r.testCase.Config.Debug {
fmt.Printf("Running test against package %s in dir %s \n", r.pkgName, pkgPath)
}
var resultsDir, destDir string
if r.IsFnResultExpected() {
resultsDir = filepath.Join(tmpDir, "results")
}
if r.IsOutOfPlace() {
destDir = filepath.Join(pkgPath, outDir)
}
// copy package to temp directory
err = copyDir(r.testCase.Path, pkgPath)
if err != nil {
return fmt.Errorf("failed to copy package: %w", err)
}
// init and commit package files
err = r.preparePackage(pkgPath)
if err != nil {
return fmt.Errorf("failed to prepare package: %w", err)
}
err = r.runSetupScript(pkgPath)
if err != nil {
return err
}
var cmd *exec.Cmd
execScriptPath, err := filepath.Abs(filepath.Join(r.testCase.Path, expectedDir, execScript))
if err != nil {
return err
}
if _, err := os.Stat(execScriptPath); err == nil {
cmd = getCommand(pkgPath, "bash", []string{execScriptPath})
} else {
kptArgs := []string{"fn", "eval", pkgPath}
if resultsDir != "" {
kptArgs = append(kptArgs, "--results-dir", resultsDir)
}
if destDir != "" {
kptArgs = append(kptArgs, "-o", destDir)
}
if r.testCase.Config.AllowWasm {
kptArgs = append(kptArgs, allowWasmFlag)
}
if r.testCase.Config.ImagePullPolicy != "" {
kptArgs = append(kptArgs, "--image-pull-policy", r.testCase.Config.ImagePullPolicy)
}
if r.testCase.Config.EvalConfig.Network {
kptArgs = append(kptArgs, "--network")
}
if r.testCase.Config.EvalConfig.Image != "" {
kptArgs = append(kptArgs, "--image", r.testCase.Config.EvalConfig.Image)
} else if !r.testCase.Config.EvalConfig.execUniquePath.Empty() {
kptArgs = append(kptArgs, "--exec", string(r.testCase.Config.EvalConfig.execUniquePath))
}
if r.testCase.Config.EvalConfig.Tag != "" {
kptArgs = append(kptArgs, "--tag", r.testCase.Config.EvalConfig.Tag)
}
if !r.testCase.Config.EvalConfig.fnConfigUniquePath.Empty() {
kptArgs = append(kptArgs, "--fn-config", string(r.testCase.Config.EvalConfig.fnConfigUniquePath))
}
if r.testCase.Config.EvalConfig.IncludeMetaResources {
kptArgs = append(kptArgs, "--include-meta-resources")
}
// args must be appended last
if len(r.testCase.Config.EvalConfig.Args) > 0 {
kptArgs = append(kptArgs, "--")
for k, v := range r.testCase.Config.EvalConfig.Args {
kptArgs = append(kptArgs, fmt.Sprintf("%s=%s", k, v))
}
}
cmd = getCommand("", r.kptBin, kptArgs)
}
r.t.Logf("running command: %v=%v %v", fnruntime.ContainerRuntimeEnv, os.Getenv(fnruntime.ContainerRuntimeEnv), cmd.String())
stdout, stderr, fnErr := runCommand(cmd)
if fnErr != nil {
r.t.Logf("kpt error, stdout: %s; stderr: %s", stdout, stderr)
}
// Update the diff file or results file if updateExpectedEnv is set.
if strings.ToLower(os.Getenv(updateExpectedEnv)) == "true" {
return r.updateExpected(pkgPath, resultsDir, filepath.Join(r.testCase.Path, expectedDir))
}
// compare results
err = r.compareResult(fnErr, stdout, sanitizeTimestamps(stderr), pkgPath, resultsDir)
if err != nil {
return err
}
// we passed result check, now we should break if the command error
// is expected
if fnErr != nil {
break
}
err = r.runTearDownScript(pkgPath)
if err != nil {
return err
}
// cleanup temp directory after iteration
if !r.testCase.Config.Debug {
os.RemoveAll(tmpDir)
}
}
return nil
}
func sanitizeTimestamps(stderr string) string {
// Output will have non-deterministic output timestamps. We will replace these to static message for
// stable comparison in tests.
var sanitized []string
for line := range strings.SplitSeq(stderr, "\n") {
// [PASS] \"ghcr.io/kptdev/krm-functions-catalog/set-namespace:latest\" in 2.0s
if strings.HasPrefix(line, "[PASS]") || strings.HasPrefix(line, "[FAIL]") {
tokens := strings.Fields(line)
if len(tokens) == 4 && tokens[2] == "in" {
tokens[3] = "0s"
line = strings.Join(tokens, " ")
}
}
sanitized = append(sanitized, line)
}
return strings.Join(sanitized, "\n")
}
// IsFnResultExpected determines if function results are expected for this testcase.
func (r *Runner) IsFnResultExpected() bool {
_, err := os.ReadFile(filepath.Join(r.testCase.Path, expectedDir, expectedResultsFile))
return err == nil
}
// IsOutOfPlace determines if command output is saved in a different directory (out-of-place).
func (r *Runner) IsOutOfPlace() bool {
_, err := os.ReadDir(filepath.Join(r.testCase.Path, outDir))
return err == nil
}
func (r *Runner) runFnRender() error {
// run function
for i := 0; i < r.testCase.Config.RunCount(); i++ {
r.t.Logf("Running test against package %s, iteration %d \n", r.pkgName, i+1)
tmpDir, err := os.MkdirTemp("", "kpt-pipeline-e2e-*")
if err != nil {
return fmt.Errorf("failed to create temporary dir: %w", err)
}
if r.testCase.Config.Debug {
fmt.Printf("Running test against package %s in dir %s \n", r.pkgName, tmpDir)
}
pkgPath := filepath.Join(tmpDir, r.pkgName)
// create dir to store untouched pkg to compare against
origPkgPath := filepath.Join(tmpDir, "original")
err = os.Mkdir(origPkgPath, 0755)
if err != nil {
return fmt.Errorf("failed to create original dir %s: %w", origPkgPath, err)
}
var resultsDir, destDir string
if r.IsFnResultExpected() {
resultsDir = filepath.Join(tmpDir, "results")
}
if r.IsOutOfPlace() {
destDir = filepath.Join(pkgPath, outDir)
}
// copy package to temp directory
err = copyDir(r.testCase.Path, pkgPath)
if err != nil {
return fmt.Errorf("failed to copy package: %w", err)
}
err = copyDir(r.testCase.Path, origPkgPath)
if err != nil {
return fmt.Errorf("failed to copy package: %w", err)
}
// init and commit package files
err = r.preparePackage(pkgPath)
if err != nil {
return fmt.Errorf("failed to prepare package: %w", err)
}
err = r.runSetupScript(pkgPath)
if err != nil {
return err
}
var cmd *exec.Cmd
execScriptPath, err := filepath.Abs(filepath.Join(r.testCase.Path, expectedDir, execScript))
if err != nil {
return err
}
if _, err := os.Stat(execScriptPath); err == nil {
cmd = getCommand(pkgPath, "bash", []string{execScriptPath})
} else {
kptArgs := []string{"fn", "render", pkgPath}
if resultsDir != "" {
kptArgs = append(kptArgs, "--results-dir", resultsDir)
}
if destDir != "" {
kptArgs = append(kptArgs, "-o", destDir)
}
if r.testCase.Config.ImagePullPolicy != "" {
kptArgs = append(kptArgs, "--image-pull-policy", r.testCase.Config.ImagePullPolicy)
}
if r.testCase.Config.AllowExec {
kptArgs = append(kptArgs, "--allow-exec")
}
if r.testCase.Config.AllowWasm {
kptArgs = append(kptArgs, allowWasmFlag)
}
if r.testCase.Config.DisableOutputTruncate {
kptArgs = append(kptArgs, "--truncate-output=false")
}
cmd = getCommand("", r.kptBin, kptArgs)
}
r.t.Logf("running command: %v=%v %v", fnruntime.ContainerRuntimeEnv, os.Getenv(fnruntime.ContainerRuntimeEnv), cmd.String())
stdout, stderr, fnErr := runCommand(cmd)
// Update the diff file or results file if updateExpectedEnv is set.
if strings.ToLower(os.Getenv(updateExpectedEnv)) == "true" {
return r.updateExpected(pkgPath, resultsDir, filepath.Join(r.testCase.Path, expectedDir))
}
if fnErr != nil {
r.t.Logf("kpt error, stdout: %s; stderr: %s", stdout, stderr)
}
// compare results
err = r.compareResult(fnErr, stdout, sanitizeTimestamps(stderr), pkgPath, resultsDir)
if err != nil {
return err
}
// we passed result check, now we should run teardown script and break
// if the command error is expected
err = r.runTearDownScript(pkgPath)
if err != nil {
return err
}
// cleanup temp directory after iteration
if !r.testCase.Config.Debug {
os.RemoveAll(tmpDir)
}
if fnErr != nil {
break
}
}
return nil
}
func (r *Runner) preparePackage(pkgPath string) error {
err := gitInit(pkgPath)
if err != nil {
return err
}
err = gitAddAll(pkgPath)
if err != nil {
return err
}
err = gitCommit(pkgPath, "first")
if err != nil {
return err
}
r.initialCommit, err = getCommitHash(pkgPath)
return err
}
func (r *Runner) compareResult(exitErr error, stdout string, inStderr string, tmpPkgPath, resultsPath string) error {
stderr := r.stripLines(inStderr, r.testCase.Config.StdErrStripLines)
expected, err := newExpected(tmpPkgPath)
if err != nil {
return err
}
// get exit code
exitCode := 0
if e, ok := exitErr.(*exec.ExitError); ok {
exitCode = e.ExitCode()
} else if exitErr != nil {
return fmt.Errorf("cannot get exit code, received error '%w'", exitErr)
}
if exitCode != r.testCase.Config.ExitCode {
return fmt.Errorf("actual exit code %d doesn't match expected %d", exitCode, r.testCase.Config.ExitCode)
}
err = r.compareOutput(stdout, stderr)
if err != nil {
return err
}
// compare results
actualResults, err := readActualResults(resultsPath)
if err != nil {
return fmt.Errorf("failed to read actual results: %w", err)
}
actualResults = r.stripLines(actualResults, r.testCase.Config.ActualStripLines)
diffOfResult, err := diffStrings(actualResults, expected.Results)
if err != nil {
return fmt.Errorf("error when run diff of results: %w: %s", err, diffOfResult)
}
if actualResults != expected.Results {
return fmt.Errorf("actual results doesn't match expected\nActual\n===\n%s\nDiff of Results\n===\n%s",
actualResults, diffOfResult)
}
// compare diff
actualDiff, err := readActualDiff(tmpPkgPath, r.initialCommit)
if err != nil {
return fmt.Errorf("failed to read actual diff: %w", err)
}
if actualDiff != expected.Diff {
diffOfDiff, err := diffStrings(actualDiff, expected.Diff)
if err != nil {
return fmt.Errorf("error when run diff of diff: %w: %s", err, diffOfDiff)
}
return fmt.Errorf("actual diff doesn't match expected\nActual\n===\n%s\nDiff of Diff\n===\n%s",
actualDiff, diffOfDiff)
}
return nil
}
// check stdout and stderr against expected
func (r *Runner) compareOutput(stdout string, stderr string) error {
expectedStderr := r.testCase.Config.StdErr
conditionedStderr := removeArmPlatformWarning(stderr)
if !strings.Contains(conditionedStderr, expectedStderr) {
r.t.Logf("stderr diff is %s", cmp.Diff(expectedStderr, conditionedStderr))
return fmt.Errorf("wanted stderr %q, got %q", expectedStderr, conditionedStderr)
}
stdErrRegEx := r.testCase.Config.StdErrRegEx
if stdErrRegEx != "" {
r, err := regexp.Compile(stdErrRegEx)
if err != nil {
return fmt.Errorf("unable to compile the regular expression %q: %w", stdErrRegEx, err)
}
if !r.MatchString(conditionedStderr) {
return fmt.Errorf("unable to match regular expression %q, got %v", stdErrRegEx, conditionedStderr)
}
}
expectedStdout := r.testCase.Config.StdOut
if !strings.Contains(stdout, expectedStdout) {
r.t.Logf("stdout diff is %s", cmp.Diff(expectedStdout, stdout))
return fmt.Errorf("wanted stdout %q, got %q", expectedStdout, stdout)
}
return nil
}
func (r *Runner) Skip() bool {
return r.testCase.Config.Skip
}
func readActualResults(resultsPath string) (string, error) {
// no results
if resultsPath == "" {
return "", nil
}
l, err := os.ReadDir(resultsPath)
if err != nil {
return "", fmt.Errorf("failed to get files in results dir: %w", err)
}
if len(l) > 1 {
return "", fmt.Errorf("unexpected results files number %d, should be 0 or 1", len(l))
}
if len(l) == 0 {
// no result file
return "", nil
}
resultsFile := l[0].Name()
actualResults, err := os.ReadFile(filepath.Join(resultsPath, resultsFile))
if err != nil {
return "", fmt.Errorf("failed to read actual results: %w", err)
}
return strings.TrimSpace(string(actualResults)), nil
}
func readActualDiff(path, origHash string) (string, error) {
err := gitAddAll(path)
if err != nil {
return "", err
}
err = gitCommit(path, "second")
if err != nil {
return "", err
}
// diff with first commit
actualDiff, err := gitDiff(path, origHash, "HEAD")
if err != nil {
return "", err
}
return strings.TrimSpace(actualDiff), nil
}
// expected contains the expected result for the function running
type expected struct {
Results string
Diff string
}
func newExpected(path string) (expected, error) {
e := expected{}
// get expected results
expectedResults, err := os.ReadFile(filepath.Join(path, expectedDir, expectedResultsFile))
switch {
case os.IsNotExist(err):
e.Results = ""
case err != nil:
return e, fmt.Errorf("failed to read expected results: %w", err)
default:
e.Results = strings.TrimSpace(string(expectedResults))
}
// get expected diff
expectedDiff, err := os.ReadFile(filepath.Join(path, expectedDir, expectedDiffFile))
switch {
case os.IsNotExist(err):
e.Diff = ""
case err != nil:
return e, fmt.Errorf("failed to read expected diff: %w", err)
default:
e.Diff = strings.TrimSpace(string(expectedDiff))
}
return e, nil
}
func (r *Runner) updateExpected(tmpPkgPath, resultsPath, sourceOfTruthPath string) error {
if resultsPath != "" {
// We update results directory only when a result file already exists.
l, err := os.ReadDir(resultsPath)
if err != nil {
return err
}
if len(l) > 0 {
actualResults, err := readActualResults(resultsPath)
if err != nil {
return err
}
if actualResults != "" {
if err := os.WriteFile(filepath.Join(sourceOfTruthPath, expectedResultsFile), []byte(actualResults+"\n"), 0666); err != nil {
return err
}
}
}
}
actualDiff, err := readActualDiff(tmpPkgPath, r.initialCommit)
if err != nil {
return err
}
if actualDiff != "" {
if err := os.WriteFile(filepath.Join(sourceOfTruthPath, expectedDiffFile), []byte(actualDiff+"\n"), 0666); err != nil {
return err
}
}
return nil
}
func (r *Runner) stripLines(string2Strip string, linesToStrip []string) string {
strippedString := string2Strip
for _, line2Strip := range linesToStrip {
strippedString = strings.ReplaceAll(strippedString, line2Strip+"\n", "")
}
return strippedString
}