-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
client_test.go
240 lines (198 loc) 路 6.83 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
// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/pulumi/pulumi/sdk/v3/go/common/apitype"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newMockServer(statusCode int, message string) *httptest.Server {
return httptest.NewServer(
http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(statusCode)
_, err := rw.Write([]byte(message))
if err != nil {
return
}
}))
}
func newMockServerRequestProcessor(statusCode int, processor func(req *http.Request) string) *httptest.Server {
return httptest.NewServer(
http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(statusCode)
_, err := rw.Write([]byte(processor(req)))
if err != nil {
return
}
}))
}
func newMockClient(server *httptest.Server) *Client {
return &Client{
apiURL: server.URL,
apiToken: "",
apiUser: "",
diag: nil,
client: &defaultRESTClient{
client: &defaultHTTPClient{
client: http.DefaultClient,
},
},
}
}
func TestAPIErrorResponses(t *testing.T) {
t.Parallel()
t.Run("TestAuthError", func(t *testing.T) {
t.Parallel()
// check 401 error is handled
unauthorizedServer := newMockServer(401, "401: Unauthorized")
defer unauthorizedServer.Close()
unauthorizedClient := newMockClient(unauthorizedServer)
_, _, unauthorizedErr := unauthorizedClient.GetCLIVersionInfo(context.Background())
assert.Error(t, unauthorizedErr)
assert.Equal(t, unauthorizedErr.Error(), "this command requires logging in; try running `pulumi login` first")
})
t.Run("TestRateLimitError", func(t *testing.T) {
t.Parallel()
// test handling 429: Too Many Requests/rate-limit response
rateLimitedServer := newMockServer(429, "rate-limit error")
defer rateLimitedServer.Close()
rateLimitedClient := newMockClient(rateLimitedServer)
_, _, rateLimitErr := rateLimitedClient.GetCLIVersionInfo(context.Background())
assert.Error(t, rateLimitErr)
assert.Equal(t, rateLimitErr.Error(), "pulumi service: request rate-limit exceeded")
})
t.Run("TestDefaultError", func(t *testing.T) {
t.Parallel()
// test handling non-standard error message
defaultErrorServer := newMockServer(418, "I'm a teapot")
defer defaultErrorServer.Close()
defaultErrorClient := newMockClient(defaultErrorServer)
_, _, defaultErrorErr := defaultErrorClient.GetCLIVersionInfo(context.Background())
assert.Error(t, defaultErrorErr)
})
}
func TestGzip(t *testing.T) {
t.Parallel()
// test handling non-standard error message
gzipCheckServer := newMockServerRequestProcessor(200, func(req *http.Request) string {
assert.Equal(t, req.Header.Get("Content-Encoding"), "gzip")
return "{}"
})
defer gzipCheckServer.Close()
client := newMockClient(gzipCheckServer)
// POST /import
_, err := client.ImportStackDeployment(context.Background(), StackIdentifier{}, nil)
assert.NoError(t, err)
// PATCH /checkpoint
err = client.PatchUpdateCheckpoint(context.Background(), UpdateIdentifier{}, nil, "")
assert.NoError(t, err)
// POST /events/batch
err = client.RecordEngineEvents(context.Background(), UpdateIdentifier{}, apitype.EngineEventBatch{}, "")
assert.NoError(t, err)
// POST /events/batch
_, err = client.BulkDecryptValue(context.Background(), StackIdentifier{}, nil)
assert.NoError(t, err)
}
func TestPatchUpdateCheckpointVerbatimIndents(t *testing.T) {
t.Parallel()
deployment := apitype.DeploymentV3{
Resources: []apitype.ResourceV3{
{URN: resource.URN("urn1")},
{URN: resource.URN("urn2")},
},
}
var serializedDeployment json.RawMessage
serializedDeployment, err := json.Marshal(deployment)
assert.NoError(t, err)
untypedDeployment, err := json.Marshal(apitype.UntypedDeployment{
Version: 3,
Deployment: serializedDeployment,
})
assert.NoError(t, err)
var request apitype.PatchUpdateVerbatimCheckpointRequest
server := newMockServerRequestProcessor(200, func(req *http.Request) string {
reader, err := gzip.NewReader(req.Body)
assert.NoError(t, err)
defer reader.Close()
err = json.NewDecoder(reader).Decode(&request)
assert.NoError(t, err)
return "{}"
})
client := newMockClient(server)
sequenceNumber := 1
indented, err := MarshalUntypedDeployment(&deployment)
assert.NoError(t, err)
err = client.PatchUpdateCheckpointVerbatim(context.Background(),
UpdateIdentifier{}, sequenceNumber, indented, "token")
assert.NoError(t, err)
compacted := func(raw json.RawMessage) string {
var buf bytes.Buffer
err := json.Compact(&buf, []byte(raw))
assert.NoError(t, err)
return buf.String()
}
// It should have more than one line as json.Marshal would produce.
assert.Equal(t, 4, len(strings.Split(string(request.UntypedDeployment), "\n")))
// Compacting should recover the same form as json.Marshal would produce.
assert.Equal(t, string(untypedDeployment), compacted(request.UntypedDeployment))
}
func TestGetCapabilities(t *testing.T) {
t.Parallel()
t.Run("legacy-service-404", func(t *testing.T) {
t.Parallel()
s := newMockServer(404, "NOT FOUND")
defer s.Close()
c := newMockClient(s)
resp, err := c.GetCapabilities(context.Background())
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.Empty(t, resp.Capabilities)
})
t.Run("updated-service-with-delta-checkpoint-capability", func(t *testing.T) {
t.Parallel()
cfg := apitype.DeltaCheckpointUploadsConfigV1{
CheckpointCutoffSizeBytes: 1024 * 1024 * 4,
}
cfgJSON, err := json.Marshal(cfg)
require.NoError(t, err)
actualResp := apitype.CapabilitiesResponse{
Capabilities: []apitype.APICapabilityConfig{{
Version: 3,
Capability: apitype.DeltaCheckpointUploads,
Configuration: json.RawMessage(cfgJSON),
}},
}
respJSON, err := json.Marshal(actualResp)
require.NoError(t, err)
s := newMockServer(200, string(respJSON))
defer s.Close()
c := newMockClient(s)
resp, err := c.GetCapabilities(context.Background())
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.Len(t, resp.Capabilities, 1)
assert.Equal(t, apitype.DeltaCheckpointUploads, resp.Capabilities[0].Capability)
assert.Equal(t, `{"checkpointCutoffSizeBytes":4194304}`,
string(resp.Capabilities[0].Configuration))
})
}