github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/transformer/z_tsfm_protobuf_test.go (about)

     1  package transformer_test
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"net/http"
     7  	"reflect"
     8  	"testing"
     9  
    10  	"github.com/golang/protobuf/proto"
    11  	. "github.com/onsi/gomega"
    12  
    13  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx"
    14  	. "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/transformer"
    15  	testdatapb "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/transformer/testdata"
    16  	"github.com/machinefi/w3bstream/pkg/depends/x/typesx"
    17  )
    18  
    19  func TestProtobuf(t *testing.T) {
    20  	data := testdatapb.Event{}
    21  
    22  	ct, _ := DefaultFactory.NewTransformer(
    23  		bgctx,
    24  		typesx.FromReflectType(reflect.TypeOf(data)),
    25  		Option{MIME: "protobuf"},
    26  	)
    27  
    28  	t.Run("EncodeTo", func(t *testing.T) {
    29  		b := bytes.NewBuffer(nil)
    30  		h := http.Header{}
    31  
    32  		err := ct.EncodeTo(context.Background(), WriterWithHeader(b, h), &data)
    33  		NewWithT(t).Expect(err).To(BeNil())
    34  		NewWithT(t).Expect(h.Get(httpx.HeaderContentType)).To(Equal("application/x-protobuf"))
    35  
    36  		err = ct.EncodeTo(context.Background(), WriterWithHeader(b, h), struct{}{})
    37  		NewWithT(t).Expect(err).To(Equal(ErrEncodeDataNotProtobuf))
    38  
    39  		err = ct.EncodeTo(context.Background(), WriterWithHeader(b, h), data)
    40  		NewWithT(t).Expect(err).To(Equal(ErrEncodeDataNotProtobuf))
    41  	})
    42  
    43  	t.Run("DecodeFrom", func(t *testing.T) {
    44  		ori := testdatapb.Event{
    45  			Header:  &testdatapb.Header{EventType: "mock_type"},
    46  			Payload: []byte(`{"key":"value"}`),
    47  		}
    48  
    49  		raw, err := proto.Marshal(&ori)
    50  		NewWithT(t).Expect(err).To(BeNil())
    51  
    52  		b := bytes.NewBuffer(raw)
    53  		decoded := testdatapb.Event{}
    54  		err = ct.DecodeFrom(context.Background(), b, &decoded)
    55  		NewWithT(t).Expect(err).To(BeNil())
    56  		NewWithT(t).Expect(decoded.Header.EventType).To(Equal(ori.Header.EventType))
    57  		NewWithT(t).Expect(decoded.Payload).To(Equal(ori.Payload))
    58  
    59  		err = ct.DecodeFrom(context.Background(), b, decoded)
    60  		NewWithT(t).Expect(err).To(Equal(ErrDecodeTargetNotProtobuf))
    61  
    62  		err = ct.DecodeFrom(context.Background(), b, struct{}{})
    63  		NewWithT(t).Expect(err).To(Equal(ErrDecodeTargetNotProtobuf))
    64  	})
    65  
    66  }