-
Notifications
You must be signed in to change notification settings - Fork 212
/
main.go
220 lines (181 loc) · 6.27 KB
/
main.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
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
package tester
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"get.porter.sh/porter/pkg/portercontext"
"get.porter.sh/porter/pkg/storage/plugins/mongodb_docker"
"get.porter.sh/porter/tests"
"github.com/stretchr/testify/require"
"github.com/uwu-tools/magex/shx"
)
type Tester struct {
originalPwd string
// unique database name assigned to the test
dbName string
// TestContext is a porter context for the filesystem.
TestContext *portercontext.TestContext
// TestDir is the temp directory created for the test.
TestDir string
// PorterHomeDir is the temp PORTER_HOME directory for the test.
PorterHomeDir string
// RepoRoot is the root of the porter repository.
// Useful for constructing paths that won't break when the test is moved.
RepoRoot string
// T is the test helper.
T *testing.T
}
// NewTest sets up for a smoke test.
//
// Always defer Tester.Close(), even when an error is returned.
func NewTest(t *testing.T) (Tester, error) {
return NewTestWithConfig(t, "")
}
// NewTestWithConfig sets up for a smoke test using the specified
// Porter config file. The path should be either be absolute, or
// relative to the repository root.
//
// Always defer Tester.Close(), even when an error is returned.
func NewTestWithConfig(t *testing.T, configFilePath string) (Tester, error) {
var err error
pwd, _ := os.Getwd()
test := &Tester{T: t, originalPwd: pwd}
test.TestContext = portercontext.NewTestContext(t)
test.TestContext.UseFilesystem()
test.RepoRoot = test.TestContext.FindRepoRoot()
test.TestDir, err = os.MkdirTemp("", "porter-test")
if err != nil {
return *test, fmt.Errorf("could not create temp test directory: %w", err)
}
test.dbName = tests.GenerateDatabaseName(t.Name())
err = test.createPorterHome(configFilePath)
if err != nil {
return *test, err
}
os.Setenv("PORTER_HOME", test.PorterHomeDir)
os.Setenv("PATH", test.PorterHomeDir+string(os.PathListSeparator)+os.Getenv("PATH"))
return *test, test.startMongo(context.Background())
}
// CurrentNamespace configured in Porter's config file
func (t Tester) CurrentNamespace() string {
return "dev"
}
func (t Tester) startMongo(ctx context.Context) error {
conn, err := mongodb_docker.EnsureMongoIsRunning(ctx,
t.TestContext.Context,
"porter-smoke-test-mongodb-plugin",
"27017",
"",
t.dbName,
10,
)
if err != nil {
return err
}
defer conn.Close()
// Start with a fresh database
err = conn.RemoveDatabase(ctx)
return err
}
// Run a porter command and fail the test if the command returns an error.
func (t Tester) RequirePorter(args ...string) (stdout string, combinedoutput string) {
t.T.Helper()
stdout, combinedoutput, err := t.RunPorter(args...)
if err != nil {
t.T.Logf("failed to run porter %s", strings.Join(args, " "))
t.T.Log(combinedoutput)
}
require.NoError(t.T, err)
return stdout, combinedoutput
}
// RunPorter executes a porter command returning stderr when it fails.
func (t Tester) RunPorter(args ...string) (stdout string, combinedoutput string, err error) {
t.T.Helper()
return t.RunPorterWith(func(cmd *shx.PreparedCommand) {
cmd.Args(args...)
})
}
// RunPorterWith works like RunPorter, but you can customize the command before it's run.
func (t Tester) RunPorterWith(opts ...func(*shx.PreparedCommand)) (stdout string, combinedoutput string, err error) {
t.T.Helper()
cmd := t.buildPorterCommand(opts...)
// Copy stderr to stdout so we can return the "full" output printed to the console
stdoutBuf := &bytes.Buffer{}
stderrBuf := &bytes.Buffer{}
output := &bytes.Buffer{}
cmd.Stdout(io.MultiWriter(stdoutBuf, output)).Stderr(io.MultiWriter(stderrBuf, output))
t.T.Log(cmd.String())
ran, _, err := cmd.Exec()
if err != nil {
if ran {
err = fmt.Errorf("%s: %w", stderrBuf.String(), err)
}
return stdoutBuf.String(), output.String(), err
}
return stdoutBuf.String(), output.String(), nil
}
// Build a porter command, ready to be executed or further customized.
func (t Tester) buildPorterCommand(opts ...func(*shx.PreparedCommand)) shx.PreparedCommand {
debugCmdPrefix := os.Getenv("PORTER_RUN_IN_DEBUGGER")
configureCommand := func(cmd shx.PreparedCommand) {
cmd.Env("PORTER_HOME="+t.PorterHomeDir, "PORTER_TEST_DB_NAME="+t.dbName, "PORTER_VERBOSITY=debug")
for _, opt := range opts {
opt(&cmd)
}
}
cmd := shx.Command("porter")
configureCommand(cmd)
prettyCmd := cmd.String()
if debugCmdPrefix != "" && strings.HasPrefix(prettyCmd, debugCmdPrefix) {
port := os.Getenv("PORTER_DEBUGGER_PORT")
if port == "" {
port = "55942"
}
porterPath := filepath.Join(t.RepoRoot, "bin/porter")
cmd = shx.Command("dlv", "exec", porterPath, "--listen=:"+port, "--headless=true", "--api-version=2", "--accept-multiclient", "--")
configureCommand(cmd)
}
return cmd
}
func (t Tester) Close() {
t.T.Log("Removing temp test PORTER_HOME")
os.RemoveAll(t.PorterHomeDir)
t.T.Log("Removing temp test directory")
os.RemoveAll(t.TestDir)
// Reset the current directory for the next test
t.Chdir(t.originalPwd)
}
// Create a test PORTER_HOME directory with the optional config file.
// The config file path should be specified relative to the repository root
func (t *Tester) createPorterHome(configFilePath string) error {
if configFilePath == "" {
configFilePath = "tests/testdata/config/config.yaml"
}
if !filepath.IsAbs(configFilePath) {
configFilePath = filepath.Join(t.RepoRoot, configFilePath)
}
var err error
binDir := filepath.Join(t.RepoRoot, "bin")
t.PorterHomeDir, err = os.MkdirTemp("", "porter")
if err != nil {
return fmt.Errorf("could not create temp PORTER_HOME directory: %w", err)
}
require.NoError(t.T, shx.Copy(filepath.Join(binDir, "porter*"), t.PorterHomeDir),
"could not copy porter binaries into test PORTER_HOME")
require.NoError(t.T, shx.Copy(filepath.Join(binDir, "runtimes"), t.PorterHomeDir, shx.CopyRecursive),
"could not copy runtimes/ into test PORTER_HOME")
require.NoError(t.T, shx.Copy(filepath.Join(binDir, "mixins"), t.PorterHomeDir, shx.CopyRecursive),
"could not copy mixins/ into test PORTER_HOME")
require.NoError(t.T, shx.Copy(configFilePath, filepath.Join(t.PorterHomeDir, "config"+filepath.Ext(configFilePath))),
"error copying config file to PORTER_HOME")
return nil
}
func (t Tester) Chdir(dir string) {
t.TestContext.Chdir(dir)
require.NoError(t.T, os.Chdir(dir))
}