-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint_test.go
541 lines (503 loc) · 11.7 KB
/
endpoint_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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package npoint_test
import (
"bytes"
"database/sql"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/muir/nject"
"github.com/muir/npoint"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
type (
intType3 int
intType5 int
intType7 int
)
type (
stringA string
stringB string
stringC string
stringD string
stringE string
stringF string
)
func NewBinder() *ManualBinder {
return &ManualBinder{
Bound: make(map[string]http.HandlerFunc),
}
}
type ManualBinder struct {
Bound map[string]http.HandlerFunc
}
func (b *ManualBinder) Bind(path string, h http.HandlerFunc) {
b.Bound[path] = h
}
func (b *ManualBinder) Call(path string, method string, buf string, h http.Header) *http.Response {
handler, found := b.Bound[path]
if !found {
panic(fmt.Sprintf("no handler for %s", path))
}
url := "http://localhost" + path
// nolint:noctx
req, err := http.NewRequest(method, url, bytes.NewReader([]byte(buf)))
if err != nil {
panic(err)
}
req.Header = h
w := NewWriter()
handler(w, req)
resp := &http.Response{
Status: fmt.Sprintf("%d Something", w.code),
StatusCode: w.code,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: w.h,
Body: ioutil.NopCloser(bytes.NewBuffer([]byte(w.buf))),
ContentLength: int64(len(w.buf)),
Request: req,
}
return resp
}
type Writer struct {
h http.Header
buf string
code int
}
func NewWriter() *Writer { return &Writer{h: make(http.Header)} }
func (w *Writer) Write(b []byte) (int, error) { w.buf += string(b); return len(b), nil }
func (w *Writer) Header() http.Header { return w.h }
func (w *Writer) WriteHeader(i int) { w.code = i }
func TestTestFramework(t *testing.T) {
t.Parallel()
b := NewBinder()
var bodyReceived string
var headerReceived string
b.Bind("/y", func(w http.ResponseWriter, r *http.Request) {
buf, err := ioutil.ReadAll(r.Body)
assert.NoError(t, err)
bodyReceived = string(buf)
headerReceived = r.Header.Get("X-Test-Request")
w.Header().Set("X-Test-Respond", "H1")
_, _ = w.Write([]byte("some data written"))
w.WriteHeader(203)
})
h := make(http.Header)
h.Set("X-Test-Request", "H2")
// nolint:bodyclose
resp := b.Call("/y", "POST", "some data sent", h)
buf, err := ioutil.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "some data written", string(buf))
assert.Equal(t, "H1", resp.Header.Get("X-Test-Respond"))
assert.Equal(t, "", resp.Header.Get("X-Test-Request"))
assert.Equal(t, "some data sent", bodyReceived)
assert.Equal(t, "H2", headerReceived)
}
type interfaceI interface {
I() int
}
type interfaceJ interface {
I() int
}
type interfaceK interface {
I() int
}
type doesI struct {
i int
}
func (di *doesI) I() int { return di.i * 2 }
type doesJ struct {
j int
}
func (dj *doesJ) I() int { return dj.j * 3 }
func TestVariablePassing(t *testing.T) {
t.Skip("Requires fuzzy matching")
t.Parallel()
s := npoint.PreregisterService("TestVariablePassing")
s.RegisterEndpoint("/x",
// ------------- static injectors ------------
// [0] Send simple things
func() (stringA, stringB) {
return "static1", "static2"
},
func(b stringB) {
assert.Equal(t, stringB("static2"), b)
},
func(b stringB) {
assert.Equal(t, stringB("static2"), b)
},
// [3] Send interfaces
func() interfaceI {
return &doesI{7}
},
func() interfaceJ {
return &doesI{8}
},
func() *doesI {
return &doesI{9}
},
func() *doesJ {
return &doesJ{10}
},
// [7] check receiving by priority
func(i interfaceI) {
// exact match on interface
assert.Equal(t, 14, i.I())
},
func(j interfaceJ) {
// exact match on interface
assert.Equal(t, 16, j.I())
},
func(di *doesI) {
// exact match on interface
assert.Equal(t, 18, di.I())
},
func(k interfaceK) {
// nearest one that satisfies interface
assert.Equal(t, 30, k.I())
},
// ------------- middleware ------------
// [11]
func(inner func(intType3, stringC) (intType5, stringE), a stringA) {
assert.Equal(t, stringA("static1"), a)
i5, e := inner(93, "c-v")
assert.Equal(t, stringE("fooE"), e)
assert.Equal(t, intType5(55), i5)
},
// ------------- injector ------------
// [12]
func(c stringC, i3 intType3, j *doesJ) stringA {
assert.Equal(t, stringC("c-v"), c)
assert.Equal(t, intType3(93), i3)
assert.Equal(t, 30, j.I())
return "newAv"
},
// ------------- endpoint ------------
func(i3 intType3, b stringB, a stringA, c stringC) (stringE, intType5) {
assert.Equal(t, intType3(93), i3)
assert.Equal(t, stringB("static2"), b)
assert.Equal(t, stringA("newAv"), a)
assert.Equal(t, stringC("c-v"), c)
return "fooE", 55
})
b := NewBinder()
s.Start(b.Bind)
// nolint:bodyclose
_ = b.Call("/x", "GET", "", make(http.Header))
}
var inclusionTests = []struct {
name string
endpoint interface{}
called string
}{
{
"just e",
func(e stringE) {},
"e cd",
},
}
func TestInclusion(t *testing.T) {
t.Parallel()
for _, tc := range inclusionTests {
s := npoint.PreregisterService(fmt.Sprintf("TestDemandInclusion-%s", tc.name))
called := make(map[string]bool)
s.RegisterEndpoint("/x",
func() (stringA, stringB) {
called["ab"] = true
return "static1", "static2"
},
func() (stringC, stringD) {
called["cd"] = true
return "static3", "static4"
},
func(d stringD) stringE {
called["e"] = true
return "static5"
},
func(b stringB) stringF {
called["f"] = true
return "static6"
},
tc.endpoint)
b := NewBinder()
s.Start(b.Bind)
// nolint:bodyclose
_ = b.Call("/x", "GET", "", make(http.Header))
expected := make(map[string]bool)
for _, c := range strings.Split(tc.called, " ") {
expected[c] = true
}
assert.Equal(t, expected, called, tc.name)
}
}
type error2 struct {
e error
}
func (e2 error2) Error() string {
return e2.e.Error()
}
type paymentProvider interface {
Stuff() int
}
type examplePaymentProvider int
func (epp examplePaymentProvider) Stuff() int {
return int(epp * 2)
}
type (
tripsURI string
csettings map[string]string
logger interface {
Logf(string, ...interface{})
}
)
type enhancedWriter interface {
http.ResponseWriter
S(int)
}
type enhancedWriterImp struct {
http.ResponseWriter
}
func (w enhancedWriterImp) S(i int) {
w.WriteHeader(i)
}
type (
dbname string
rbody []byte
jresult interface{}
)
func TestChains(t *testing.T) {
t.Parallel()
chainTests := []struct {
Name string
Panics bool
Chain []interface{}
}{
{
"interface games",
true, // requires fuzzy matching
[]interface{}{
func() logger {
return t
},
func(w http.ResponseWriter, l logger) enhancedWriter {
return &enhancedWriterImp{w}
},
func(inner func() jresult) {
j := inner()
e, is := j.(error)
assert.True(t, is)
assert.Equal(t, "example error", e.Error())
},
func(inner func() (jresult, error2), l logger, w enhancedWriter) jresult {
_, err := inner()
return err
},
func(inner func() error, l logger, w enhancedWriter) error2 {
return error2{inner()}
},
func() error {
return fmt.Errorf("example error")
},
},
},
{
"unused return",
true,
[]interface{}{
func(inner func() error) error {
return inner()
},
func(r *http.Request, w http.ResponseWriter) error {
return nil
},
},
},
{
"obscured return",
true,
[]interface{}{
func(inner func() error2) {
_ = inner()
},
func(inner func() error) error {
return inner()
},
func(inner func() error) *error2 {
return &error2{inner()}
},
func(r *http.Request, w http.ResponseWriter) error {
return nil
},
},
},
{
"regression",
false,
[]interface{}{
nject.Sequence("service",
func() paymentProvider {
return examplePaymentProvider(7)
},
func() tripsURI {
return "tu"
},
func() context.Context {
return context.Background()
},
nject.Sequence("common-handlers",
func() logger {
return t
},
nject.Sequence("base-collection",
func() csettings {
return make(map[string]string)
},
func(r *http.Request, l logger) logger {
return l
},
func(w http.ResponseWriter, l logger) enhancedWriter {
return &enhancedWriterImp{w}
},
func(w enhancedWriter, ac csettings) {},
func(inner func() jresult, w enhancedWriter, l logger) {
_ = inner()
},
func(inner func() (jresult, error2), l logger, w enhancedWriter) jresult {
res, _ := inner()
return res
},
func(inner func() error, l logger, w enhancedWriter) error2 {
return error2{inner()}
},
func(inner func(rbody) error, r *http.Request) error {
return inner([]byte("foo"))
},
),
nject.Sequence("open-database",
func() dbname {
return "foo"
},
func(inner func(*sql.DB) error, name dbname) error {
db, err := sql.Open("postgres", string(name))
if err != nil {
return err
}
err = inner(db)
db.Close()
return err
},
),
func(inner func(*sql.Tx) error, db *sql.DB, l logger, w enhancedWriter) error {
tx, _ := db.Begin()
return inner(tx)
},
),
),
func(inner func() error, w enhancedWriter) jresult {
return nil
},
func(l logger, b rbody, tx *sql.Tx) error {
return nil
},
},
},
{
"static regression",
false,
[]interface{}{
nject.Sequence("service",
func() paymentProvider {
return examplePaymentProvider(7)
},
func() tripsURI {
return "tu"
},
func() context.Context {
return context.Background()
},
nject.Sequence("common-handlers",
func() logger {
return t
},
nject.Sequence("base-collection",
func() csettings {
return make(map[string]string)
},
func(r *http.Request, l logger) logger {
return l
},
func(w http.ResponseWriter, l logger) enhancedWriter {
return &enhancedWriterImp{w}
},
func(w enhancedWriter, ac csettings) {},
func(inner func() jresult, w enhancedWriter, l logger) {
_ = inner()
},
func(inner func() (jresult, error2), l logger, w enhancedWriter) jresult {
res, _ := inner()
return res
},
func(inner func() error, l logger, w enhancedWriter) error2 {
return error2{inner()}
},
func(inner func(rbody) error, r *http.Request) error {
return inner([]byte("foo"))
},
),
nject.Sequence("open-database",
func() dbname {
return "foo"
},
func(inner func(*sql.DB) error, name dbname) error {
db, err := sql.Open("postgres", string(name))
if err != nil {
return err
}
err = inner(db)
db.Close()
return err
},
),
func(inner func(*sql.Tx) error, db *sql.DB, l logger, w enhancedWriter) error {
tx, _ := db.Begin()
return inner(tx)
},
func() intType7 {
return 3
},
),
),
nject.Sequence("endpoint-list",
func(i intType7) intType5 {
return 3
},
func(l logger, b rbody, tx *sql.Tx, i intType5) (jresult, error) {
return nil, nil
},
),
},
},
}
for _, test := range chainTests {
test := test
t.Log("TEST:", test.Name)
f := func() {
e := npoint.CreateEndpoint(test.Chain...)
b := NewBinder()
b.Bind("/foo", e)
// nolint:bodyclose
b.Call("/foo", "GET", "", nil)
}
if test.Panics {
assert.Panics(t, f, test.Name)
} else {
f()
assert.NotPanics(t, f, test.Name)
}
}
}