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