Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions compiler/cpp/src/thrift/generate/t_go_generator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1768,6 +1768,11 @@ void t_go_generator::generate_countsetfields_helper(ostream& out,
out << indent() << "func (p *" << tstruct_name << ") CountSetFields" << tstruct_name << "() int {"
<< '\n';
indent_up();
out << indent() << "if p == nil {" << '\n';
indent_up();
out << indent() << "return 0" << '\n';
indent_down();
out << indent() << "}" << '\n';
out << indent() << "count := 0" << '\n';
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
if ((*f_iter)->get_req() == t_field::T_REQUIRED)
Expand Down
5 changes: 5 additions & 0 deletions lib/go/test/UnionDefaultValueTest.thrift
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,8 @@ union Descendant {
struct TestStruct {
1: optional Descendant descendant = { "option1": {}}
}

struct StructWithUnsetUnion {
1: required bool f_1 = 1,
2: Descendant f_2,
}
33 changes: 33 additions & 0 deletions lib/go/test/tests/union_default_value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
package tests

import (
"context"
"strings"
"testing"

"github.com/apache/thrift/lib/go/test/gopath/src/uniondefaultvaluetest"
"github.com/apache/thrift/lib/go/thrift"
)

func TestUnionDefaultValue(t *testing.T) {
Expand All @@ -32,3 +35,33 @@ func TestUnionDefaultValue(t *testing.T) {
t.Error("Default Union value not set!")
}
}

func TestNilUnion(t *testing.T) {
var d *uniondefaultvaluetest.Descendant
if count := d.CountSetFieldsDescendant(); count != 0 {
t.Errorf("Expected 0 set fields for nil union, got %d", count)
}

proto := thrift.NewTBinaryProtocolConf(thrift.NewTMemoryBuffer(), nil)
err := d.Write(context.Background(), proto)
if err == nil {
t.Error("Expected error when writing nil union, got nil")
}
}

func TestStructWithUnsetUnion(t *testing.T) {
s := uniondefaultvaluetest.NewStructWithUnsetUnion()
buf := thrift.NewTMemoryBuffer()
proto := thrift.NewTBinaryProtocolConf(buf, nil)

// Writing a struct whose union field is nil used to dereference the nil
// receiver inside CountSetFields and panic. It now reports which union
// could not be written instead.
err := s.Write(context.Background(), proto)
if err == nil {
t.Fatal("Expected an error writing a struct with an unset union, got nil")
}
if !strings.Contains(err.Error(), "exactly one field must be set") {
t.Errorf("Expected the union arity error, got %v", err)
}
}
Loading