-
Notifications
You must be signed in to change notification settings - Fork 41
/
client_test.go
405 lines (373 loc) · 13.5 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package stencil_test
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os/exec"
"path/filepath"
"testing"
"time"
stencil "github.com/raystack/stencil/clients/go"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/dynamicpb"
)
func runProtoc(
rootDir string,
includeImports bool,
descSetOut string,
filePaths []string,
) error {
protocBinPath, err := exec.LookPath("protoc")
if err != nil {
return err
}
protocBinPath, err = filepath.EvalSymlinks(protocBinPath)
if err != nil {
return err
}
protocBinPath, err = filepath.Abs(protocBinPath)
if err != nil {
return err
}
protocIncludePath, err := filepath.Abs(filepath.Join(filepath.Dir(protocBinPath), "..", "include"))
if err != nil {
return err
}
args := []string{"-I", rootDir, "-I", protocIncludePath}
args = append(args, fmt.Sprintf("--descriptor_set_out=%s", descSetOut))
if includeImports {
args = append(args, "--include_imports")
}
args = append(args, filePaths...)
stderr := bytes.NewBuffer(nil)
cmd := exec.Command(protocBinPath, args...)
cmd.Stdout = stderr
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s returned error: %v %v", protocBinPath, err, stderr.String())
}
return nil
}
func getDescriptorDataByPath(t *testing.T, includeImports bool, rootPath string) ([]byte, error) {
root, _ := filepath.Abs(rootPath)
fileName := filepath.Join(t.TempDir(), "file.desc")
rootFiles, _ := filepath.Glob(filepath.Join(root, "./*.proto"))
err := runProtoc(root, includeImports, fileName, rootFiles)
assert.NoError(t, err)
data, err := ioutil.ReadFile(fileName)
return data, err
}
func getDescriptorData(t *testing.T, includeImports bool) ([]byte, error) {
return getDescriptorDataByPath(t, includeImports, "./test_data")
}
func getUpdatedDescriptorDataAndMsgData(t *testing.T, includeImports bool) ([]byte, []byte) {
data, err := getDescriptorDataByPath(t, includeImports, "./test_data/updated")
assert.NoError(t, err)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}))
defer ts.Close()
url := ts.URL
client, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Nil(t, err)
assert.NotNil(t, client)
msgDesc, err := client.GetDescriptor("test.stencil.One")
assert.NoError(t, err)
//construct message
msg := dynamicpb.NewMessage(msgDesc).New()
fieldOne := msgDesc.Fields().ByName("field_one")
msg.Set(fieldOne, protoreflect.ValueOfInt64(200))
fieldTwo := msgDesc.Fields().ByName("field_two")
msg.Set(fieldTwo, protoreflect.ValueOfInt64(300))
msgData, err := proto.Marshal(msg.Interface())
assert.NoError(t, err)
return data, msgData
}
func TestNewClient(t *testing.T) {
t.Run("should return error if url is not valid", func(t *testing.T) {
url := "h_ttp://invalidurl"
_, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Contains(t, err.Error(), "invalid request")
})
t.Run("should return error if request fails", func(t *testing.T) {
url := "ithttp://localhost"
_, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Contains(t, err.Error(), "request failed")
})
t.Run("should return error if file download fails", func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}))
defer ts.Close()
url := ts.URL
_, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Contains(t, err.Error(), "request failed.")
})
t.Run("should return error if downloaded file is not valid", func(t *testing.T) {
data := []byte("invalid")
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}))
defer ts.Close()
url := ts.URL
_, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Contains(t, err.Error(), "invalid file descriptorset file.")
})
t.Run("should return error if downloaded file is not fully contained file", func(t *testing.T) {
data, err := getDescriptorData(t, false)
assert.NoError(t, err)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}))
defer ts.Close()
url := ts.URL
_, err = stencil.NewClient([]string{url}, stencil.Options{})
if assert.NotNil(t, err) {
assert.Contains(t, err.Error(), "file is not fully contained descriptor file.")
}
})
t.Run("should create a client if provided descriptor file is valid", func(t *testing.T) {
data, err := getDescriptorData(t, true)
assert.NoError(t, err)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}))
defer ts.Close()
url := ts.URL
client, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Nil(t, err)
assert.NotNil(t, client)
})
t.Run("should pass provided headers to request", func(t *testing.T) {
data, _ := getDescriptorData(t, true)
headers := map[string]string{
"key": "value",
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for key, val := range headers {
assert.Equal(t, val, r.Header.Get(key))
}
w.Write(data)
}))
client, err := stencil.NewClient([]string{ts.URL}, stencil.Options{HTTPOptions: stencil.HTTPOptions{Headers: headers}})
assert.Nil(t, err)
assert.NotNil(t, client)
})
t.Run("should refresh descriptors by specified intervals", func(t *testing.T) {
data, _ := getDescriptorData(t, true)
callCount := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.Write(data)
}))
client, _ := stencil.NewClient([]string{ts.URL}, stencil.Options{AutoRefresh: true, RefreshInterval: 2 * time.Millisecond})
// wait for interval to end
time.Sleep(3 * time.Millisecond)
client.GetDescriptor("test.One")
time.Sleep(1 * time.Millisecond)
client.Close()
assert.Equal(t, 2, callCount)
})
}
func TestClient(t *testing.T) {
t.Run("GetDescriptor", func(t *testing.T) {
data, err := getDescriptorData(t, true)
assert.NoError(t, err)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}))
defer ts.Close()
url := ts.URL
client, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Nil(t, err)
assert.NotNil(t, client)
t.Run("should return notFoundErr if not found", func(t *testing.T) {
msg, err := client.GetDescriptor("test.stencil.Two.Unknown")
assert.Nil(t, msg)
assert.NotNil(t, err)
assert.Equal(t, stencil.ErrNotFound, err)
})
t.Run("should get nested message descriptor from fully qualified java classname", func(t *testing.T) {
msg, err := client.GetDescriptor("test.stencil.Two.Four")
assert.Nil(t, err)
field := msg.Fields().ByName("recursive")
assert.NotNil(t, field)
})
t.Run("should get nested message descriptor if java_option not specified", func(t *testing.T) {
msg, err := client.GetDescriptor("test.Three")
assert.Nil(t, err)
field := msg.Fields().ByName("field_one")
assert.NotNil(t, field)
})
t.Run("should get descriptor if package name is not defined", func(t *testing.T) {
msg, err := client.GetDescriptor("Root")
assert.Nil(t, err)
field := msg.Fields().ByName("field_one")
assert.NotNil(t, field)
})
t.Run("should get descriptor if proto package name is not defined but java package is defined", func(t *testing.T) {
msg, err := client.GetDescriptor("test.stencil.Root")
assert.Nil(t, err)
field := msg.Fields().ByName("field_one")
assert.NotNil(t, field)
})
})
t.Run("Parse", func(t *testing.T) {
data, err := getDescriptorData(t, true)
assert.NoError(t, err)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}))
defer ts.Close()
url := ts.URL
client, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Nil(t, err)
assert.NotNil(t, client)
t.Run("should return notFoundErr if not found", func(t *testing.T) {
msg, err := client.Parse("test.stencil.Two.Unknown", []byte(""))
assert.Nil(t, msg)
assert.NotNil(t, err)
assert.Equal(t, stencil.ErrNotFound, err)
})
t.Run("should parse wire format data given className", func(t *testing.T) {
msgDesc, err := client.GetDescriptor("test.stencil.One")
assert.NoError(t, err)
//construct message
msg := dynamicpb.NewMessage(msgDesc).New()
fieldOne := msgDesc.Fields().ByName("field_one")
msg.Set(fieldOne, protoreflect.ValueOfInt64(200))
bytesData, err := proto.Marshal(msg.Interface())
assert.NoError(t, err)
parsed, err := client.Parse("test.stencil.One", bytesData)
assert.Nil(t, err)
assert.NotNil(t, parsed)
val := parsed.ProtoReflect().Get(fieldOne)
assert.Equal(t, int64(200), val.Int())
assert.Nil(t, parsed.ProtoReflect().GetUnknown())
})
t.Run("should parse extensions without having any unknown fields", func(t *testing.T) {
msgDesc, err := client.GetDescriptor("test.ExtendableMessage")
assert.NoError(t, err)
//construct message
msg := dynamicpb.NewMessage(msgDesc).New()
fieldOne := msgDesc.Fields().ByName("field_extra")
msg.Set(fieldOne, protoreflect.ValueOfInt64(200))
extenderMsgDesc, err := client.GetDescriptor("test.Extender")
assert.NoError(t, err)
fieldTwoDesc := extenderMsgDesc.Extensions().ByName("field_two")
fieldTwoType := dynamicpb.NewExtensionType(fieldTwoDesc)
fieldTwo := fieldTwoType.TypeDescriptor()
proto.SetExtension(msg.Interface(), fieldTwoType, "field_two_value")
bytesData, err := proto.Marshal(msg.Interface())
assert.NoError(t, err)
parsed, err := client.Parse("test.ExtendableMessage", bytesData)
assert.Nil(t, err)
assert.NotNil(t, parsed)
val := parsed.ProtoReflect().Get(fieldOne)
assert.Equal(t, int64(200), val.Int())
val2 := parsed.ProtoReflect().Get(fieldTwo)
assert.Equal(t, "field_two_value", val2.String())
assert.Nil(t, parsed.ProtoReflect().GetUnknown())
})
})
t.Run("Serialize", func(t *testing.T) {
desc, err := getDescriptorData(t, true)
assert.NoError(t, err)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(desc)
}))
defer ts.Close()
url := ts.URL
client, err := stencil.NewClient([]string{url}, stencil.Options{})
assert.Nil(t, err)
assert.NotNil(t, client)
validData := map[string]interface{}{
"field_one": 23,
}
t.Run("should return error when unable to get descriptor", func(t *testing.T) {
result, err := client.Serialize("invalidClass", validData)
assert.Nil(t, result)
assert.Equal(t, stencil.ErrNotFound, err)
})
t.Run("should return error when unable to serialize to bytes", func(t *testing.T) {
mapData := make(map[string]interface{})
mapData["key1"] = "value1"
result, err := client.Serialize("test.stencil.One", mapData)
assert.Nil(t, result)
assert.Error(t, err)
assert.Equal(t, stencil.ErrInvalidDescriptor, err)
})
t.Run("should return bytes", func(t *testing.T) {
className := "test.stencil.One"
bytes, err := client.Serialize(className, validData)
assert.NoError(t, err)
parsed, err := client.Parse(className, bytes)
if err != nil {
t.Fatal(err)
}
descriptor, err := client.GetDescriptor(className)
if err != nil {
t.Fatal(err)
}
fieldOneValue := validData["field_one"].(int)
fieldOne := descriptor.Fields().ByName("field_one")
val := parsed.ProtoReflect().Get(fieldOne)
assert.Equal(t, int64(fieldOneValue), val.Int())
})
})
}
func TestRefreshStrategies(t *testing.T) {
t.Run("VersionBasedRefresh", func(t *testing.T) {
dataDownloadOneCount := 0
dataDownloadTwoCount := 0
versionsDownloadCount := 0
// setup
data, err := getDescriptorDataByPath(t, true, "./test_data")
assert.NoError(t, err)
versions := `{"versions": [1]}`
mux := http.NewServeMux()
mux.HandleFunc("/v1beta1/namespaces/test-namespace/schemas/test-schema/versions", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
rw.Write([]byte(versions))
versionsDownloadCount++
})
mux.HandleFunc("/v1beta1/namespaces/test-namespace/schemas/test-schema/versions/1", func(rw http.ResponseWriter, r *http.Request) {
rw.Write(data)
dataDownloadOneCount++
})
mux.HandleFunc("/v1beta1/namespaces/test-namespace/schemas/test-schema/versions/2", func(rw http.ResponseWriter, r *http.Request) {
rw.Write(data)
dataDownloadTwoCount++
})
ts := httptest.NewServer(mux)
// test
opts := stencil.Options{AutoRefresh: true, RefreshStrategy: stencil.VersionBasedRefresh, RefreshInterval: 2 * time.Millisecond}
client, err := stencil.NewClient([]string{fmt.Sprintf("%s/v1beta1/namespaces/test-namespace/schemas/test-schema", ts.URL)}, opts)
assert.NoError(t, err)
assert.NotNil(t, client)
// wait for refresh interval
time.Sleep(3 * time.Millisecond)
desc, err := client.GetDescriptor("test.stencil.One")
assert.Nil(t, err)
assert.NotNil(t, desc)
time.Sleep(1 * time.Millisecond)
assert.Equal(t, 2, versionsDownloadCount)
assert.Equal(t, 1, dataDownloadOneCount)
assert.Equal(t, 0, dataDownloadTwoCount)
// simulates version update
versions = `{"versions": [1,2]}`
// wait for refresh interval
time.Sleep(3 * time.Millisecond)
desc, err = client.GetDescriptor("test.stencil.One")
assert.Nil(t, err)
assert.NotNil(t, desc)
time.Sleep(1 * time.Millisecond)
assert.Equal(t, 3, versionsDownloadCount)
assert.Equal(t, 1, dataDownloadOneCount)
assert.Equal(t, 1, dataDownloadTwoCount)
})
}