-
Notifications
You must be signed in to change notification settings - Fork 290
/
test_utils.go
266 lines (226 loc) · 7.87 KB
/
test_utils.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
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
package build
import (
"archive/tar"
"context"
"fmt"
"log"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/stretchr/testify/assert"
wmcontainer "github.com/windmilleng/tilt/internal/container"
"github.com/windmilleng/tilt/internal/docker"
"github.com/windmilleng/tilt/internal/dockerfile"
"github.com/windmilleng/tilt/internal/k8s"
"github.com/windmilleng/tilt/internal/minikube"
"github.com/windmilleng/tilt/internal/testutils"
"github.com/windmilleng/tilt/internal/testutils/bufsync"
"github.com/windmilleng/tilt/internal/testutils/tempdir"
"github.com/windmilleng/tilt/pkg/model"
)
type dockerBuildFixture struct {
*tempdir.TempDirFixture
t testing.TB
ctx context.Context
dCli *docker.Cli
fakeDocker *docker.FakeClient
b *dockerImageBuilder
registry *exec.Cmd
reaper ImageReaper
containerIDs []wmcontainer.ID
ps *PipelineState
}
type fakeClock struct {
now time.Time
}
func (c fakeClock) Now() time.Time { return c.now }
func newDockerBuildFixture(t testing.TB) *dockerBuildFixture {
ctx, _, _ := testutils.CtxAndAnalyticsForTest()
env := k8s.EnvGKE
dEnv, err := docker.ProvideClusterEnv(ctx, env, wmcontainer.RuntimeDocker, minikube.FakeClient{})
if err != nil {
t.Fatal(err)
}
dCli := docker.NewDockerClient(ctx, docker.Env(dEnv))
_, ok := dCli.(*docker.Cli)
// If it wasn't an actual Docker client, it's an exploding client
if !ok {
cli := dCli.(docker.Client)
// Call the simplest interface function that returns the error which originally occurred in NewDockerClient()
t.Fatal(cli.CheckConnected())
}
ps := NewPipelineState(ctx, 3, fakeClock{})
labels := dockerfile.Labels(map[dockerfile.Label]dockerfile.LabelValue{
TestImage: "1",
})
return &dockerBuildFixture{
TempDirFixture: tempdir.NewTempDirFixture(t),
t: t,
ctx: ctx,
dCli: dCli.(*docker.Cli),
b: NewDockerImageBuilder(dCli, labels),
reaper: NewImageReaper(dCli),
ps: ps,
}
}
func newFakeDockerBuildFixture(t testing.TB) *dockerBuildFixture {
ctx, _, _ := testutils.CtxAndAnalyticsForTest()
dCli := docker.NewFakeClient()
labels := dockerfile.Labels(map[dockerfile.Label]dockerfile.LabelValue{
TestImage: "1",
})
ps := NewPipelineState(ctx, 3, realClock{})
return &dockerBuildFixture{
TempDirFixture: tempdir.NewTempDirFixture(t),
t: t,
ctx: ctx,
fakeDocker: dCli,
b: NewDockerImageBuilder(dCli, labels),
reaper: NewImageReaper(dCli),
ps: ps,
}
}
func (f *dockerBuildFixture) teardown() {
for _, cID := range f.containerIDs {
// ignore failures
_ = f.dCli.ContainerRemove(f.ctx, string(cID), types.ContainerRemoveOptions{
Force: true,
})
}
// ignore failures
_ = f.reaper.RemoveTiltImages(f.ctx, time.Now(), true /*force*/, FilterByLabel(TestImage))
if f.registry != nil && f.registry.Process != nil {
go func() {
err := f.registry.Process.Kill()
if err != nil {
log.Printf("killing the registry failed: %v\n", err)
}
}()
// ignore the error. we expect it to be killed
_ = f.registry.Wait()
_ = exec.Command("docker", "kill", "tilt-registry").Run()
_ = exec.Command("docker", "rm", "tilt-registry").Run()
}
f.TempDirFixture.TearDown()
}
func (f *dockerBuildFixture) getNameFromTest() wmcontainer.RefSet {
x := fmt.Sprintf("windmill.build/%s", strings.ToLower(f.t.Name()))
sel := wmcontainer.MustParseSelector(x)
return wmcontainer.MustSimpleRefSet(sel)
}
func (f *dockerBuildFixture) startRegistry() {
stdout := bufsync.NewThreadSafeBuffer()
cmd := exec.Command("docker", "run", "--name", "tilt-registry", "-p", "5005:5000", "registry:2")
cmd.Stdout = stdout
cmd.Stderr = stdout
f.registry = cmd
err := cmd.Start()
if err != nil {
f.t.Fatal(err)
}
err = stdout.WaitUntilContains("listening on", 5*time.Second)
if err != nil {
f.t.Fatalf("Registry didn't start: %v", err)
}
}
type expectedFile = testutils.ExpectedFile
func (f *dockerBuildFixture) assertImageExists(ref reference.NamedTagged) {
_, _, err := f.dCli.ImageInspectWithRaw(f.ctx, ref.String())
if err != nil {
f.t.Errorf("Expected image %q to exist, got: %v", ref, err)
}
}
func (f *dockerBuildFixture) assertImageNotExists(ref reference.NamedTagged) {
_, _, err := f.dCli.ImageInspectWithRaw(f.ctx, ref.String())
if err == nil || !client.IsErrNotFound(err) {
f.t.Errorf("Expected image %q to fail with ErrNotFound, got: %v", ref, err)
}
}
func (f *dockerBuildFixture) assertImageHasLabels(ref reference.Named, expected map[string]string) {
inspect, _, err := f.dCli.ImageInspectWithRaw(f.ctx, ref.String())
if err != nil {
f.t.Fatalf("error inspecting image %s: %v", ref.String(), err)
}
if inspect.Config == nil {
f.t.Fatalf("'inspect' result for image %s has nil config", ref.String())
}
actual := inspect.Config.Labels
for k, expectV := range expected {
actualV, ok := actual[k]
if assert.True(f.t, ok, "key %q not found in actual labels: %v", k, actual) {
assert.Equal(f.t, expectV, actualV, "actual label (%s = %s) did not match expected (%s = %s)",
k, actualV, k, expectV)
}
}
}
func (f *dockerBuildFixture) assertFilesInImage(ref reference.NamedTagged, expectedFiles []expectedFile) {
cID := f.startContainer(f.ctx, containerConfigRunCmd(ref, model.Cmd{}))
f.assertFilesInContainer(f.ctx, cID, expectedFiles)
}
func (f *dockerBuildFixture) assertFilesInContainer(
ctx context.Context, cID wmcontainer.ID, expectedFiles []expectedFile) {
for _, expectedFile := range expectedFiles {
reader, _, err := f.dCli.CopyFromContainer(ctx, cID.String(), expectedFile.Path)
if expectedFile.Missing {
if err == nil {
f.t.Errorf("Expected path %q to not exist", expectedFile.Path)
} else if !strings.Contains(err.Error(), "No such container:path") {
f.t.Errorf("Expected path %q to not exist, but got a different error: %v", expectedFile.Path, err)
}
continue
}
if err != nil {
f.t.Fatal(err)
}
// When you copy a single file out of a container, you get
// back a tarball with 1 entry, the file basename.
adjustedFile := expectedFile
adjustedFile.Path = filepath.Base(adjustedFile.Path)
testutils.AssertFileInTar(f.t, tar.NewReader(reader), adjustedFile)
}
}
// startContainer starts a container from the given config
func (f *dockerBuildFixture) startContainer(ctx context.Context, config *container.Config) wmcontainer.ID {
resp, err := f.dCli.ContainerCreate(ctx, config, nil, nil, "")
if err != nil {
f.t.Fatalf("startContainer: %v", err)
}
cID := resp.ID
err = f.dCli.ContainerStart(ctx, cID, types.ContainerStartOptions{})
if err != nil {
f.t.Fatalf("startContainer: %v", err)
}
result := wmcontainer.ID(cID)
f.containerIDs = append(f.containerIDs, result)
return result
}
// Get a container config to run a container with a given command instead of
// the existing entrypoint. If cmd is nil, we run nothing.
func containerConfigRunCmd(imgRef reference.NamedTagged, cmd model.Cmd) *container.Config {
config := containerConfig(imgRef)
// In Docker, both the Entrypoint and the Cmd are used to determine what
// process the container runtime uses, where Entrypoint takes precedence over
// command. We set both here to ensure that we don't get weird results due
// to inheritance.
//
// If cmd is nil, we use a fake cmd that does nothing.
//
// https://github.com/opencontainers/image-spec/blob/master/config.md#properties
if cmd.Empty() {
config.Cmd = model.ToShellCmd("# NOTE(nick): a fake cmd").Argv
} else {
config.Cmd = cmd.Argv
}
config.Entrypoint = []string{}
return config
}
// Get a container config to run a container as-is.
func containerConfig(imgRef reference.NamedTagged) *container.Config {
return &container.Config{Image: imgRef.String()}
}