Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ignite
GitHub Repository: ignite/cli
Path: blob/main/integration/exec.go
1007 views
1
package envtest
2
3
import (
4
"bytes"
5
"context"
6
"fmt"
7
"io"
8
"os"
9
"time"
10
11
"github.com/stretchr/testify/assert"
12
13
"github.com/ignite/cli/v29/ignite/pkg/cmdrunner"
14
"github.com/ignite/cli/v29/ignite/pkg/cmdrunner/step"
15
"github.com/ignite/cli/v29/ignite/pkg/errors"
16
)
17
18
type execOptions struct {
19
ctx context.Context
20
shouldErr, shouldRetry bool
21
stdout, stderr io.Writer
22
}
23
24
type ExecOption func(*execOptions)
25
26
// ExecShouldError sets the expectations of a command's execution to end with a failure.
27
func ExecShouldError() ExecOption {
28
return func(o *execOptions) {
29
o.shouldErr = true
30
}
31
}
32
33
// ExecCtx sets cancelation context for the execution.
34
func ExecCtx(ctx context.Context) ExecOption {
35
return func(o *execOptions) {
36
o.ctx = ctx
37
}
38
}
39
40
// ExecStdout captures stdout of an execution.
41
func ExecStdout(w io.Writer) ExecOption {
42
return func(o *execOptions) {
43
o.stdout = w
44
}
45
}
46
47
// ExecStderr captures stderr of an execution.
48
func ExecStderr(w io.Writer) ExecOption {
49
return func(o *execOptions) {
50
o.stderr = w
51
}
52
}
53
54
// ExecRetry retries command until it is successful before context is canceled.
55
func ExecRetry() ExecOption {
56
return func(o *execOptions) {
57
o.shouldRetry = true
58
}
59
}
60
61
// Exec executes a command step with options where msg describes the expectation from the test.
62
// unless calling with Must(), Exec() will not exit test runtime on failure.
63
func (e Env) Exec(msg string, steps step.Steps, options ...ExecOption) (ok bool) {
64
opts := &execOptions{
65
ctx: e.ctx,
66
stdout: io.Discard,
67
stderr: io.Discard,
68
}
69
for _, o := range options {
70
o(opts)
71
}
72
var (
73
stdout = &bytes.Buffer{}
74
stderr = &bytes.Buffer{}
75
)
76
copts := []cmdrunner.Option{
77
cmdrunner.DefaultStdout(io.MultiWriter(stdout, opts.stdout)),
78
cmdrunner.DefaultStderr(io.MultiWriter(stderr, opts.stderr)),
79
}
80
if HasTestVerboseFlag() {
81
fmt.Printf("Executing %d step(s) for %q\n", len(steps), msg)
82
copts = append(copts, cmdrunner.EnableDebug())
83
}
84
if IsCI {
85
copts = append(copts, cmdrunner.EndSignal(os.Kill))
86
}
87
err := cmdrunner.
88
New(copts...).
89
Run(opts.ctx, steps...)
90
if errors.Is(err, context.Canceled) {
91
err = nil
92
}
93
if err != nil {
94
fmt.Fprintln(os.Stderr, err)
95
if opts.shouldRetry && opts.ctx.Err() == nil {
96
time.Sleep(time.Second)
97
return e.Exec(msg, steps, options...)
98
}
99
}
100
101
if err != nil {
102
msg = fmt.Sprintf("%s\n\nLogs:\n\n%s\n\nError Logs:\n\n%s\n",
103
msg,
104
stdout.String(),
105
stderr.String())
106
}
107
if opts.shouldErr {
108
return assert.Error(e.t, err, msg)
109
}
110
return assert.NoError(e.t, err, msg)
111
}
112
113