-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
359 lines (317 loc) · 7.69 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
package governor
import (
"bytes"
"context"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"strings"
"testing"
"testing/fstest"
"time"
"github.com/stretchr/testify/require"
"xorkevin.dev/governor/util/kjson"
"xorkevin.dev/kerrors"
"xorkevin.dev/kfs"
"xorkevin.dev/kfs/kfstest"
"xorkevin.dev/klog"
)
type (
testServiceC struct {
log *klog.LevelLogger
}
testServiceCReq struct {
Method string `json:"method"`
Path string `json:"path"`
}
)
func (s *testServiceC) Register(r ConfigRegistrar) {
}
func (s *testServiceC) Init(ctx context.Context, r ConfigReader, kit ServiceKit) error {
s.log = klog.NewLevelLogger(kit.Logger)
m1 := NewMethodRouter(kit.Router)
m1.AnyCtx("/echo", s.echo)
m1.AnyCtx("/fail", s.fail)
return nil
}
func (s *testServiceC) Start(ctx context.Context) error {
return nil
}
func (s *testServiceC) Stop(ctx context.Context) {
}
func (s *testServiceC) Setup(ctx context.Context, req ReqSetup) error {
return nil
}
func (s *testServiceC) Health(ctx context.Context) error {
return nil
}
func (s *testServiceC) echo(c *Context) {
c.WriteJSON(http.StatusOK, testServiceCReq{
Method: c.Req().Method,
Path: c.Req().URL.EscapedPath(),
})
}
func (s *testServiceC) fail(c *Context) {
c.WriteError(ErrWithRes(nil, http.StatusBadRequest, "", "Test fail"))
}
type (
testClientC struct {
log *klog.LevelLogger
term Term
httpc *HTTPFetcher
ranRegister bool
ranInit bool
}
)
func (c *testClientC) Register(r ConfigRegistrar, cr CmdRegistrar) {
c.ranRegister = true
r.SetDefault("prop1", "val1")
cr.Register(CmdDesc{
Usage: "echo",
Short: "echo input",
Long: "test route that echos input",
Flags: nil,
}, CmdHandlerFunc(c.echo))
}
func (c *testClientC) Init(r ClientConfigReader, kit ClientKit) error {
c.ranInit = true
if u, err := url.Parse(r.Config().BaseURL); err != nil {
return kerrors.WithMsg(err, "Invalid base url")
} else if u.Path != "/api" {
return kerrors.WithMsg(nil, "Mismatched client config")
}
if r.Name() != "servicec" {
return kerrors.WithMsg(nil, "Mismatched client name")
}
if r.URL() != "/servicec" {
return kerrors.WithMsg(nil, "Mismatched client url")
}
if !r.GetBool("propbool") {
return kerrors.WithMsg(nil, "Mismatched prop bool")
}
if r.GetInt("propint") != 123 {
return kerrors.WithMsg(nil, "Mismatched prop int")
}
if t, err := r.GetDuration("propdur"); err != nil {
return kerrors.WithMsg(err, "Mismatched prop int")
} else if t != 24*time.Hour {
return kerrors.WithMsg(nil, "Mismatched prop int")
}
if r.GetStr("prop1") != "value1" {
return kerrors.WithMsg(nil, "Mismatched prop str")
}
if k := r.GetStrSlice("propslice"); len(k) != 3 || k[0] != "abc" {
return kerrors.WithMsg(nil, "Mismatched prop str slice")
}
var propobj testServiceCReq
if err := r.Unmarshal("propobj", &propobj); err != nil || propobj != (testServiceCReq{
Method: "abc",
Path: "def",
}) {
return kerrors.WithMsg(err, "Mismatched prop obj")
}
c.log = klog.NewLevelLogger(kit.Logger)
c.term = kit.Term
c.httpc = NewHTTPFetcher(kit.HTTPClient)
return nil
}
func (c *testClientC) echo(args []string) error {
req, err := c.httpc.ReqJSON(http.MethodPost, "/echo", testServiceCReq{
Method: http.MethodPost,
Path: "/api/servicec/echo",
})
if err != nil {
return err
}
var res testServiceCReq
if _, err := c.httpc.DoJSON(context.Background(), req, &res); err != nil {
return err
}
b, err := kjson.Marshal(res)
if err != nil {
return err
}
if _, err := c.term.Stdout().Write(b); err != nil {
return err
}
var buf bytes.Buffer
f, err := fs.ReadFile(c.term.FS(), "test.txt")
if err != nil {
return kerrors.WithMsg(err, "Could not read file")
}
if _, err := buf.Write(f); err != nil {
return err
}
ib, err := io.ReadAll(c.term.Stdin())
if err != nil {
return kerrors.WithMsg(err, "Could not read stdin")
}
if _, err := buf.Write(ib); err != nil {
return err
}
if err := kfs.WriteFile(c.term.FS(), "testoutput.txt", buf.Bytes(), 0o644); err != nil {
return kerrors.WithMsg(err, "Could not write file")
}
return nil
}
func (c *testClientC) echoEmpty(args []string) error {
req, err := c.httpc.ReqJSON(http.MethodPost, "/echo", testServiceCReq{
Method: http.MethodPost,
Path: "/api/servicec/echo",
})
if err != nil {
return err
}
res, err := c.httpc.DoNoContent(context.Background(), req)
if err != nil {
return err
}
if _, err := io.WriteString(c.term.Stdout(), strconv.Itoa(res.StatusCode)); err != nil {
return err
}
return nil
}
func (c *testClientC) fail(args []string) error {
req, err := c.httpc.ReqJSON(http.MethodPost, "/fail", testServiceCReq{
Method: http.MethodPost,
Path: "/api/servicec/fail",
})
if err != nil {
return err
}
var res testServiceCReq
if _, err = c.httpc.DoJSON(context.Background(), req, &res); err != nil {
return err
}
return kerrors.WithMsg(nil, "Should have errored")
}
type (
handlerRoundTripper struct {
Handler http.Handler
}
)
func (h handlerRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
rec := httptest.NewRecorder()
r = r.Clone(klog.ExtendCtx(r.Context(), nil))
h.Handler.ServeHTTP(rec, r)
return rec.Result(), nil
}
func TestClient(t *testing.T) {
t.Parallel()
server := New(Opts{
Appname: "govtest",
Version: Version{
Num: "test",
Hash: "dev",
},
Description: "test gov server",
EnvPrefix: "gov",
ClientPrefix: "govc",
}, &ServerOpts{
ConfigReader: strings.NewReader(`
{
"http": {
"addr": ":8080",
"basepath": "/api"
}
}
`),
VaultReader: strings.NewReader(`
{
"data": {
}
}
`),
Fsys: fstest.MapFS{},
})
serviceC := &testServiceC{}
server.Register("servicec", "/servicec", serviceC)
assert := require.New(t)
assert.NoError(server.Start(context.Background(), Flags{}, klog.Discard{}))
var out bytes.Buffer
fsys := &kfstest.MapFS{
Fsys: fstest.MapFS{
"test.txt": &fstest.MapFile{
Data: []byte(`test file contents`),
Mode: 0o644,
ModTime: time.Now(),
},
},
}
client := NewClient(Opts{
Appname: "govtest",
Version: Version{
Num: "test",
Hash: "dev",
},
Description: "test gov server",
EnvPrefix: "gov",
ClientPrefix: "govc",
}, &ClientOpts{
ConfigReader: strings.NewReader(`
{
"servicec": {
"propbool": true,
"propint": 123,
"propdur": "24h",
"prop1": "value1",
"propslice": [
"abc",
"def",
"ghi"
],
"propobj": {
"method": "abc",
"path": "def"
}
}
}
`),
HTTPTransport: handlerRoundTripper{
Handler: server,
},
TermConfig: &TermConfig{
StdinFd: int(os.Stdin.Fd()),
Stdin: strings.NewReader("test input contents"),
Stdout: klog.NewSyncWriter(&out),
Stderr: io.Discard,
Fsys: fsys,
},
})
client.SetFlags(ClientFlags{})
clientC := &testClientC{}
client.Register("servicec", "/servicec", &CmdDesc{
Usage: "sc",
Short: "service c",
Long: "interact with service c",
Flags: nil,
}, clientC)
assert.NoError(client.Init(ClientFlags{}, klog.Discard{}))
assert.True(clientC.ranRegister)
assert.True(clientC.ranInit)
assert.NoError(clientC.echo(nil))
var echoRes testServiceCReq
assert.NoError(kjson.Unmarshal(out.Bytes(), &echoRes))
assert.Equal(testServiceCReq{
Method: http.MethodPost,
Path: "/api/servicec/echo",
}, echoRes)
out.Reset()
outputFile := fsys.Fsys["testoutput.txt"]
assert.NotNil(outputFile)
assert.Equal([]byte("test file contentstest input contents"), outputFile.Data)
assert.NoError(clientC.echoEmpty(nil))
status, err := strconv.Atoi(out.String())
assert.NoError(err)
assert.Equal(200, status)
out.Reset()
err = clientC.fail(nil)
assert.Error(err)
var errres *ErrorServerRes
assert.ErrorAs(err, &errres)
assert.Equal("Test fail", errres.Message)
}