github.com/hamba/avro@v1.8.0/encoder_fixed_test.go (about) 1 package avro_test 2 3 import ( 4 "bytes" 5 "math/big" 6 "testing" 7 8 "github.com/hamba/avro" 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestEncoder_FixedInvalidType(t *testing.T) { 13 defer ConfigTeardown() 14 15 schema := `{"type":"fixed", "name": "test", "size": 6}` 16 buf := bytes.NewBuffer([]byte{}) 17 enc, err := avro.NewEncoder(schema, buf) 18 assert.NoError(t, err) 19 20 err = enc.Encode([6]int{}) 21 22 assert.Error(t, err) 23 } 24 25 func TestEncoder_Fixed(t *testing.T) { 26 defer ConfigTeardown() 27 28 schema := `{"type":"fixed", "name": "test", "size": 6}` 29 buf := bytes.NewBuffer([]byte{}) 30 enc, err := avro.NewEncoder(schema, buf) 31 assert.NoError(t, err) 32 33 err = enc.Encode([6]byte{'f', 'o', 'o', 'f', 'o', 'o'}) 34 35 assert.NoError(t, err) 36 assert.Equal(t, []byte{0x66, 0x6F, 0x6F, 0x66, 0x6F, 0x6F}, buf.Bytes()) 37 } 38 39 func TestEncoder_FixedRat_Positive(t *testing.T) { 40 defer ConfigTeardown() 41 42 schema := `{"type":"fixed", "name": "test", "size": 6,"logicalType":"decimal","precision":4,"scale":2}` 43 buf := bytes.NewBuffer([]byte{}) 44 enc, err := avro.NewEncoder(schema, buf) 45 assert.NoError(t, err) 46 47 err = enc.Encode(big.NewRat(1734, 5)) 48 49 assert.NoError(t, err) 50 assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00, 0x87, 0x78}, buf.Bytes()) 51 } 52 53 func TestEncoder_FixedRat_Negative(t *testing.T) { 54 defer ConfigTeardown() 55 56 schema := `{"type":"fixed", "name": "test", "size": 6, "logicalType":"decimal","precision":4,"scale":2}` 57 buf := bytes.NewBuffer([]byte{}) 58 enc, err := avro.NewEncoder(schema, buf) 59 assert.NoError(t, err) 60 61 err = enc.Encode(big.NewRat(-1734, 5)) 62 63 assert.NoError(t, err) 64 assert.Equal(t, []byte{0xFF, 0xFF, 0xFF, 0xFF, 0x78, 0x88}, buf.Bytes()) 65 } 66 67 func TestEncoder_FixedRat_Zero(t *testing.T) { 68 defer ConfigTeardown() 69 70 schema := `{"type":"fixed", "name": "test", "size": 6,"logicalType":"decimal","precision":4,"scale":2}` 71 buf := bytes.NewBuffer([]byte{}) 72 enc, err := avro.NewEncoder(schema, buf) 73 assert.NoError(t, err) 74 75 err = enc.Encode(big.NewRat(0, 1)) 76 77 assert.NoError(t, err) 78 assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, buf.Bytes()) 79 } 80 81 func TestEncoder_FixedRatInvalidLogicalSchema(t *testing.T) { 82 defer ConfigTeardown() 83 84 schema := `{"type":"fixed", "name": "test", "size": 6}` 85 buf := bytes.NewBuffer([]byte{}) 86 enc, err := avro.NewEncoder(schema, buf) 87 assert.NoError(t, err) 88 89 err = enc.Encode(big.NewRat(1734, 5)) 90 91 assert.Error(t, err) 92 }