github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/handler_test.go (about)

     1  // Copyright 2021 Edward McFarlane. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package larking
     6  
     7  import (
     8  	"context"
     9  	"encoding/json"
    10  	"fmt"
    11  	"io/ioutil"
    12  	"net/http"
    13  	"net/http/httptest"
    14  	"strings"
    15  	"testing"
    16  
    17  	"github.com/emcfarlane/larking/testpb"
    18  	"github.com/google/go-cmp/cmp"
    19  	"google.golang.org/grpc"
    20  	"google.golang.org/grpc/metadata"
    21  	"google.golang.org/protobuf/proto"
    22  	"google.golang.org/protobuf/testing/protocmp"
    23  )
    24  
    25  func TestHandler(t *testing.T) {
    26  	ms := &testpb.UnimplementedMessagingServer{}
    27  
    28  	req := httptest.NewRequest(http.MethodPatch, "/v1/messages/msg_123", strings.NewReader(
    29  		`{ "text": "Hi!" }`,
    30  	))
    31  	req.Header.Set("Content-Type", "application/json")
    32  
    33  	interceptor := func(
    34  		ctx context.Context,
    35  		req interface{},
    36  		info *grpc.UnaryServerInfo,
    37  		_ grpc.UnaryHandler,
    38  	) (interface{}, error) {
    39  		_, ok := metadata.FromIncomingContext(ctx)
    40  		if !ok {
    41  			return nil, fmt.Errorf("missing context metadata")
    42  		}
    43  
    44  		if info.FullMethod != "/larking.testpb.Messaging/UpdateMessage" {
    45  			return nil, fmt.Errorf("invalid method %s", info.FullMethod)
    46  		}
    47  
    48  		in := req.(proto.Message)
    49  		want := &testpb.UpdateMessageRequestOne{
    50  			MessageId: "msg_123",
    51  			Message: &testpb.Message{
    52  				Text: "Hi!",
    53  			},
    54  		}
    55  
    56  		if !proto.Equal(want, in) {
    57  			diff := cmp.Diff(in, want, protocmp.Transform())
    58  			t.Fatal(diff)
    59  			return nil, fmt.Errorf("unexpected message")
    60  		}
    61  		return &testpb.Message{Text: "hello, patch!"}, nil
    62  	}
    63  
    64  	m, err := NewMux(UnaryServerInterceptorOption(interceptor))
    65  	if err != nil {
    66  		t.Fatal(err)
    67  	}
    68  	testpb.RegisterMessagingServer(m, ms)
    69  
    70  	w := httptest.NewRecorder()
    71  
    72  	m.ServeHTTP(w, req)
    73  	t.Log(w)
    74  	r := w.Result()
    75  	if r.StatusCode != 200 {
    76  		t.Fatal(r.Status)
    77  	}
    78  
    79  	data, err := ioutil.ReadAll(r.Body)
    80  	if err != nil {
    81  		t.Fatal(err)
    82  	}
    83  	t.Log(string(data))
    84  
    85  	rsp := &testpb.Message{}
    86  	if err := json.Unmarshal(data, rsp); err != nil {
    87  		t.Fatal(err)
    88  	}
    89  	want := &testpb.Message{Text: "hello, patch!"}
    90  
    91  	if !proto.Equal(want, rsp) {
    92  		t.Fatal(cmp.Diff(rsp, want, protocmp.Transform()))
    93  	}
    94  }