github.com/hamba/avro/v2@v2.22.1-0.20240518180522-aff3955acf7d/registry/decoder_test.go (about)

     1  package registry_test
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"testing"
     8  
     9  	"github.com/hamba/avro/v2/registry"
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestDecoder_Decode(t *testing.T) {
    15  	tests := []struct {
    16  		name    string
    17  		data    []byte
    18  		schema  string
    19  		want    int
    20  		wantErr require.ErrorAssertionFunc
    21  	}{
    22  		{
    23  			name:    "decodes data",
    24  			data:    []byte{0x0, 0x0, 0x0, 0x0, 0x2a, 0x80, 0x2},
    25  			schema:  `{"schema":"int"}`,
    26  			want:    128,
    27  			wantErr: require.NoError,
    28  		},
    29  		{
    30  			name:    "handles short data",
    31  			data:    []byte{0x0, 0x0, 0x0, 0x0, 0x2a},
    32  			schema:  `{"schema":"int"}`,
    33  			wantErr: require.Error,
    34  		},
    35  		{
    36  			name:    "handles bad magic",
    37  			data:    []byte{0x1, 0x0, 0x0, 0x0, 0x2a, 0x80, 0x2},
    38  			schema:  `{"schema":"int"}`,
    39  			wantErr: require.Error,
    40  		},
    41  		{
    42  			name:    "handles bad schema",
    43  			data:    []byte{0x0, 0x0, 0x0, 0x0, 0x2a, 0x80, 0x2},
    44  			schema:  `{"schema":"nope"}`,
    45  			wantErr: require.Error,
    46  		},
    47  	}
    48  
    49  	for _, test := range tests {
    50  		test := test
    51  		t.Run(test.name, func(t *testing.T) {
    52  			h := http.NewServeMux()
    53  			h.Handle("/schemas/ids/42", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
    54  				assert.Equal(t, "GET", req.Method)
    55  
    56  				_, _ = rw.Write([]byte(test.schema))
    57  			}))
    58  			srv := httptest.NewServer(h)
    59  			t.Cleanup(srv.Close)
    60  
    61  			client, _ := registry.NewClient(srv.URL)
    62  			decoder := registry.NewDecoder(client)
    63  
    64  			var got int
    65  			err := decoder.Decode(context.Background(), test.data, &got)
    66  
    67  			test.wantErr(t, err)
    68  			assert.Equal(t, test.want, got)
    69  		})
    70  	}
    71  }