github.com/cosmos/cosmos-proto@v1.0.0-beta.3/testpb/clear_test.go (about)

     1  package testpb
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/require"
     7  	"google.golang.org/protobuf/proto"
     8  	"google.golang.org/protobuf/types/dynamicpb"
     9  	"google.golang.org/protobuf/types/known/anypb"
    10  )
    11  
    12  func TestClear(t *testing.T) {
    13  	t.Run("clear all", func(t *testing.T) {
    14  		m := &A{
    15  			Enum:        Enumeration_Two,
    16  			SomeBoolean: true,
    17  			INT32:       1,
    18  			SINT32:      2,
    19  			UINT32:      3,
    20  			INT64:       4,
    21  			SING64:      5,
    22  			UINT64:      6,
    23  			SFIXED32:    7,
    24  			FIXED32:     8,
    25  			FLOAT:       9,
    26  			SFIXED64:    10,
    27  			FIXED64:     11,
    28  			DOUBLE:      12,
    29  			STRING:      "a string",
    30  			BYTES:       []byte("test bytes"),
    31  			MESSAGE: &B{
    32  				X: "something else",
    33  			},
    34  			MAP:       map[string]*B{"item": {X: "inside_map_item"}},
    35  			LIST:      []*B{{X: "part of list"}},
    36  			ONEOF:     &A_ONEOF_B{ONEOF_B: &B{X: "1"}},
    37  			LIST_ENUM: []Enumeration{Enumeration_One, Enumeration_One},
    38  		}
    39  
    40  		dyn := dynamicpb.NewMessage(m.ProtoReflect().Descriptor())
    41  
    42  		b, err := proto.MarshalOptions{}.Marshal(m)
    43  		require.NoError(t, err)
    44  		require.NoError(t, proto.Unmarshal(b, dyn))
    45  
    46  		for i := 0; i < md_A.Fields().Len(); i++ {
    47  			fd := md_A.Fields().Get(i)
    48  
    49  			m.ProtoReflect().Clear(fd)
    50  			dyn.Clear(fd)
    51  
    52  			require.Equal(t, dyn.Has(fd), m.ProtoReflect().Has(fd), fd.FullName())
    53  		}
    54  	})
    55  
    56  	t.Run("unknown field descriptor", func(t *testing.T) {
    57  		m := &A{}
    58  
    59  		require.Panics(t, func() {
    60  			m.ProtoReflect().Clear((&anypb.Any{}).ProtoReflect().Descriptor().Fields().Get(0))
    61  		})
    62  	})
    63  }