-
Notifications
You must be signed in to change notification settings - Fork 301
/
client_test.go
360 lines (299 loc) · 10.9 KB
/
client_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
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
package k8s
import (
"context"
"fmt"
"testing"
"time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/kubernetes/scheme"
ktesting "k8s.io/client-go/testing"
"github.com/tilt-dev/tilt/internal/k8s/testyaml"
"github.com/tilt-dev/tilt/internal/testutils"
)
const upsertTimeout = time.Minute
func TestEmptyNamespace(t *testing.T) {
var emptyNamespace Namespace
assert.True(t, emptyNamespace.Empty())
assert.True(t, emptyNamespace == "")
assert.Equal(t, "default", emptyNamespace.String())
}
func TestNotEmptyNamespace(t *testing.T) {
var ns Namespace = "x"
assert.False(t, ns.Empty())
assert.False(t, ns == "")
assert.Equal(t, "x", ns.String())
}
func TestUpsert(t *testing.T) {
f := newClientTestFixture(t)
postgres, err := ParseYAMLFromString(testyaml.PostgresYAML)
assert.Nil(t, err)
_, err = f.k8sUpsert(f.ctx, postgres)
assert.Nil(t, err)
assert.Equal(t, 5, len(f.runner.calls))
assert.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, f.runner.calls[0].argv)
}
func TestUpsertMutableAndImmutable(t *testing.T) {
f := newClientTestFixture(t)
eDeploy := MustParseYAMLFromString(t, testyaml.SanchoYAML)[0]
eJob := MustParseYAMLFromString(t, testyaml.JobYAML)[0]
eNamespace := MustParseYAMLFromString(t, testyaml.MyNamespaceYAML)[0]
_, err := f.k8sUpsert(f.ctx, []K8sEntity{eDeploy, eJob, eNamespace})
if !assert.Nil(t, err) {
t.FailNow()
}
// two different calls: one for mutable entities (namespace, deployment),
// one for immutable (job)
require.Len(t, f.runner.calls, 3)
call0 := f.runner.calls[0]
call1 := f.runner.calls[1]
require.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, call0.argv, "expected args for call 0")
require.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, call1.argv, "expected args for call 1")
// compare entities instead of strings because str > entity > string gets weird
call0Entity := mustParseYAML(t, call0.stdin)[0]
call1Entity := mustParseYAML(t, call1.stdin)[0]
// `apply` should preserve input order of entities (we sort them further upstream)
require.Equal(t, eDeploy, call0Entity, "expect call 0 to have applied deployment first (preserve input order)")
require.Equal(t, eNamespace, call1Entity, "expect call 0 to have applied namespace second (preserve input order)")
call2 := f.runner.calls[2]
require.Equal(t, []string{"replace", "-o", "yaml", "--force", "-f", "-"}, call2.argv, "expected args for call 1")
call2Entities := mustParseYAML(t, call2.stdin)
require.Len(t, call2Entities, 1, "expect only one immutable entity applied")
require.Equal(t, eJob, call2Entities[0], "expect call 1 to have applied job")
}
func TestUpsertAnnotationTooLong(t *testing.T) {
f := newClientTestFixture(t)
postgres := MustParseYAMLFromString(t, testyaml.PostgresYAML)
f.setStderr(`The ConfigMap "postgres-config" is invalid: metadata.annotations: Too long: must have at most 262144 bytes`)
_, err := f.k8sUpsert(f.ctx, postgres)
if !assert.Nil(t, err) {
t.FailNow()
}
expectedArgs := [][]string{
{"apply", "-o", "yaml", "-f", "-"},
{"delete", "--ignore-not-found=true", "-f", "-"},
{"create", "-o", "yaml", "-f", "-"},
{"apply", "-o", "yaml", "-f", "-"},
{"apply", "-o", "yaml", "-f", "-"},
{"apply", "-o", "yaml", "-f", "-"},
{"apply", "-o", "yaml", "-f", "-"},
}
require.Len(t, f.runner.calls, len(expectedArgs))
for i, call := range f.runner.calls {
require.Equalf(t, expectedArgs[i], call.argv, "expected args for call %d", i)
observedEntities := mustParseYAML(t, call.stdin)
require.Len(t, observedEntities, 1, "expect 1 entity")
}
}
func TestUpsertStatefulsetForbidden(t *testing.T) {
f := newClientTestFixture(t)
postgres, err := ParseYAMLFromString(testyaml.PostgresYAML)
assert.Nil(t, err)
f.setStderr(`The StatefulSet "postgres" is invalid: spec: Forbidden: updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden.`)
_, err = f.k8sUpsert(f.ctx, postgres)
if assert.Nil(t, err) && assert.Equal(t, 7, len(f.runner.calls)) {
assert.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, f.runner.calls[0].argv)
assert.Equal(t, []string{"delete", "--ignore-not-found=true", "-f", "-"}, f.runner.calls[1].argv)
assert.Equal(t, []string{"create", "-o", "yaml", "-f", "-"}, f.runner.calls[2].argv)
assert.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, f.runner.calls[3].argv)
assert.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, f.runner.calls[4].argv)
assert.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, f.runner.calls[5].argv)
assert.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, f.runner.calls[6].argv)
}
}
func TestUpsertToTerminatingNamespaceForbidden(t *testing.T) {
f := newClientTestFixture(t)
postgres, err := ParseYAMLFromString(testyaml.SanchoYAML)
assert.Nil(t, err)
// Bad error parsing used to result in us treating this error as an immutable
// field error. Make sure we treat it as what it is and bail out of `kubectl apply`
// rather than trying to --force
errStr := `Error from server (Forbidden): error when creating "STDIN": deployments.apps "sancho" is forbidden: unable to create new content in namespace sancho-ns because it is being terminated`
f.setStderr(errStr)
_, err = f.k8sUpsert(f.ctx, postgres)
if assert.NotNil(t, err) {
assert.Contains(t, err.Error(), errStr)
}
if assert.Equal(t, 1, len(f.runner.calls)) {
assert.Equal(t, []string{"apply", "-o", "yaml", "-f", "-"}, f.runner.calls[0].argv)
}
}
func TestGetGroup(t *testing.T) {
for _, test := range []struct {
name string
apiVersion string
expectedGroup string
}{
{"normal", "apps/v1", "apps"},
// core types have an empty group
{"core", "/v1", ""},
// on some versions of k8s, deployment is buggy and doesn't have a version in its apiVersion
{"no version", "extensions", "extensions"},
{"alpha version", "apps/v1alpha1", "apps"},
{"beta version", "apps/v1beta1", "apps"},
// I've never seen this in the wild, but the docs say it's legal
{"alpha version, no second number", "apps/v1alpha", "apps"},
} {
t.Run(test.name, func(t *testing.T) {
obj := v1.ObjectReference{APIVersion: test.apiVersion}
assert.Equal(t, test.expectedGroup, getGroup(obj))
})
}
}
func TestUpsertTimeout(t *testing.T) {
f := newClientTestFixture(t)
postgres := MustParseYAMLFromString(t, testyaml.PostgresYAML)
f.runner.pauseForever = true
// we can't use a fake clock with context.Context, so we'll cheat a bit
// and just pass Upsert an already expired context.
var cancel context.CancelFunc
f.ctx, cancel = context.WithDeadline(f.ctx, time.Now().Add(-time.Hour))
defer cancel()
timeout := time.Second * 123
_, err := f.client.Upsert(f.ctx, postgres, timeout)
require.Error(t, err)
require.Equal(t, err.Error(), timeoutError(timeout).Error())
}
type call struct {
argv []string
stdin string
}
type fakeKubectlRunner struct {
pauseForever bool
stdout string
stderr string
err error
calls []call
}
func (f *fakeKubectlRunner) waitForDeadline(ctx context.Context) {
// hopefully 10 seconds is longer than any test is going to execute for
// this means that in case we run this without a higher level timeout, a broken test will still exit
select {
case <-ctx.Done():
f.err = errors.New("context was canceled")
case <-time.After(10 * time.Second):
f.err = errors.New("test set to have kubectl pause forever, but it never timed kubectl out!")
}
}
func (f *fakeKubectlRunner) execWithStdin(ctx context.Context, args []string, stdin string) (stdout string, stderr string, err error) {
f.calls = append(f.calls, call{argv: args, stdin: stdin})
defer func() {
f.stdout = ""
f.stderr = ""
f.err = nil
f.pauseForever = false
}()
if f.pauseForever {
f.waitForDeadline(ctx)
}
return f.stdout, f.stderr, f.err
}
func (f *fakeKubectlRunner) exec(ctx context.Context, args []string) (stdout string, stderr string, err error) {
f.calls = append(f.calls, call{argv: args})
defer func() {
f.stdout = ""
f.stderr = ""
f.err = nil
f.pauseForever = false
}()
if f.pauseForever {
f.waitForDeadline(ctx)
}
return f.stdout, f.stderr, f.err
}
var _ kubectlRunner = &fakeKubectlRunner{}
type clientTestFixture struct {
t *testing.T
ctx context.Context
client K8sClient
runner *fakeKubectlRunner
tracker ktesting.ObjectTracker
watchNotify chan watch.Interface
}
func newClientTestFixture(t *testing.T) *clientTestFixture {
ret := &clientTestFixture{}
ret.t = t
ctx, _, _ := testutils.CtxAndAnalyticsForTest()
ret.ctx = ctx
ret.runner = &fakeKubectlRunner{}
tracker := ktesting.NewObjectTracker(scheme.Scheme, scheme.Codecs.UniversalDecoder())
watchNotify := make(chan watch.Interface, 100)
ret.watchNotify = watchNotify
cs := &fake.Clientset{}
cs.AddReactor("*", "*", ktesting.ObjectReaction(tracker))
cs.AddWatchReactor("*", func(action ktesting.Action) (handled bool, ret watch.Interface, err error) {
gvr := action.GetResource()
ns := action.GetNamespace()
watch, err := tracker.Watch(gvr, ns)
if err != nil {
return false, nil, err
}
watchNotify <- watch
return true, watch, nil
})
ret.tracker = tracker
core := cs.CoreV1()
runtimeAsync := newRuntimeAsync(core)
registryAsync := newRegistryAsync(EnvUnknown, core, runtimeAsync)
ret.client = K8sClient{
env: EnvUnknown,
kubectlRunner: ret.runner,
core: core,
portForwardClient: &FakePortForwardClient{},
runtimeAsync: runtimeAsync,
registryAsync: registryAsync,
}
return ret
}
func (c clientTestFixture) k8sUpsert(ctx context.Context, entities []K8sEntity) ([]K8sEntity, error) {
return c.client.Upsert(ctx, entities, time.Minute)
}
func (c clientTestFixture) addObject(obj runtime.Object) {
err := c.tracker.Add(obj)
if err != nil {
c.t.Fatal(err)
}
}
func (c clientTestFixture) getPod(id PodID) *v1.Pod {
c.t.Helper()
pod, err := c.client.core.Pods(DefaultNamespace.String()).Get(c.ctx, id.String(), metav1.GetOptions{})
if err != nil {
c.t.Fatal(err)
}
return pod
}
func (c clientTestFixture) updatePod(pod *v1.Pod) {
gvks, _, err := scheme.Scheme.ObjectKinds(pod)
if err != nil {
c.t.Fatalf("updatePod: %v", err)
} else if len(gvks) == 0 {
c.t.Fatal("Could not parse pod into k8s schema")
}
for _, gvk := range gvks {
gvr, _ := meta.UnsafeGuessKindToResource(gvk)
err = c.tracker.Update(gvr, pod, NamespaceFromPod(pod).String())
if err != nil {
c.t.Fatal(err)
}
}
}
func (c clientTestFixture) setOutput(s string) {
c.runner.stdout = s
}
func (c clientTestFixture) setStderr(stderr string) {
c.runner.stderr = stderr
c.runner.err = fmt.Errorf("exit status 1")
}
func (c clientTestFixture) setError(err error) {
c.runner.err = err
}
func (c clientTestFixture) setKubectlPauseForever(d time.Duration) {
c.runner.pauseForever = true
}