github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/encoding/text/decode_test.go (about) 1 package text_test 2 3 import ( 4 "errors" 5 "io" 6 "reflect" 7 "strconv" 8 "testing" 9 10 "github.com/abemedia/go-don" 11 "github.com/abemedia/go-don/encoding" 12 "github.com/abemedia/go-don/pkg/httptest" 13 "github.com/google/go-cmp/cmp" 14 "github.com/valyala/fasthttp" 15 ) 16 17 func TestDecode(t *testing.T) { 18 tests := []struct { 19 in string 20 want any 21 }{ 22 {" \n", ""}, 23 {"test\n", "test"}, 24 {"test\n", []byte("test")}, 25 {"5\n", int(5)}, 26 {"5\n", int8(5)}, 27 {"5\n", int16(5)}, 28 {"5\n", int32(5)}, 29 {"5\n", int64(5)}, 30 {"5\n", uint(5)}, 31 {"5\n", uint8(5)}, 32 {"5\n", uint16(5)}, 33 {"5\n", uint32(5)}, 34 {"5\n", uint64(5)}, 35 {"5.1\n", float32(5.1)}, 36 {"5.1\n", float64(5.1)}, 37 {"true\n", true}, 38 {"test\n", unmarshaler{S: "test"}}, 39 {"test\n", unmarshaler{S: "test"}}, // Test cached unmarshaler. 40 {"test\n", &unmarshaler{S: "test"}}, 41 } 42 43 dec := encoding.GetDecoder("text/plain") 44 if dec == nil { 45 t.Fatal("decoder not found") 46 } 47 48 for _, test := range tests { 49 ctx := httptest.NewRequest(fasthttp.MethodGet, "/", test.in, nil) 50 v := reflect.New(reflect.TypeOf(test.want)).Interface() 51 if err := dec(ctx, v); err != nil { 52 t.Error(err) 53 } else { 54 if diff := cmp.Diff(test.want, reflect.ValueOf(v).Elem().Interface()); diff != "" { 55 t.Errorf("%T: %s", test.want, diff) 56 } 57 } 58 } 59 } 60 61 func TestDecodeError(t *testing.T) { 62 tests := []struct { 63 in string 64 val any 65 want error 66 }{ 67 {"test\n", &struct{}{}, don.ErrUnsupportedMediaType}, 68 {"test\n", ptr(0), strconv.ErrSyntax}, 69 {"test\n", &unmarshaler{Err: io.EOF}, io.EOF}, 70 } 71 72 dec := encoding.GetDecoder("text/plain") 73 if dec == nil { 74 t.Fatal("decoder not found") 75 } 76 77 for _, test := range tests { 78 ctx := httptest.NewRequest(fasthttp.MethodGet, "/", test.in, nil) 79 if err := dec(ctx, test.val); err == nil { 80 t.Error("should return error") 81 } else if !errors.Is(err, test.want) { 82 t.Errorf("should return error %q, got %q", test.want, err) 83 } 84 } 85 } 86 87 func ptr[T any](v T) *T { 88 return &v 89 } 90 91 type unmarshaler struct { 92 S string 93 Err error 94 } 95 96 func (m *unmarshaler) UnmarshalText(text []byte) error { 97 if m.Err != nil { 98 return m.Err 99 } 100 m.S = string(text) 101 return nil 102 }