-
Notifications
You must be signed in to change notification settings - Fork 8
/
main_test.go
80 lines (64 loc) · 1.86 KB
/
main_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
package main
import (
"bytes"
"context"
"encoding/json"
"net/http/httptest"
"testing"
"github.com/jsteenb2/allsrvc"
"github.com/jsteenb2/mess/allsrv"
"github.com/jsteenb2/mess/allsrv/allsrvtesting"
)
func TestCliSVC(t *testing.T) {
allsrvtesting.TestSVC(t, func(t *testing.T, opts allsrvtesting.SVCTestOpts) allsrvtesting.SVCDeps {
svc := allsrvtesting.NewInmemSVC(t, opts)
srv := httptest.NewServer(allsrv.NewServerV2(svc))
t.Cleanup(srv.Close)
return allsrvtesting.SVCDeps{
SVC: &cmdCLI{addr: srv.URL},
}
})
}
type cmdCLI struct {
addr string
}
func (c *cmdCLI) CreateFoo(ctx context.Context, f allsrv.Foo) (allsrv.Foo, error) {
return c.expectFoo(ctx, "add", "--name", f.Name, "--note", f.Note)
}
func (c *cmdCLI) ReadFoo(ctx context.Context, id string) (allsrv.Foo, error) {
return c.expectFoo(ctx, "read", id)
}
func (c *cmdCLI) UpdateFoo(ctx context.Context, f allsrv.FooUpd) (allsrv.Foo, error) {
args := []string{"--id", f.ID}
if f.Name != nil {
args = append(args, "--name", *f.Name)
}
if f.Note != nil {
args = append(args, "--note", *f.Note)
}
return c.expectFoo(ctx, "update", args...)
}
func (c *cmdCLI) DelFoo(ctx context.Context, id string) error {
_, err := c.execute(ctx, "rm", id)
return err
}
func (c *cmdCLI) expectFoo(ctx context.Context, op string, args ...string) (allsrv.Foo, error) {
b, err := c.execute(ctx, op, args...)
if err != nil {
return allsrv.Foo{}, err
}
var out allsrvc.Data[allsrvc.ResourceFooAttrs]
if err := json.Unmarshal(b, &out); err != nil {
return allsrv.Foo{}, err
}
return allsrv.DataToFoo(out), nil
}
func (c *cmdCLI) execute(ctx context.Context, op string, args ...string) ([]byte, error) {
cmd := newCmd()
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
cmd.SetArgs(append([]string{op, "--addr", c.addr}, args...))
err := cmd.ExecuteContext(ctx)
return buf.Bytes(), err
}