Skip to content

Commit

Permalink
fix: record MarshalJSON in case of default record with nullable field (
Browse files Browse the repository at this point in the history
  • Loading branch information
redaLaanait authored Sep 16, 2024
1 parent a6c674d commit 84f98c7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 7 additions & 1 deletion schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ import (
jsoniter "github.com/json-iterator/go"
)

var nullDefault = struct{}{}
type nullDefaultType struct{}

func (nullDefaultType) MarshalJSON() ([]byte, error) {
return []byte("null"), nil
}

var nullDefault nullDefaultType = struct{}{}

var (
schemaReserved = []string{
Expand Down
17 changes: 16 additions & 1 deletion schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,11 @@ func TestRecordSchema_ValidatesDefault(t *testing.T) {
schema: `{"type":"record", "name":"test", "namespace": "org.hamba.avro", "fields":[{"name": "a", "type": {"type":"record", "name": "test2", "fields":[{"name": "b", "type": "int"},{"name": "c", "type": "int", "default": 1}]}, "default": {"b": 1}}]}`,
wantErr: assert.NoError,
},
{
name: "Record With Nullable Field",
schema: `{"type":"record", "name":"test", "namespace": "org.hamba.avro", "fields":[{"name": "a", "type": {"type":"record", "name": "test2", "fields":[{"name": "b", "type": "int"},{"name": "c", "type": ["null","int"]}]}, "default": {"b": 1, "c": null}}]}`,
wantErr: assert.NoError,
},
{
name: "Record Not Map",
schema: `{"type":"record", "name":"test", "namespace": "org.hamba.avro", "fields":[{"name": "a", "type": {"type":"record", "name": "test2", "fields":[{"name": "b", "type": "int"},{"name": "c", "type": "int", "default": 1}]}, "default": "test"}]}`,
Expand All @@ -438,9 +443,19 @@ func TestRecordSchema_ValidatesDefault(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
t.Parallel()

_, err := avro.ParseWithCache(test.schema, "", &avro.SchemaCache{})
schema, err := avro.ParseWithCache(test.schema, "", &avro.SchemaCache{})

test.wantErr(t, err)
if err != nil {
return
}

// Ensure MarshalJSON Generate the same schema as it considers default values
b, err := schema.(*avro.RecordSchema).MarshalJSON()
assert.NoError(t, err)
schema2, err := avro.ParseWithCache(string(b), "", &avro.SchemaCache{})
assert.NoError(t, err)
assert.Equal(t, schema, schema2)
})
}
}
Expand Down

0 comments on commit 84f98c7

Please sign in to comment.