-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathhttp_test.go
More file actions
235 lines (202 loc) · 7.14 KB
/
http_test.go
File metadata and controls
235 lines (202 loc) · 7.14 KB
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
// Copyright 2021 - 2024 Crunchy Data Solutions, Inc.
//
// SPDX-License-Identifier: Apache-2.0
package upgradecheck
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/go-logr/logr/funcr"
"github.com/pkg/errors"
"gotest.tools/v3/assert"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/manager"
"github.com/percona/percona-postgresql-operator/v2/internal/feature"
"github.com/percona/percona-postgresql-operator/v2/internal/logging"
"github.com/percona/percona-postgresql-operator/v2/internal/testing/cmp"
)
func init() {
client = &MockClient{Timeout: 1}
// set backoff to two steps, 1 second apart for testing
backoff = wait.Backoff{
Duration: 1 * time.Second,
Factor: float64(1),
Steps: 2,
}
}
type MockClient struct {
Timeout time.Duration
}
var funcFoo func() (*http.Response, error)
// Do is the mock request that will return a mock success
func (m *MockClient) Do(req *http.Request) (*http.Response, error) {
return funcFoo()
}
func TestCheckForUpgrades(t *testing.T) {
fakeClient := setupFakeClientWithPGOScheme(t, true)
cfg := &rest.Config{}
ctx := logging.NewContext(context.Background(), logging.Discard())
gate := feature.NewGate()
assert.NilError(t, gate.SetFromMap(map[string]bool{
feature.TablespaceVolumes: true,
}))
ctx = feature.NewContext(ctx, gate)
// Pass *testing.T to allows the correct messages from the assert package
// in the event of certain failures.
checkData := func(t *testing.T, header string) {
data := clientUpgradeData{}
err := json.Unmarshal([]byte(header), &data)
assert.NilError(t, err)
assert.Assert(t, data.DeploymentID != "")
assert.Equal(t, data.PGOVersion, "4.7.3")
assert.Equal(t, data.RegistrationToken, "speakFriend")
assert.Equal(t, data.BridgeClustersTotal, 2)
assert.Equal(t, data.PGOClustersTotal, 2)
assert.Equal(t, data.FeatureGatesEnabled, "AutoCreateUserSchema=true,TablespaceVolumes=true")
}
t.Run("success", func(t *testing.T) {
// A successful call
funcFoo = func() (*http.Response, error) {
json := `{"pgo_versions":[{"tag":"v5.0.4"},{"tag":"v5.0.3"},{"tag":"v5.0.2"},{"tag":"v5.0.1"},{"tag":"v5.0.0"}]}`
return &http.Response{
Body: io.NopCloser(strings.NewReader(json)),
StatusCode: http.StatusOK,
}, nil
}
res, header, err := checkForUpgrades(ctx, "", "4.7.3", backoff,
fakeClient, cfg, false, "speakFriend")
assert.NilError(t, err)
assert.Equal(t, res, `{"pgo_versions":[{"tag":"v5.0.4"},{"tag":"v5.0.3"},{"tag":"v5.0.2"},{"tag":"v5.0.1"},{"tag":"v5.0.0"}]}`)
checkData(t, header)
})
t.Run("total failure, err sending", func(t *testing.T) {
var counter int
// A call returning errors
funcFoo = func() (*http.Response, error) {
counter++
return &http.Response{}, errors.New("whoops")
}
res, header, err := checkForUpgrades(ctx, "", "4.7.3", backoff,
fakeClient, cfg, false, "speakFriend")
// Two failed calls because of env var
assert.Equal(t, counter, 2)
assert.Equal(t, res, "")
assert.Equal(t, err.Error(), `whoops`)
checkData(t, header)
})
t.Run("total failure, bad StatusCode", func(t *testing.T) {
var counter int
// A call returning bad StatusCode
funcFoo = func() (*http.Response, error) {
counter++
return &http.Response{
Body: io.NopCloser(strings.NewReader("")),
StatusCode: http.StatusBadRequest,
}, nil
}
res, header, err := checkForUpgrades(ctx, "", "4.7.3", backoff,
fakeClient, cfg, false, "speakFriend")
assert.Equal(t, res, "")
// Two failed calls because of env var
assert.Equal(t, counter, 2)
assert.Equal(t, err.Error(), `received StatusCode 400`)
checkData(t, header)
})
t.Run("one failure, then success", func(t *testing.T) {
var counter int
// A call returning bad StatusCode the first time
// and a successful response the second time
funcFoo = func() (*http.Response, error) {
if counter < 1 {
counter++
return &http.Response{
Body: io.NopCloser(strings.NewReader("")),
StatusCode: http.StatusBadRequest,
}, nil
}
counter++
json := `{"pgo_versions":[{"tag":"v5.0.4"},{"tag":"v5.0.3"},{"tag":"v5.0.2"},{"tag":"v5.0.1"},{"tag":"v5.0.0"}]}`
return &http.Response{
Body: io.NopCloser(strings.NewReader(json)),
StatusCode: http.StatusOK,
}, nil
}
res, header, err := checkForUpgrades(ctx, "", "4.7.3", backoff,
fakeClient, cfg, false, "speakFriend")
assert.Equal(t, counter, 2)
assert.NilError(t, err)
assert.Equal(t, res, `{"pgo_versions":[{"tag":"v5.0.4"},{"tag":"v5.0.3"},{"tag":"v5.0.2"},{"tag":"v5.0.1"},{"tag":"v5.0.0"}]}`)
checkData(t, header)
})
}
// TODO(benjaminjb): Replace `fake` with envtest
func TestCheckForUpgradesScheduler(t *testing.T) {
fakeClient := setupFakeClientWithPGOScheme(t, false)
_, server := setupVersionServer(t, true)
defer server.Close()
cfg := &rest.Config{Host: server.URL}
t.Run("panic from checkForUpgrades doesn't bubble up", func(t *testing.T) {
ctx := context.Background()
// capture logs
var calls []string
ctx = logging.NewContext(ctx, funcr.NewJSON(func(object string) {
calls = append(calls, object)
}, funcr.Options{
Verbosity: 1,
}))
// A panicking call
funcFoo = func() (*http.Response, error) {
panic(errors.New("oh no!"))
}
s := CheckForUpgradesScheduler{
Client: fakeClient,
Config: cfg,
}
s.check(ctx)
assert.Equal(t, len(calls), 2)
assert.Assert(t, cmp.Contains(calls[1], `encountered panic in upgrade check`))
})
t.Run("successful log each loop, ticker works", func(t *testing.T) {
ctx := context.Background()
// capture logs
var calls []string
ctx = logging.NewContext(ctx, funcr.NewJSON(func(object string) {
calls = append(calls, object)
}, funcr.Options{
Verbosity: 1,
}))
// A successful call
funcFoo = func() (*http.Response, error) {
json := `{"pgo_versions":[{"tag":"v5.0.4"},{"tag":"v5.0.3"},{"tag":"v5.0.2"},{"tag":"v5.0.1"},{"tag":"v5.0.0"}]}`
return &http.Response{
Body: io.NopCloser(strings.NewReader(json)),
StatusCode: http.StatusOK,
}, nil
}
// Set loop time to 1s and sleep for 2s before sending the done signal
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
s := CheckForUpgradesScheduler{
Client: fakeClient,
Config: cfg,
Refresh: 1 * time.Second,
}
assert.ErrorIs(t, context.DeadlineExceeded, s.Start(ctx))
// Sleeping leads to some non-deterministic results, but we expect at least 2 executions
// plus one log for the failure to apply the configmap
assert.Assert(t, len(calls) >= 4)
assert.Assert(t, cmp.Contains(calls[1], `{\"pgo_versions\":[{\"tag\":\"v5.0.4\"},{\"tag\":\"v5.0.3\"},{\"tag\":\"v5.0.2\"},{\"tag\":\"v5.0.1\"},{\"tag\":\"v5.0.0\"}]}`))
assert.Assert(t, cmp.Contains(calls[3], `{\"pgo_versions\":[{\"tag\":\"v5.0.4\"},{\"tag\":\"v5.0.3\"},{\"tag\":\"v5.0.2\"},{\"tag\":\"v5.0.1\"},{\"tag\":\"v5.0.0\"}]}`))
})
}
func TestCheckForUpgradesSchedulerLeaderOnly(t *testing.T) {
// CheckForUpgradesScheduler should implement this interface.
var s manager.LeaderElectionRunnable = new(CheckForUpgradesScheduler)
assert.Assert(t, s.NeedLeaderElection(),
"expected to only run on the leader")
}