1
2
3
4
5 package defval_test
6
7 import (
8 "math"
9 "reflect"
10 "testing"
11
12 "google.golang.org/protobuf/internal/encoding/defval"
13 "google.golang.org/protobuf/internal/filedesc"
14 "google.golang.org/protobuf/reflect/protoreflect"
15 )
16
17 func Test(t *testing.T) {
18 evs := filedesc.EnumValues{List: []filedesc.EnumValue{{}}}
19 evs.List[0].L0.ParentFile = filedesc.SurrogateProto2
20 evs.List[0].L0.FullName = "ALPHA"
21 evs.List[0].L1.Number = 1
22
23 V := protoreflect.ValueOf
24 tests := []struct {
25 val protoreflect.Value
26 enum protoreflect.EnumValueDescriptor
27 enums protoreflect.EnumValueDescriptors
28 kind protoreflect.Kind
29 strPB string
30 strGo string
31 }{{
32 val: V(bool(true)),
33 enum: nil,
34 enums: nil,
35 kind: protoreflect.BoolKind,
36 strPB: "true",
37 strGo: "1",
38 }, {
39 val: V(int32(-0x1234)),
40 enum: nil,
41 enums: nil,
42 kind: protoreflect.Int32Kind,
43 strPB: "-4660",
44 strGo: "-4660",
45 }, {
46 val: V(float32(math.Pi)),
47 enum: nil,
48 enums: nil,
49 kind: protoreflect.FloatKind,
50 strPB: "3.1415927",
51 strGo: "3.1415927",
52 }, {
53 val: V(float64(math.Pi)),
54 enum: nil,
55 enums: nil,
56 kind: protoreflect.DoubleKind,
57 strPB: "3.141592653589793",
58 strGo: "3.141592653589793",
59 }, {
60 val: V(string("hello, \xde\xad\xbe\xef\n")),
61 enum: nil,
62 enums: nil,
63 kind: protoreflect.StringKind,
64 strPB: "hello, \xde\xad\xbe\xef\n",
65 strGo: "hello, \xde\xad\xbe\xef\n",
66 }, {
67 val: V([]byte("hello, \xde\xad\xbe\xef\n")),
68 enum: nil,
69 enums: nil,
70 kind: protoreflect.BytesKind,
71 strPB: "hello, \\336\\255\\276\\357\\n",
72 strGo: "hello, \\336\\255\\276\\357\\n",
73 }, {
74 val: V(protoreflect.EnumNumber(1)),
75 enum: &evs.List[0],
76 enums: &evs,
77 kind: protoreflect.EnumKind,
78 strPB: "ALPHA",
79 strGo: "1",
80 }}
81
82 for _, tt := range tests {
83 t.Run("", func(t *testing.T) {
84 gotStr, _ := defval.Marshal(tt.val, tt.enum, tt.kind, defval.Descriptor)
85 if gotStr != tt.strPB {
86 t.Errorf("Marshal(%v, %v, Descriptor) = %q, want %q", tt.val, tt.kind, gotStr, tt.strPB)
87 }
88
89 gotStr, _ = defval.Marshal(tt.val, tt.enum, tt.kind, defval.GoTag)
90 if gotStr != tt.strGo {
91 t.Errorf("Marshal(%v, %v, GoTag) = %q, want %q", tt.val, tt.kind, gotStr, tt.strGo)
92 }
93
94 gotVal, gotEnum, _ := defval.Unmarshal(tt.strPB, tt.kind, tt.enums, defval.Descriptor)
95 if !reflect.DeepEqual(gotVal.Interface(), tt.val.Interface()) || gotEnum != tt.enum {
96 t.Errorf("Unmarshal(%v, %v, Descriptor) = (%q, %v), want (%q, %v)", tt.strPB, tt.kind, gotVal, gotEnum, tt.val, tt.enum)
97 }
98
99 gotVal, gotEnum, _ = defval.Unmarshal(tt.strGo, tt.kind, tt.enums, defval.GoTag)
100 if !reflect.DeepEqual(gotVal.Interface(), tt.val.Interface()) || gotEnum != tt.enum {
101 t.Errorf("Unmarshal(%v, %v, GoTag) = (%q, %v), want (%q, %v)", tt.strGo, tt.kind, gotVal, gotEnum, tt.val, tt.enum)
102 }
103 })
104 }
105 }
106
View as plain text