Skip to content

Commit

Permalink
Merge pull request #58 from k1LoW/allow-any
Browse files Browse the repository at this point in the history
Response() supports accepting any value
  • Loading branch information
k1LoW authored Sep 25, 2023
2 parents 6fb2a8e + 989c335 commit 1efdb0a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
21 changes: 19 additions & 2 deletions grpcstub.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ type matcher struct {
matchFuncs []matchFunc
handler handlerFunc
requests []*Request
t *testing.T
mu sync.RWMutex
}

Expand Down Expand Up @@ -283,6 +284,7 @@ func (s *Server) startServer() {
func (s *Server) Match(fn func(r *Request) bool) *matcher {
m := &matcher{
matchFuncs: []matchFunc{fn},
t: s.t,
}
s.mu.Lock()
defer s.mu.Unlock()
Expand All @@ -305,6 +307,7 @@ func (s *Server) Service(service string) *matcher {
fn := serviceMatchFunc(service)
m := &matcher{
matchFuncs: []matchFunc{fn},
t: s.t,
}
s.matchers = append(s.matchers, m)
return m
Expand Down Expand Up @@ -336,6 +339,7 @@ func (s *Server) Method(method string) *matcher {
fn := methodMatchFunc(method)
m := &matcher{
matchFuncs: []matchFunc{fn},
t: s.t,
}
s.matchers = append(s.matchers, m)
return m
Expand Down Expand Up @@ -400,7 +404,20 @@ func (m *matcher) Handler(fn func(r *Request) *Response) {
}

// Response set handler which return response.
func (m *matcher) Response(message map[string]any) *matcher {
func (m *matcher) Response(message any) *matcher {
mm := map[string]any{}
switch v := message.(type) {
case map[string]any:
mm = v
default:
b, err := json.Marshal(v)
if err != nil {
m.t.Fatalf("failed to convert message: %v", err)
}
if err := json.Unmarshal(b, &mm); err != nil {
m.t.Fatalf("failed to convert message: %v", err)
}
}
prev := m.handler
m.handler = func(r *Request, md protoreflect.MethodDescriptor) *Response {
var res *Response
Expand All @@ -409,7 +426,7 @@ func (m *matcher) Response(message map[string]any) *matcher {
} else {
res = prev(r, md)
}
res.Messages = append(res.Messages, message)
res.Messages = append(res.Messages, mm)
return res
}
return m
Expand Down
24 changes: 24 additions & 0 deletions grpcstub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -656,3 +656,27 @@ func TestRequestStringer(t *testing.T) {
})
}
}

func TestResponseAny(t *testing.T) {
ctx := context.Background()
ts := NewServer(t, "testdata/route_guide.proto")
t.Cleanup(func() {
ts.Close()
})
ts.Service("routeguide.RouteGuide").Method("GetFeature").Response(&routeguide.Feature{
Name: "hello",
})

client := routeguide.NewRouteGuideClient(ts.Conn())
res, err := client.GetFeature(ctx, &routeguide.Point{
Latitude: 10,
Longitude: 13,
})
if err != nil {
t.Fatal(err)
}
got := res.Name
if want := "hello"; got != want {
t.Errorf("got %v\nwant %v", got, want)
}
}

0 comments on commit 1efdb0a

Please sign in to comment.