-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathtest.go
175 lines (151 loc) · 4.2 KB
/
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
package compiler
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"golang.org/x/exp/slices"
"encr.dev/pkg/errinsrc/srcerrors"
)
type TestConfig struct {
// Env sets environment variables for "go test".
Env []string
// Args sets extra arguments for "go test".
Args []string
// Stdout and Stderr are where to redirect "go test" output.
Stdout, Stderr io.Writer
}
// Test tests the application.
func Test(ctx context.Context, appRoot string, cfg *Config) error {
if err := cfg.Validate(); err != nil {
return err
} else if appRoot, err = filepath.Abs(appRoot); err != nil {
return err
}
b := &builder{
cfg: cfg,
appRoot: appRoot,
log: cfg.Log,
forTesting: true,
configs: make(map[string]string),
}
return b.Test(ctx)
}
func (b *builder) Test(ctx context.Context) (err error) {
defer func() {
if e := recover(); e != nil {
if b, ok := e.(bailout); ok {
err = b.err
} else {
err = srcerrors.UnhandledPanic(e)
}
}
}()
b.workdir, err = os.MkdirTemp("", "encore-test")
if err != nil {
return err
}
defer os.RemoveAll(b.workdir)
for _, fn := range []func() error{
b.parseApp,
b.pickupConfigFiles,
b.checkApp, // we need to validate & compute the config
b.writeModFile,
b.writeSumFile,
b.writePackages,
b.writeHandlers,
b.writeTestMains,
b.writeConfigUnmarshallers,
b.writeEtypePkg,
} {
if err := fn(); err != nil {
return err
}
}
return b.runTests(ctx)
}
// EncoreEnvironmentalVariablesToEmbed tells us if we need to embed the environmental variables into the built
// binary for testing.
//
// This is needed because GoLand first builds the test binary as one phase, and then secondary executes that built binary
func (b *builder) EncoreEnvironmentalVariablesToEmbed() []string {
if b.forTesting == false || b.cfg.Test == nil {
return nil
}
// If -c is passed to the go test, it means compile the test binary to pkg.test but do not run it
if !slices.Contains(b.cfg.Test.Args, "-c") {
return nil
}
rtn := make([]string, 0)
for _, env := range b.cfg.Test.Env {
if strings.HasPrefix(env, "ENCORE_") {
rtn = append(rtn, env)
}
}
// Embed any computed configs
for serviceName, cfgString := range b.configs {
rtn = append(rtn, "ENCORE_CFG_"+strings.ToUpper(serviceName)+"="+base64.RawURLEncoding.EncodeToString([]byte(cfgString)))
}
return rtn
}
func (b *builder) writeTestMains() error {
defer b.trace("write test mains")()
for _, pkg := range b.res.App.Packages {
if err := b.generateTestMain(pkg); err != nil {
return err
}
}
return nil
}
// runTests runs "go test".
func (b *builder) runTests(ctx context.Context) error {
defer b.trace("run tests")()
overlayData, _ := json.Marshal(map[string]interface{}{"Replace": b.overlay})
overlayPath := filepath.Join(b.workdir, "overlay.json")
if err := os.WriteFile(overlayPath, overlayData, 0644); err != nil {
return err
}
tags := append([]string{"encore", "encore_internal", "encore_app"}, b.cfg.BuildTags...)
args := []string{
"test",
"-tags=" + strings.Join(tags, ","),
"-overlay=" + overlayPath,
"-modfile=" + filepath.Join(b.workdir, "go.mod"),
"-mod=mod",
"-vet=off",
}
if b.cfg.StaticLink {
var ldflags string
// Enable external linking if we use cgo.
if b.cfg.CgoEnabled {
ldflags = "-linkmode external "
}
ldflags += `-extldflags "-static"`
args = append(args, "-ldflags", ldflags)
}
args = append(args, b.cfg.Test.Args...)
cmd := exec.CommandContext(ctx, filepath.Join(b.cfg.EncoreGoRoot, "bin", "go"+b.exe()), args...)
// Copy the env before we add additional env vars
// to avoid accidentally sharing the same backing array.
env := make([]string, len(b.cfg.Test.Env))
copy(env, b.cfg.Test.Env)
env = append(env,
"GO111MODULE=on",
"GOROOT="+b.cfg.EncoreGoRoot,
)
if !b.cfg.CgoEnabled {
env = append(env, "CGO_ENABLED=0")
}
for serviceName, cfgString := range b.configs {
env = append(env, "ENCORE_CFG_"+strings.ToUpper(serviceName)+"="+base64.RawURLEncoding.EncodeToString([]byte(cfgString)))
}
cmd.Env = append(os.Environ(), env...)
cmd.Dir = filepath.Join(b.appRoot, b.cfg.WorkingDir)
cmd.Stdout = b.cfg.Test.Stdout
cmd.Stderr = b.cfg.Test.Stderr
return cmd.Run()
}