-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathgotest.go
More file actions
562 lines (500 loc) · 19 KB
/
Copy pathgotest.go
File metadata and controls
562 lines (500 loc) · 19 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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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 mage
import (
"context"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"slices"
"strings"
"time"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"golang.org/x/sys/execabs"
"github.com/elastic/beats/v7/dev-tools/mage/gotool"
"github.com/elastic/beats/v7/dev-tools/testbin"
)
// GoTestArgs are the arguments used for the "go*Test" targets and they define
// how "go test" is invoked. "go test" is always invoked with -v for verbose.
type GoTestArgs struct {
TestName string // Test name used in logging.
Race bool // Enable race detector.
Tags []string // Build tags to enable.
ExtraFlags []string // Extra flags to pass to 'go test'.
Packages []string // Packages to test.
Env map[string]string // Env vars to add to the current env.
OutputFile string // File to write verbose test output to.
JUnitReportFile string // File to write a JUnit XML test report to.
CoverageProfileFile string // Test coverage profile file (enables -cover).
Dir string // The directory the test should run from
Output io.Writer // Write stderr and stdout to Output if set
Timeout string // Timeout for tests (-timeout flag)
}
// TestBinaryArgs are the arguments used when building binary for testing.
type TestBinaryArgs struct {
Name string // Name of the binary to build
InputFiles []string
ExtraFlags []string // Extra flags to pass to 'go test'.
}
func makeGoTestArgs(name string) GoTestArgs {
fileName := fmt.Sprintf("build/TEST-go-%s", strings.ReplaceAll(strings.ToLower(name), " ", "_"))
params := GoTestArgs{
TestName: name,
Race: RaceDetector,
Packages: []string{"./..."},
Env: fipsTestEnv(),
OutputFile: fileName + ".out",
JUnitReportFile: fileName + ".xml",
Tags: testTagsFromEnv(),
}
if TestCoverage {
params.CoverageProfileFile = fileName + ".cov"
}
return params
}
func makeGoTestArgsForPackage(name, pkg string) GoTestArgs {
fileName := fmt.Sprintf(
"build/TEST-go-%s-%s",
strings.ReplaceAll(strings.ToLower(name), " ", "_"),
strings.ReplaceAll(strings.ToLower(pkg), " ", "_"))
params := GoTestArgs{
TestName: fmt.Sprintf("%s-%s", name, pkg),
Race: RaceDetector,
Packages: []string{fmt.Sprintf("./module/%s", pkg)},
Env: fipsTestEnv(),
OutputFile: fileName + ".out",
JUnitReportFile: fileName + ".xml",
Tags: testTagsFromEnv(),
}
if TestCoverage {
params.CoverageProfileFile = fileName + ".cov"
}
return params
}
// fetchGoPackages retrieves all Go packages for a beats module. It uses
// "go list -tags integration" to obtain the list of packages.
// Example: for the "kafka" module inside "metricbeat/module", it'll return:
//
// [kafka kafka/broker kafka/consumer kafka/consumergroup kafka/partition kafka/producer]
func fetchGoPackages(module string) ([]string, error) {
//nolint:gosec // G204 can be ignored as we don't send any input
cmd := execabs.Command(
"go", "list", "-tags", "integration", fmt.Sprintf("./%s/...", module))
output, err := cmd.Output()
if err != nil {
return nil, err
}
rawPackages := strings.Split(strings.TrimSpace(string(output)), "\n")
var pkgs []string
for _, pkg := range rawPackages {
tmp := strings.Split(pkg, "/module/")
if len(tmp) != 2 {
continue
}
pkgs = append(pkgs, tmp[1])
}
return pkgs, nil
}
// testTagsFromEnv gets a list of comma-separated tags from the TEST_TAGS
// environment variables, e.g: TEST_TAGS=aws,azure.
// If the FIPS env var is set to true, the requirefips tag is injected.
func testTagsFromEnv() []string {
testTags := strings.Trim(os.Getenv("TEST_TAGS"), ", ")
var tags []string
if testTags != "" {
tags = strings.Split(testTags, ",")
}
if FIPSBuild {
tags = append(tags, "requirefips")
}
return tags
}
// fipsTestEnv returns the environment variables required to compile and run FIPS tests.
func fipsTestEnv() map[string]string {
env := make(map[string]string, len(FIPSConfig.Compile.Env))
if !FIPSBuild {
return env
}
for k, v := range FIPSConfig.Compile.Env {
env[k] = v
}
return env
}
// DefaultGoTestUnitArgs returns a default set of arguments for running
// all unit tests. We tag unit test files with '!integration'.
func DefaultGoTestUnitArgs() GoTestArgs { return makeGoTestArgs("Unit") }
// DefaultGoFIPSOnlyTestArgs returns a default set of arguments for running
// fips140=only unit tests.
func DefaultGoFIPSOnlyTestArgs() GoTestArgs {
args := makeGoTestArgs("Unit-FIPS-only")
// We also set GODEBUG=tlsmlkem=0 to disable the X25519MLKEM768 TLS key
// exchange mechanism; without this setting and with the GODEBUG=fips140=only
// setting, we get errors in tests like so:
// Failed to connect: crypto/ecdh: use of X25519 is not allowed in FIPS 140-only mode
// Note that we are only disabling this TLS key exchange mechanism in tests!
args.Env["GODEBUG"] = "fips140=only,tlsmlkem=0"
return args
}
// DefaultGoWindowsTestIntegrationArgs returns a default set of arguments for running
// windows integration tests. We tag integration test files with 'integration'.
func DefaultGoWindowsTestIntegrationArgs() GoTestArgs {
args := makeGoTestArgs("Windows-Integration")
args.Tags = append(args.Tags, "win_integration")
args.ExtraFlags = append(args.ExtraFlags, "-count=1")
args.Packages = []string{"./tests/integration/windows"}
return args
}
// DefaultGoTestIntegrationArgs returns a default set of arguments for running
// all integration tests. We tag integration test files with 'integration'.
func DefaultGoTestIntegrationArgs(ctx context.Context) GoTestArgs {
args := makeGoTestArgs("Integration")
args.Tags = append(args.Tags, "integration")
cmdCtx, cmdCancel := context.WithTimeout(ctx, 5*time.Second)
defer cmdCancel()
synth := exec.CommandContext(cmdCtx, "npx", "@elastic/synthetics", "-h")
if synth.Run() == nil {
// Run an empty journey to ensure playwright can be loaded
// catches situations like missing playwright deps
cmd := exec.CommandContext(cmdCtx, "sh", "-c", "echo 'step(\"t\", () => { })' | elastic-synthetics --inline")
var out strings.Builder
cmd.Stdout = &out
cmd.Stderr = &out
err := cmd.Run()
if err != nil || cmd.ProcessState.ExitCode() != 0 {
fmt.Printf("synthetics is available, but not invokable, command exited with bad code: %s\n", out.String())
}
fmt.Println("npx @elastic/synthetics found, will run with synthetics tags")
os.Setenv("ELASTIC_SYNTHETICS_CAPABLE", "true")
args.Tags = append(args.Tags, "synthetics")
}
// Use the non-cachable -count=1 flag to disable test caching when running integration tests.
// There are reasons to re-run tests even if the code is unchanged (e.g. Dockerfile changes).
args.ExtraFlags = append(args.ExtraFlags, "-count=1")
args.ExtraFlags = append(args.ExtraFlags, "-timeout=15m")
return args
}
// DefaultGoTestIntegrationFromHostArgs returns a default set of arguments for running
// all integration tests from the host system (outside the docker network).
func DefaultGoTestIntegrationFromHostArgs(ctx context.Context) GoTestArgs {
args := DefaultGoTestIntegrationArgs(ctx)
args.Env = WithGoIntegTestHostEnv(args.Env)
return args
}
// FIPSOnlyGoTestIngrationFromHostArgs returns a default set of arguments for running
// all integration tests from the host system (outside the docker network) along
// with the GODEBUG=fips140=only arg set.
func FIPSOnlyGoTestIntegrationFromHostArgs(ctx context.Context) GoTestArgs {
args := DefaultGoTestIntegrationArgs(ctx)
args.Tags = append(args.Tags, "requirefips")
args.Env = WithGoIntegTestHostEnv(args.Env)
// We also set GODEBUG=tlsmlkem=0 to disable the X25519MLKEM768 TLS key
// exchange mechanism; without this setting and with the GODEBUG=fips140=only
// setting, we get errors in tests like so:
// Failed to connect: crypto/ecdh: use of X25519 is not allowed in FIPS 140-only mode
// Note that we are only disabling this TLS key exchange mechanism in tests!
args.Env["GODEBUG"] = "fips140=only,tlsmlkem=0"
return args
}
// GoTestIntegrationArgsForPackage returns a default set of arguments for running
// module integration tests. We tag integration test files with 'integration'.
func GoTestIntegrationArgsForPackage(pkg string) GoTestArgs {
args := makeGoTestArgsForPackage("Integration", pkg)
args.Tags = append(args.Tags, "integration")
// some test build docker images which download artifacts, and it can take a
// long time.
args.Timeout = "2h"
// add the requirefips tag when doing fips140 testing
if v, ok := os.LookupEnv("GODEBUG"); ok && strings.Contains(v, "fips140=only") {
args.Tags = append(args.Tags, "requirefips")
}
return args
}
// DefaultTestBinaryArgs returns the default arguments for building
// a binary for testing.
func DefaultTestBinaryArgs() TestBinaryArgs {
return TestBinaryArgs{
Name: BeatName,
}
}
// GoTestIntegrationForModule executes the Go integration tests for each Go
// package within a module sequentially.
// Currently, all test cases must be present under "./module" directory.
//
// Motivation: previous implementation executed all integration tests at once,
// causing high CPU load, high memory usage and resulted in timeouts.
//
// This method executes integration tests for a single module at a time.
// Use TEST_COVERAGE=true to enable code coverage profiling.
// Use RACE_DETECTOR=true to enable the race detector.
// Use MODULE=module to run only tests for `module`.
func GoTestIntegrationForModule(ctx context.Context) error {
modules := EnvOr("MODULE", "")
if modules == "" {
log.Printf("Warning: environment variable MODULE is empty: [%s]\n", modules)
}
moduleArr := strings.Split(modules, ",")
for _, module := range moduleArr {
err := goTestIntegrationForSingleModule(ctx, module)
if err != nil {
return err
}
}
return nil
}
// goTestIntegrationForSingleModule sequentially executes the tests every Go
// packages within a module.
func goTestIntegrationForSingleModule(ctx context.Context, module string) error {
modulesFileInfo, err := os.ReadDir("./module")
if err != nil {
return err
}
foundModule := false
failedModules := make([]string, 0, len(modulesFileInfo))
for _, fi := range modulesFileInfo {
// skip the ones that are not directories or with suffix @tmp, which are created by Jenkins build job
if !fi.IsDir() || strings.HasSuffix(fi.Name(), "@tmp") {
continue
}
if module != "" && module != fi.Name() {
continue
}
foundModule = true
// Set MODULE because only want that modules tests to run inside the testing environment.
env := map[string]string{"MODULE": fi.Name()}
passThroughEnvs(env, IntegrationTestEnvVars()...)
runners, err := NewIntegrationRunners(path.Join("./module", fi.Name()), env)
if err != nil {
return fmt.Errorf("test setup failed for module %s: %w", fi.Name(), err)
}
err = runners.Test("goIntegTest", func() error {
pkgs, err := fetchGoPackages("module/" + fi.Name())
if err != nil {
return fmt.Errorf("could not list packages for module %s: %w",
fi.Name(), err)
}
var errs []error
for _, pkg := range pkgs {
err := GoTest(ctx, GoTestIntegrationArgsForPackage(pkg))
if err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
})
if err != nil {
fmt.Printf("Error: failed to run integration tests for module %s:\n%v\n", fi.Name(), err)
// err will already be report to stdout, collect failed module to report at end
failedModules = append(failedModules, fi.Name())
}
}
if module != "" && !foundModule {
return fmt.Errorf("no module %s", module)
}
if len(failedModules) > 0 {
return fmt.Errorf("failed modules: %s", strings.Join(failedModules, ", "))
}
return nil
}
// InstallGoTestTools installs additional tools that are required to run unit and integration tests.
func InstallGoTestTools() error {
return gotool.Install(
gotool.Install.Package("gotest.tools/gotestsum"),
)
}
// GoTest invokes "go test" and reports the results to stdout. It returns an
// error if there was any failure executing the tests or if there were any
// test failures.
func GoTest(ctx context.Context, params GoTestArgs) error {
mg.Deps(InstallGoTestTools)
fmt.Println(">> go test:", params.TestName, "Testing")
// We use gotestsum to drive the tests and produce a junit report.
// The tool runs `go test -json` in order to produce a structured log which makes it easier
// to parse the actual test output.
// Of OutputFile is given the original JSON file will be written as well.
//
// The runner needs to set CLI flags for gotestsum and for "go test". We track the different
// CLI flags in the gotestsumArgs and testArgs variables, such that we can finally produce command like:
// $ gotestsum <gotestsum args> -- <go test args>
//
// The additional arguments given via GoTestArgs are applied to `go test` only. Callers can not
// modify any of the gotestsum arguments.
gotestsumArgs := []string{"--no-color"}
if mg.Verbose() {
gotestsumArgs = append(gotestsumArgs, "-f", "standard-verbose")
} else {
gotestsumArgs = append(gotestsumArgs, "-f", "standard-quiet")
}
if params.JUnitReportFile != "" {
CreateDir(params.JUnitReportFile)
gotestsumArgs = append(gotestsumArgs, "--junitfile", params.JUnitReportFile)
}
if params.OutputFile != "" {
CreateDir(params.OutputFile)
gotestsumArgs = append(gotestsumArgs, "--jsonfile", params.OutputFile+".json")
}
var testArgs []string
if params.Race {
// Enable the race detector for supported platforms.
// This is an intersection of the supported platforms for Beats and Go.
//
// See https://go.dev/doc/articles/race_detector#Requirements.
devOS := os.Getenv("DEV_OS")
devArch := os.Getenv("DEV_ARCH")
raceAmd64 := devArch == "amd64"
raceArm64 := devArch == "arm64" &&
slices.Contains([]string{"linux", "darwin"}, devOS)
if raceAmd64 || raceArm64 {
testArgs = append(testArgs, "-race")
} else {
//nolint:gosec // G706: DEV_OS/DEV_ARCH are trusted build-time env vars, not untrusted input
log.Printf("Warning: skipping -race flag for unsupported platform %s/%s\n", devOS, devArch)
}
}
if len(params.Tags) > 0 {
params := strings.Join(params.Tags, ",")
if params != "" {
testArgs = append(testArgs, "-tags="+params)
}
}
if params.CoverageProfileFile != "" {
params.CoverageProfileFile = createDir(filepath.Clean(params.CoverageProfileFile))
testArgs = append(testArgs,
"-covermode=atomic",
"-coverprofile="+params.CoverageProfileFile,
)
}
if params.Timeout != "" {
testArgs = append(testArgs, "-timeout="+params.Timeout)
}
testArgs = append(testArgs, params.ExtraFlags...)
testArgs = append(testArgs, params.Packages...)
args := append(gotestsumArgs, append([]string{"--"}, testArgs...)...)
goTest := makeCommand(ctx, params.Env, "gotestsum", args...)
// Set execution directory
if params.Dir != "" {
goTest.Dir = params.Dir
}
// Wire up the outputs.
var outputs []io.Writer
if params.Output != nil {
outputs = append(outputs, params.Output)
}
if params.OutputFile != "" {
fileOutput, err := os.Create(CreateDir(params.OutputFile))
if err != nil {
return fmt.Errorf("failed to create go test output file: %w", err)
}
defer fileOutput.Close()
outputs = append(outputs, fileOutput)
}
output := io.MultiWriter(outputs...)
if params.Output == nil {
goTest.Stdout = io.MultiWriter(output, os.Stdout)
goTest.Stderr = io.MultiWriter(output, os.Stderr)
} else {
goTest.Stdout = output
goTest.Stderr = output
}
err := goTest.Run()
var goTestErr *exec.ExitError
if err != nil {
// Command ran.
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return fmt.Errorf("failed to execute go: %w", err)
}
// Command ran but failed. Process the output.
goTestErr = exitErr
}
if goTestErr != nil {
// No packages were tested. Probably the code didn't compile.
return fmt.Errorf("go test returned a non-zero value: %w", goTestErr)
}
// Generate a HTML code coverage report.
var htmlCoverReport string
if params.CoverageProfileFile != "" {
htmlCoverReport = strings.TrimSuffix(params.CoverageProfileFile,
filepath.Ext(params.CoverageProfileFile)) + ".html"
coverToHTML := sh.RunCmd("go", "tool", "cover",
"-html="+params.CoverageProfileFile,
"-o", htmlCoverReport)
if err := coverToHTML(); err != nil {
return fmt.Errorf("failed to write HTML code coverage report: %w", err)
}
}
// Return an error indicating that testing failed.
if goTestErr != nil {
fmt.Println(">> go test:", params.TestName, "Test Failed")
return fmt.Errorf("go test returned a non-zero value: %w", goTestErr)
}
fmt.Println(">> go test:", params.TestName, "Test Passed")
return nil
}
func makeCommand(ctx context.Context, env map[string]string, cmd string, args ...string) *exec.Cmd {
c := exec.CommandContext(ctx, cmd, args...)
c.Env = os.Environ()
for k, v := range env {
c.Env = append(c.Env, k+"="+v)
}
c.Stdout = io.Discard
if mg.Verbose() {
c.Stdout = os.Stdout
}
c.Stderr = os.Stderr
c.Stdin = os.Stdin
log.Println("exec:", cmd, strings.Join(args, " "))
fmt.Println("exec:", cmd, strings.Join(args, " "))
return c
}
// BuildSystemTestBinary runs BuildSystemTestGoBinary with default values.
func BuildSystemTestBinary() error {
return BuildSystemTestGoBinary(DefaultTestBinaryArgs())
}
// BuildSystemTestGoBinary build a binary for testing that is instrumented for
// testing and measuring code coverage. The binary is only instrumented for
// coverage when TEST_COVERAGE=true (default is false).
func BuildSystemTestGoBinary(binArgs TestBinaryArgs) error {
_, err := testbin.Build(binArgs.Name, ".",
testbin.WithExtraFlags(binArgs.ExtraFlags...),
testbin.WithInputFiles(binArgs.InputFiles...),
)
return err
}
func DefaultECHTestArgs() GoTestArgs {
args := makeGoTestArgs("ECH")
args.Tags = append(args.Tags, "ech", "integration")
args.Dir = "tests/ech"
// attempt to use absolute paths for filenames
path, err := os.Getwd()
if err != nil {
log.Printf("Unable to get working dir, using value: .")
path = "."
}
fileName := path + "/build/TEST-go-ech"
args.OutputFile = fileName + ".out"
args.JUnitReportFile = fileName + ".xml"
if TestCoverage {
args.CoverageProfileFile = fileName + ".cov"
}
return args
}