|
| 1 | +package runtime_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "io/ioutil" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/golang/protobuf/proto" |
| 11 | + pb "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb" |
| 12 | + "github.com/grpc-ecosystem/grpc-gateway/runtime" |
| 13 | + "golang.org/x/net/context" |
| 14 | +) |
| 15 | + |
| 16 | +func TestForwardResponseStream(t *testing.T) { |
| 17 | + var ( |
| 18 | + msgs = []proto.Message{ |
| 19 | + &pb.SimpleMessage{Id: "One"}, |
| 20 | + &pb.SimpleMessage{Id: "Two"}, |
| 21 | + } |
| 22 | + |
| 23 | + ctx = runtime.NewServerMetadataContext( |
| 24 | + context.Background(), runtime.ServerMetadata{}, |
| 25 | + ) |
| 26 | + mux = runtime.NewServeMux() |
| 27 | + marshaler = &runtime.JSONPb{} |
| 28 | + req = httptest.NewRequest("GET", "http://example.com/foo", nil) |
| 29 | + resp = httptest.NewRecorder() |
| 30 | + count = 0 |
| 31 | + recv = func() (proto.Message, error) { |
| 32 | + if count >= len(msgs) { |
| 33 | + return nil, io.EOF |
| 34 | + } |
| 35 | + count++ |
| 36 | + return msgs[count-1], nil |
| 37 | + } |
| 38 | + ) |
| 39 | + |
| 40 | + runtime.ForwardResponseStream(ctx, mux, marshaler, resp, req, recv) |
| 41 | + |
| 42 | + w := resp.Result() |
| 43 | + if w.StatusCode != http.StatusOK { |
| 44 | + t.Errorf(" got %d want %d", w.StatusCode, http.StatusOK) |
| 45 | + } |
| 46 | + if h := w.Header.Get("Transfer-Encoding"); h != "chunked" { |
| 47 | + t.Errorf("ForwardResponseStream missing header chunked") |
| 48 | + } |
| 49 | + body, err := ioutil.ReadAll(w.Body) |
| 50 | + if err != nil { |
| 51 | + t.Errorf("Failed to read response body with %v", err) |
| 52 | + } |
| 53 | + w.Body.Close() |
| 54 | + |
| 55 | + var want []byte |
| 56 | + for _, msg := range msgs { |
| 57 | + b, err := marshaler.Marshal(map[string]proto.Message{"result": msg}) |
| 58 | + if err != nil { |
| 59 | + t.Errorf("marshaler.Marshal() failed %v", err) |
| 60 | + } |
| 61 | + want = append(want, b...) |
| 62 | + } |
| 63 | + |
| 64 | + if string(body) != string(want) { |
| 65 | + t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want) |
| 66 | + } |
| 67 | +} |
0 commit comments