github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/decoder/adapters_test.go (about) 1 package decoder_test 2 3 import ( 4 "testing" 5 6 "github.com/abemedia/go-don/decoder" 7 "github.com/abemedia/httprouter" 8 "github.com/google/go-cmp/cmp" 9 "github.com/valyala/fasthttp" 10 ) 11 12 func TestAdapters(t *testing.T) { 13 t.Run("Map", func(t *testing.T) { 14 in := map[string][]string{"string": {"string"}} 15 testAdapter(t, decoder.Map(in)) 16 17 var m decoder.Map 18 if m.Get("test") != "" { 19 t.Error("should return empty string") 20 } 21 if m.Values("test") != nil { 22 t.Error("should return nil") 23 } 24 }) 25 26 t.Run("Args", func(t *testing.T) { 27 in := &fasthttp.Args{} 28 in.Add("string", "string") 29 testAdapter(t, (*decoder.Args)(in)) 30 }) 31 32 t.Run("Header", func(t *testing.T) { 33 in := &fasthttp.RequestHeader{} 34 in.Add("string", "string") 35 testAdapter(t, (*decoder.Header)(in)) 36 }) 37 38 t.Run("Params", func(t *testing.T) { 39 in := httprouter.Params{{Key: "string", Value: "string"}} 40 testAdapter(t, decoder.Params(in)) 41 }) 42 } 43 44 func testAdapter(t *testing.T, in decoder.Getter) { 45 t.Helper() 46 47 type item struct { 48 Zero string `field:"empty"` 49 Nil []string `field:"empty"` 50 String string `field:"string"` 51 Strings []string `field:"string"` 52 } 53 54 want := &item{ 55 String: "string", 56 Strings: []string{"string"}, 57 } 58 59 dec, err := decoder.NewCached(item{}, "field") 60 if err != nil { 61 t.Fatal(err) 62 } 63 64 got := &item{} 65 if err = dec.Decode(in, got); err != nil { 66 t.Fatal(err) 67 } 68 69 if diff := cmp.Diff(want, got); diff != "" { 70 t.Errorf(diff) 71 } 72 }