-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapi_test.go
More file actions
97 lines (75 loc) · 1.95 KB
/
Copy pathapi_test.go
File metadata and controls
97 lines (75 loc) · 1.95 KB
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
package api_test
import (
"strings"
"testing"
"github.com/Aize-Public/forego/api"
"github.com/Aize-Public/forego/ctx"
"github.com/Aize-Public/forego/enc"
"github.com/Aize-Public/forego/test"
)
func TestRequired(t *testing.T) {
c := test.Context(t)
t.Logf("handler...")
h, err := api.NewHandler(c, &WordCount{})
test.NoError(t, err)
ser := h.Server()
data := &api.JSON{}
data.Data = enc.Map{} // empty request should give a 400
data.UID, _ = enc.Marshal(c, UID("alice"))
t.Logf("server recv...")
_, err = ser.Recv(c, data)
test.Error(t, err)
}
func TestAPI(t *testing.T) {
c := test.Context(t)
alice := UID("alice")
t.Logf("handler...")
h, err := api.NewHandler(c, &WordCount{})
test.NoError(t, err)
ser := h.Server()
cli := h.Client()
obj := WordCount{
Str: "foo bar",
}
data := &api.JSON{}
t.Logf("client send...")
err = cli.Send(c, &obj, data)
test.NoError(t, err)
t.Logf("request: %s", data.Data)
test.NotEmpty(t, data.Data)
t.Logf("auth...")
// as example, we just inject a string here, implementation should use
// jwt tokens or other authentication mechanism, and place the
// encoded result in the .UID field here
data.UID, _ = enc.Marshal(c, alice)
{
t.Logf("server recv...")
obj, err := ser.Recv(c, data)
test.NoError(t, err)
test.NotEmpty(t, obj)
test.EqualsJSON(c, alice, obj.UID)
t.Logf("Foo()ing...")
err = obj.Do(c)
test.NoError(t, err)
t.Logf("server send...")
data = &api.JSON{} // clean up
err = ser.Send(c, obj, data)
test.NoError(t, err)
t.Logf("response: %s", data.Data)
}
t.Logf("client recv...")
err = cli.Recv(c, data, &obj)
test.NoError(t, err)
test.Assert(t, obj.Ct == 2)
}
type UID string
type WordCount struct {
R api.Request `url:"/wc"`
UID UID `api:"auth,required" json:"uid"`
Str string `api:"in,required" json:"str"`
Ct int `api:"out" json:"ct"`
}
func (this *WordCount) Do(ctx.C) error {
this.Ct = len(strings.Fields(this.Str))
return nil
}