1package openapi3 2 3import ( 4 "context" 5 "encoding/json" 6 "reflect" 7 "testing" 8 9 "github.com/stretchr/testify/require" 10) 11 12func TestEncodingJSON(t *testing.T) { 13 t.Log("Marshal *openapi3.Encoding to JSON") 14 data, err := json.Marshal(encoding()) 15 require.NoError(t, err) 16 require.NotEmpty(t, data) 17 18 t.Log("Unmarshal *openapi3.Encoding from JSON") 19 docA := &Encoding{} 20 err = json.Unmarshal(encodingJSON, &docA) 21 require.NoError(t, err) 22 require.NotEmpty(t, data) 23 24 t.Log("Validate *openapi3.Encoding") 25 err = docA.Validate(context.Background()) 26 require.NoError(t, err) 27 28 t.Log("Ensure representations match") 29 dataA, err := json.Marshal(docA) 30 require.NoError(t, err) 31 require.JSONEq(t, string(data), string(encodingJSON)) 32 require.JSONEq(t, string(data), string(dataA)) 33} 34 35var encodingJSON = []byte(` 36{ 37 "contentType": "application/json", 38 "headers": { 39 "someHeader": {} 40 }, 41 "style": "form", 42 "explode": true, 43 "allowReserved": true 44} 45`) 46 47func encoding() *Encoding { 48 explode := true 49 return &Encoding{ 50 ContentType: "application/json", 51 Headers: map[string]*HeaderRef{ 52 "someHeader": { 53 Value: &Header{}, 54 }, 55 }, 56 Style: "form", 57 Explode: &explode, 58 AllowReserved: true, 59 } 60} 61 62func TestEncodingSerializationMethod(t *testing.T) { 63 boolPtr := func(b bool) *bool { return &b } 64 testCases := []struct { 65 name string 66 enc *Encoding 67 want *SerializationMethod 68 }{ 69 { 70 name: "default", 71 want: &SerializationMethod{Style: SerializationForm, Explode: true}, 72 }, 73 { 74 name: "encoding with style", 75 enc: &Encoding{Style: SerializationSpaceDelimited}, 76 want: &SerializationMethod{Style: SerializationSpaceDelimited, Explode: true}, 77 }, 78 { 79 name: "encoding with explode", 80 enc: &Encoding{Explode: boolPtr(true)}, 81 want: &SerializationMethod{Style: SerializationForm, Explode: true}, 82 }, 83 { 84 name: "encoding with no explode", 85 enc: &Encoding{Explode: boolPtr(false)}, 86 want: &SerializationMethod{Style: SerializationForm, Explode: false}, 87 }, 88 { 89 name: "encoding with style and explode ", 90 enc: &Encoding{Style: SerializationSpaceDelimited, Explode: boolPtr(false)}, 91 want: &SerializationMethod{Style: SerializationSpaceDelimited, Explode: false}, 92 }, 93 } 94 for _, tc := range testCases { 95 t.Run(tc.name, func(t *testing.T) { 96 got := tc.enc.SerializationMethod() 97 require.True(t, reflect.DeepEqual(got, tc.want), "got %#v, want %#v", got, tc.want) 98 }) 99 } 100} 101