github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/encoding/decode_test.go (about)

     1  package encoding_test
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"reflect"
     7  	"testing"
     8  
     9  	"github.com/abemedia/go-don/encoding"
    10  	"github.com/abemedia/go-don/pkg/httptest"
    11  	"github.com/valyala/fasthttp"
    12  )
    13  
    14  func TestRegisterDecoder(t *testing.T) {
    15  	t.Run("Unmarshaler", func(t *testing.T) {
    16  		testRegisterDecoder(t, func(data []byte, v any) error {
    17  			if len(data) == 0 {
    18  				return io.EOF
    19  			}
    20  			reflect.ValueOf(v).Elem().SetBytes(data)
    21  			return nil
    22  		}, "unmarshaler", "unmarshaler-alias")
    23  	})
    24  
    25  	t.Run("ContextUnmarshaler", func(t *testing.T) {
    26  		testRegisterDecoder(t, func(ctx context.Context, data []byte, v any) error {
    27  			if len(data) == 0 {
    28  				return io.EOF
    29  			}
    30  			reflect.ValueOf(v).Elem().SetBytes(data)
    31  			return nil
    32  		}, "context-unmarshaler", "context-unmarshaler-alias")
    33  	})
    34  
    35  	t.Run("RequestParser", func(t *testing.T) {
    36  		testRegisterDecoder(t, func(ctx *fasthttp.RequestCtx, v any) error {
    37  			b := ctx.Request.Body()
    38  			if len(b) == 0 {
    39  				return io.EOF
    40  			}
    41  			reflect.ValueOf(v).Elem().SetBytes(b)
    42  			return nil
    43  		}, "request-parser", "request-parser-alias")
    44  	})
    45  }
    46  
    47  func testRegisterDecoder[T encoding.DecoderConstraint](t *testing.T, dec T, contentType, alias string) {
    48  	t.Helper()
    49  
    50  	encoding.RegisterDecoder(dec, contentType, alias)
    51  
    52  	for _, v := range []string{contentType, alias} {
    53  		decode := encoding.GetDecoder(v)
    54  		if decode == nil {
    55  			t.Error("decoder not found")
    56  			continue
    57  		}
    58  
    59  		req := httptest.NewRequest("", "", v, nil)
    60  
    61  		var b []byte
    62  		if err := decode(req, &b); err != nil {
    63  			t.Error(err)
    64  		} else if string(b) != v {
    65  			t.Error("should decode request")
    66  		}
    67  
    68  		req.Request.SetBody(nil)
    69  		if err := decode(req, &b); err == nil {
    70  			t.Error("should return error")
    71  		}
    72  	}
    73  }