github.com/hamba/avro@v1.8.0/encoder_array_test.go (about)

     1  package avro_test
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  
     7  	"github.com/hamba/avro"
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestEncoder_ArrayInvalidType(t *testing.T) {
    12  	defer ConfigTeardown()
    13  
    14  	schema := `{"type":"array", "items": "int"}`
    15  	buf := bytes.NewBuffer([]byte{})
    16  	enc, err := avro.NewEncoder(schema, buf)
    17  	assert.NoError(t, err)
    18  
    19  	err = enc.Encode("test")
    20  
    21  	assert.Error(t, err)
    22  }
    23  
    24  func TestEncoder_Array(t *testing.T) {
    25  	defer ConfigTeardown()
    26  
    27  	schema := `{"type":"array", "items": "int"}`
    28  	buf := bytes.NewBuffer([]byte{})
    29  	enc, err := avro.NewEncoder(schema, buf)
    30  	assert.NoError(t, err)
    31  
    32  	err = enc.Encode([]int{27, 28})
    33  
    34  	assert.NoError(t, err)
    35  	assert.Equal(t, []byte{0x03, 0x04, 0x36, 0x38, 0x0}, buf.Bytes())
    36  }
    37  
    38  func TestEncoder_ArrayEmpty(t *testing.T) {
    39  	defer ConfigTeardown()
    40  
    41  	schema := `{"type":"array", "items": "int"}`
    42  	buf := bytes.NewBuffer([]byte{})
    43  	enc, err := avro.NewEncoder(schema, buf)
    44  	assert.NoError(t, err)
    45  
    46  	err = enc.Encode([]int{})
    47  
    48  	assert.NoError(t, err)
    49  	assert.Equal(t, []byte{0x0}, buf.Bytes())
    50  }
    51  
    52  func TestEncoder_ArrayOfStruct(t *testing.T) {
    53  	defer ConfigTeardown()
    54  
    55  	schema := `{"type":"array", "items": {"type": "record", "name": "test", "fields" : [{"name": "a", "type": "long"}, {"name": "b", "type": "string"}]}}`
    56  	buf := bytes.NewBuffer([]byte{})
    57  	enc, err := avro.NewEncoder(schema, buf)
    58  	assert.NoError(t, err)
    59  
    60  	err = enc.Encode([]TestRecord{{A: 27, B: "foo"}, {A: 27, B: "foo"}})
    61  
    62  	assert.NoError(t, err)
    63  	assert.Equal(t, []byte{0x03, 0x14, 0x36, 0x06, 0x66, 0x6f, 0x6f, 0x36, 0x06, 0x66, 0x6f, 0x6f, 0x0}, buf.Bytes())
    64  }
    65  
    66  func TestEncoder_ArrayError(t *testing.T) {
    67  	defer ConfigTeardown()
    68  
    69  	schema := `{"type":"array", "items": "int"}`
    70  	buf := bytes.NewBuffer([]byte{})
    71  	enc, err := avro.NewEncoder(schema, buf)
    72  	assert.NoError(t, err)
    73  
    74  	err = enc.Encode([]string{"foo", "bar"})
    75  
    76  	assert.Error(t, err)
    77  }