How to use String method of proto Package

Best Rod code snippet using proto.String

text_test.go

Source:text_test.go Github

copy

Full Screen

...64 ResultCount: 47,65 Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb},66 }67 m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}68 any1 := &pb2.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}69 proto.SetExtension(any1, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("foo")})70 proto.SetExtension(any1, pb2.E_Ext_Text, proto.String("bar"))71 any1b, err := proto.Marshal(any1)72 if err != nil {73 panic(err)74 }75 any2 := &pb2.MyMessage{Count: proto.Int32(42), Bikeshed: pb2.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}}76 proto.SetExtension(any2, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("baz")})77 any2b, err := proto.Marshal(any2)78 if err != nil {79 panic(err)80 }81 m6 := &pb3.Message{82 Name: "David",83 ResultCount: 47,84 Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},85 ManyThings: []*anypb.Any{86 &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b},87 &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},88 },89 }90 const (91 m1Golden = `92name: "David"93result_count: 4794anything: <95 [type.googleapis.com/proto3_test.Nested]: <96 bunny: "Monty"97 >98>99`100 m2Golden = `101name: "David"102result_count: 47103anything: <104 ["http://[::1]/type.googleapis.com/proto3_test.Nested"]: <105 bunny: "Monty"106 >107>108`109 m3Golden = `110name: "David"111result_count: 47112anything: <113 ["type.googleapis.com/\"/proto3_test.Nested"]: <114 bunny: "Monty"115 >116>117`118 m4Golden = `119name: "David"120result_count: 47121anything: <122 [type.googleapis.com/a/path/proto3_test.Nested]: <123 bunny: "Monty"124 >125>126`127 m5Golden = `128[type.googleapis.com/proto3_test.Nested]: <129 bunny: "Monty"130>131`132 m6Golden = `133name: "David"134result_count: 47135anything: <136 [type.googleapis.com/proto2_test.MyMessage]: <137 count: 47138 name: "David"139 [proto2_test.Ext.more]: <140 data: "foo"141 >142 [proto2_test.Ext.text]: "bar"143 >144>145many_things: <146 [type.googleapis.com/proto2_test.MyMessage]: <147 count: 42148 bikeshed: GREEN149 rep_bytes: "roboto"150 [proto2_test.Ext.more]: <151 data: "baz"152 >153 >154>155many_things: <156 [type.googleapis.com/proto2_test.MyMessage]: <157 count: 47158 name: "David"159 [proto2_test.Ext.more]: <160 data: "foo"161 >162 [proto2_test.Ext.text]: "bar"163 >164>165`166 )167 return []golden{168 {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "},169 {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "},170 {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "},171 {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "},172 {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "},173 {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "},174 }175}176func TestMarshalGolden(t *testing.T) {177 for _, tt := range goldenMessages {178 t.Run("", func(t *testing.T) {179 if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want {180 t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want)181 }182 if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want {183 t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want)184 }185 })186 }187}188func TestUnmarshalGolden(t *testing.T) {189 for _, tt := range goldenMessages {190 t.Run("", func(t *testing.T) {191 want := tt.m192 got := proto.Clone(tt.m)193 got.Reset()194 if err := proto.UnmarshalText(tt.t, got); err != nil {195 t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err)196 }197 if !anyEqual(got, want) {198 t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want)199 }200 got.Reset()201 if err := proto.UnmarshalText(tt.c, got); err != nil {202 t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err)203 }204 if !anyEqual(got, want) {205 t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want)206 }207 })208 }209}210func TestMarshalUnknownAny(t *testing.T) {211 m := &pb3.Message{212 Anything: &anypb.Any{213 TypeUrl: "foo",214 Value: []byte("bar"),215 },216 }217 want := `anything: <218 type_url: "foo"219 value: "bar"220>221`222 got := expandedMarshaler.Text(m)223 if got != want {224 t.Errorf("got:\n%s\nwant:\n%s", got, want)225 }226}227func TestAmbiguousAny(t *testing.T) {228 pb := &anypb.Any{}229 err := proto.UnmarshalText(`230 type_url: "ttt/proto3_test.Nested"231 value: "\n\x05Monty"232 `, pb)233 if err != nil {234 t.Errorf("unexpected proto.UnmarshalText error: %v", err)235 }236}237func TestUnmarshalOverwriteAny(t *testing.T) {238 pb := &anypb.Any{}239 err := proto.UnmarshalText(`240 [type.googleapis.com/a/path/proto3_test.Nested]: <241 bunny: "Monty"242 >243 [type.googleapis.com/a/path/proto3_test.Nested]: <244 bunny: "Rabbit of Caerbannog"245 >246 `, pb)247 want := `line 7: Any message unpacked multiple times, or "type_url" already set`248 if err.Error() != want {249 t.Errorf("incorrect error:\ngot: %v\nwant: %v", err.Error(), want)250 }251}252func TestUnmarshalAnyMixAndMatch(t *testing.T) {253 pb := &anypb.Any{}254 err := proto.UnmarshalText(`255 value: "\n\x05Monty"256 [type.googleapis.com/a/path/proto3_test.Nested]: <257 bunny: "Rabbit of Caerbannog"258 >259 `, pb)260 want := `line 5: Any message unpacked multiple times, or "value" already set`261 if err.Error() != want {262 t.Errorf("incorrect error:\ngot: %v\nwant: %v", err.Error(), want)263 }264}265// textMessage implements the methods that allow it to marshal and unmarshal266// itself as text.267type textMessage struct {268}269func (*textMessage) MarshalText() ([]byte, error) {270 return []byte("custom"), nil271}272func (*textMessage) UnmarshalText(bytes []byte) error {273 if string(bytes) != "custom" {274 return errors.New("expected 'custom'")275 }276 return nil277}278func (*textMessage) Reset() {}279func (*textMessage) String() string { return "" }280func (*textMessage) ProtoMessage() {}281func newTestMessage() *pb2.MyMessage {282 msg := &pb2.MyMessage{283 Count: proto.Int32(42),284 Name: proto.String("Dave"),285 Quote: proto.String(`"I didn't want to go."`),286 Pet: []string{"bunny", "kitty", "horsey"},287 Inner: &pb2.InnerMessage{288 Host: proto.String("footrest.syd"),289 Port: proto.Int32(7001),290 Connected: proto.Bool(true),291 },292 Others: []*pb2.OtherMessage{293 {294 Key: proto.Int64(0xdeadbeef),295 Value: []byte{1, 65, 7, 12},296 },297 {298 Weight: proto.Float32(6.022),299 Inner: &pb2.InnerMessage{300 Host: proto.String("lesha.mtv"),301 Port: proto.Int32(8002),302 },303 },304 },305 Bikeshed: pb2.MyMessage_BLUE.Enum(),306 Somegroup: &pb2.MyMessage_SomeGroup{307 GroupField: proto.Int32(8),308 },309 // One normally wouldn't do this.310 // This is an undeclared tag 13, as a varint (wire type 0) with value 4.311 XXX_unrecognized: []byte{13<<3 | 0, 4},312 }313 ext := &pb2.Ext{314 Data: proto.String("Big gobs for big rats"),315 }316 if err := proto.SetExtension(msg, pb2.E_Ext_More, ext); err != nil {317 panic(err)318 }319 greetings := []string{"adg", "easy", "cow"}320 if err := proto.SetExtension(msg, pb2.E_Greeting, greetings); err != nil {321 panic(err)322 }323 // Add an unknown extension. We marshal a pb2.Ext, and fake the ID.324 b, err := proto.Marshal(&pb2.Ext{Data: proto.String("3G skiing")})325 if err != nil {326 panic(err)327 }328 b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...)329 proto.SetRawExtension(msg, 201, b)330 // Extensions can be plain fields, too, so let's test that.331 b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19)332 proto.SetRawExtension(msg, 202, b)333 return msg334}335const text = `count: 42336name: "Dave"337quote: "\"I didn't want to go.\""338pet: "bunny"339pet: "kitty"340pet: "horsey"341inner: <342 host: "footrest.syd"343 port: 7001344 connected: true345>346others: <347 key: 3735928559348 value: "\001A\007\014"349>350others: <351 weight: 6.022352 inner: <353 host: "lesha.mtv"354 port: 8002355 >356>357bikeshed: BLUE358SomeGroup {359 group_field: 8360}361/* 18 unknown bytes */36213: 4363201: "\t3G skiing"364202: 19365[proto2_test.Ext.more]: <366 data: "Big gobs for big rats"367>368[proto2_test.greeting]: "adg"369[proto2_test.greeting]: "easy"370[proto2_test.greeting]: "cow"371`372func TestMarshalText(t *testing.T) {373 buf := new(bytes.Buffer)374 if err := proto.MarshalText(buf, newTestMessage()); err != nil {375 t.Fatalf("proto.MarshalText: %v", err)376 }377 got := buf.String()378 if diff := cmp.Diff(text, got); got != text {379 t.Errorf("diff (-want +got):\n%v\n\ngot:\n%v\n\nwant:\n%v", diff, got, text)380 }381}382func TestMarshalTextCustomMessage(t *testing.T) {383 buf := new(bytes.Buffer)384 if err := proto.MarshalText(buf, &textMessage{}); err != nil {385 t.Fatalf("proto.MarshalText: %v", err)386 }387 got := buf.String()388 if got != "custom" {389 t.Errorf("got:\n%v\n\nwant:\n%v", got, "custom")390 }391}392func TestMarshalTextNil(t *testing.T) {393 want := "<nil>"394 tests := []proto.Message{nil, (*pb2.MyMessage)(nil)}395 for i, test := range tests {396 buf := new(bytes.Buffer)397 if err := proto.MarshalText(buf, test); err != nil {398 t.Fatal(err)399 }400 if got := buf.String(); got != want {401 t.Errorf("%d: got %q want %q", i, got, want)402 }403 }404}405func TestMarshalTextUnknownEnum(t *testing.T) {406 // The Color enum only specifies values 0-2.407 m := &pb2.MyMessage{Bikeshed: pb2.MyMessage_Color(3).Enum()}408 got := m.String()409 const want = `bikeshed:3 `410 if got != want {411 t.Errorf("\n got %q\nwant %q", got, want)412 }413}414func TestTextOneof(t *testing.T) {415 tests := []struct {416 m proto.Message417 want string418 }{419 // zero message420 {&pb2.Communique{}, ``},421 // scalar field422 {&pb2.Communique{Union: &pb2.Communique_Number{4}}, `number:4`},423 // message field424 {&pb2.Communique{Union: &pb2.Communique_Msg{425 &pb2.Strings{StringField: proto.String("why hello!")},426 }}, `msg:<string_field:"why hello!" >`},427 // bad oneof (should not panic)428 {&pb2.Communique{Union: &pb2.Communique_Msg{nil}}, `msg:<>`},429 }430 for _, test := range tests {431 got := strings.TrimSpace(test.m.String())432 if got != test.want {433 t.Errorf("got:\n%s\n\nwant:\n%s", got, test.want)434 }435 }436}437func compact(src string) string {438 // s/[ \n]+/ /g; s/ $//;439 dst := make([]byte, len(src))440 space, comment := false, false441 j := 0442 for i := 0; i < len(src); i++ {443 if strings.HasPrefix(src[i:], "/*") {444 comment = true445 i++446 continue447 }448 if comment && strings.HasPrefix(src[i:], "*/") {449 comment = false450 i++451 continue452 }453 if comment {454 continue455 }456 c := src[i]457 if c == ' ' || c == '\n' {458 space = true459 continue460 }461 if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') {462 space = false463 }464 if c == '{' {465 space = false466 }467 if space {468 dst[j] = ' '469 j++470 space = false471 }472 dst[j] = c473 j++474 }475 if space {476 dst[j] = ' '477 j++478 }479 return string(dst[0:j])480}481func TestCompactText(t *testing.T) {482 got := proto.CompactTextString(newTestMessage())483 if got != compact(text) {484 t.Errorf("got:\n%v\n\nwant:\n%v", got, compact(text))485 }486}487func TestStringEscaping(t *testing.T) {488 testCases := []struct {489 in *pb2.Strings490 out string491 }{492 {493 // Test data from C++ test (TextFormatTest.StringEscape).494 // Single divergence: we don't escape apostrophes.495 &pb2.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")},496 "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n",497 },498 {499 // Test data from the same C++ test.500 &pb2.Strings{StringField: proto.String("\350\260\267\346\255\214")},501 "string_field: \"\\350\\260\\267\\346\\255\\214\"\n",502 },503 {504 // Some UTF-8.505 &pb2.Strings{StringField: proto.String("\x00\x01\xff\x81")},506 `string_field: "\000\001\377\201"` + "\n",507 },508 }509 for _, tc := range testCases {510 t.Run("", func(t *testing.T) {511 var buf bytes.Buffer512 if err := proto.MarshalText(&buf, tc.in); err != nil {513 t.Fatalf("proto.MarsalText error: %v", err)514 }515 got := buf.String()516 if got != tc.out {517 t.Fatalf("want:\n%s\n\nwant:\n%s", got, tc.out)518 }519 // Check round-trip.520 pb := new(pb2.Strings)521 if err := proto.UnmarshalText(got, pb); err != nil {522 t.Fatalf("proto.UnmarshalText error: %v", err)523 }524 if !proto.Equal(pb, tc.in) {525 t.Fatalf("proto.Equal mismatch:\ngot:\n%v\n\nwant:\n%v", pb, tc.in)526 }527 })528 }529}530// A limitedWriter accepts some output before it fails.531// This is a proxy for something like a nearly-full or imminently-failing disk,532// or a network connection that is about to die.533type limitedWriter struct {534 b bytes.Buffer535 limit int536}537var outOfSpace = errors.New("proto: insufficient space")538func (w *limitedWriter) Write(p []byte) (n int, err error) {539 var avail = w.limit - w.b.Len()540 if avail <= 0 {541 return 0, outOfSpace542 }543 if len(p) <= avail {544 return w.b.Write(p)545 }546 n, _ = w.b.Write(p[:avail])547 return n, outOfSpace548}549func TestMarshalTextFailing(t *testing.T) {550 // Try lots of different sizes to exercise more error code-paths.551 for lim := 0; lim < len(text); lim++ {552 buf := new(limitedWriter)553 buf.limit = lim554 err := proto.MarshalText(buf, newTestMessage())555 // We expect a certain error, but also some partial results in the buffer.556 if err != outOfSpace {557 t.Errorf("error mismatch: got %v, want %v", err, outOfSpace)558 }559 got := buf.b.String()560 want := text[:buf.limit]561 if got != want {562 t.Errorf("text mismatch:\n\ngot:\n%v\n\nwant:\n%v", got, want)563 }564 }565}566func TestFloats(t *testing.T) {567 tests := []struct {568 f float64569 want string570 }{571 {0, "0"},572 {4.7, "4.7"},573 {math.Inf(1), "inf"},574 {math.Inf(-1), "-inf"},575 {math.NaN(), "nan"},576 }577 for _, test := range tests {578 msg := &pb2.FloatingPoint{F: &test.f}579 got := strings.TrimSpace(msg.String())580 want := `f:` + test.want581 if got != want {582 t.Errorf("f=%f: got %q, want %q", test.f, got, want)583 }584 }585}586func TestRepeatedNilText(t *testing.T) {587 m := &pb2.MessageList{588 Message: []*pb2.MessageList_Message{589 nil,590 &pb2.MessageList_Message{591 Name: proto.String("Horse"),592 },593 nil,594 },595 }596 want := `Message {597}598Message {599 name: "Horse"600}601Message {602}603`604 if got := proto.MarshalTextString(m); got != want {605 t.Errorf("got:\n%s\n\nwant:\n%s", got, want)606 }607}608func TestProto3Text(t *testing.T) {609 tests := []struct {610 m proto.Message611 want string612 }{613 // zero message614 {&pb3.Message{}, ``},615 // zero message except for an empty byte slice616 {&pb3.Message{Data: []byte{}}, ``},617 // trivial case618 {&pb3.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`},619 // empty map620 {&pb2.MessageWithMap{}, ``},621 // non-empty map; map format is the same as a repeated struct,622 // and they are sorted by key (numerically for numeric keys).623 {624 &pb2.MessageWithMap{NameMapping: map[int32]string{625 -1: "Negatory",626 7: "Lucky",627 1234: "Feist",628 6345789: "Otis",629 }},630 `name_mapping:<key:-1 value:"Negatory" > ` +631 `name_mapping:<key:7 value:"Lucky" > ` +632 `name_mapping:<key:1234 value:"Feist" > ` +633 `name_mapping:<key:6345789 value:"Otis" >`,634 },635 // map with nil value; not well-defined, but we shouldn't crash636 {637 &pb2.MessageWithMap{MsgMapping: map[int64]*pb2.FloatingPoint{7: nil}},638 `msg_mapping:<key:7 value:<> >`,639 },640 }641 for _, test := range tests {642 got := strings.TrimSpace(test.m.String())643 if got != test.want {644 t.Errorf("got:\n%s\n\nwant:\n%s", got, test.want)645 }646 }647}648func TestRacyMarshal(t *testing.T) {649 // This test should be run with the race detector.650 any := &pb2.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}651 proto.SetExtension(any, pb2.E_Ext_Text, proto.String("bar"))652 b, err := proto.Marshal(any)653 if err != nil {654 panic(err)655 }656 m := &pb3.Message{657 Name: "David",658 ResultCount: 47,659 Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any), Value: b},660 }661 wantText := proto.MarshalTextString(m)662 wantBytes, err := proto.Marshal(m)663 if err != nil {664 t.Fatalf("proto.Marshal error: %v", err)665 }666 var wg sync.WaitGroup667 defer wg.Wait()668 wg.Add(20)669 for i := 0; i < 10; i++ {670 go func() {671 defer wg.Done()672 got := proto.MarshalTextString(m)673 if got != wantText {674 t.Errorf("proto.MarshalTextString = %q, want %q", got, wantText)675 }676 }()677 go func() {678 defer wg.Done()679 got, err := proto.Marshal(m)680 if !bytes.Equal(got, wantBytes) || err != nil {681 t.Errorf("proto.Marshal = (%x, %v), want (%x, nil)", got, err, wantBytes)682 }683 }()684 }685}686type UnmarshalTextTest struct {687 in string688 err string // if "", no error expected689 out *pb2.MyMessage690}691func buildExtStructTest(text string) UnmarshalTextTest {692 msg := &pb2.MyMessage{693 Count: proto.Int32(42),694 }695 proto.SetExtension(msg, pb2.E_Ext_More, &pb2.Ext{696 Data: proto.String("Hello, world!"),697 })698 return UnmarshalTextTest{in: text, out: msg}699}700func buildExtDataTest(text string) UnmarshalTextTest {701 msg := &pb2.MyMessage{702 Count: proto.Int32(42),703 }704 proto.SetExtension(msg, pb2.E_Ext_Text, proto.String("Hello, world!"))705 proto.SetExtension(msg, pb2.E_Ext_Number, proto.Int32(1729))706 return UnmarshalTextTest{in: text, out: msg}707}708func buildExtRepStringTest(text string) UnmarshalTextTest {709 msg := &pb2.MyMessage{710 Count: proto.Int32(42),711 }712 if err := proto.SetExtension(msg, pb2.E_Greeting, []string{"bula", "hola"}); err != nil {713 panic(err)714 }715 return UnmarshalTextTest{in: text, out: msg}716}717var unmarshalTextTests = []UnmarshalTextTest{718 // Basic719 {720 in: " count:42\n name:\"Dave\" ",721 out: &pb2.MyMessage{722 Count: proto.Int32(42),723 Name: proto.String("Dave"),724 },725 },726 // Empty quoted string727 {728 in: `count:42 name:""`,729 out: &pb2.MyMessage{730 Count: proto.Int32(42),731 Name: proto.String(""),732 },733 },734 // Quoted string concatenation with double quotes735 {736 in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`,737 out: &pb2.MyMessage{738 Count: proto.Int32(42),739 Name: proto.String("My name is elsewhere"),740 },741 },742 // Quoted string concatenation with single quotes743 {744 in: "count:42 name: 'My name is '\n'elsewhere'",745 out: &pb2.MyMessage{746 Count: proto.Int32(42),747 Name: proto.String("My name is elsewhere"),748 },749 },750 // Quoted string concatenations with mixed quotes751 {752 in: "count:42 name: 'My name is '\n\"elsewhere\"",753 out: &pb2.MyMessage{754 Count: proto.Int32(42),755 Name: proto.String("My name is elsewhere"),756 },757 },758 {759 in: "count:42 name: \"My name is \"\n'elsewhere'",760 out: &pb2.MyMessage{761 Count: proto.Int32(42),762 Name: proto.String("My name is elsewhere"),763 },764 },765 // Quoted string with escaped apostrophe766 {767 in: `count:42 name: "HOLIDAY - New Year\'s Day"`,768 out: &pb2.MyMessage{769 Count: proto.Int32(42),770 Name: proto.String("HOLIDAY - New Year's Day"),771 },772 },773 // Quoted string with single quote774 {775 in: `count:42 name: 'Roger "The Ramster" Ramjet'`,776 out: &pb2.MyMessage{777 Count: proto.Int32(42),778 Name: proto.String(`Roger "The Ramster" Ramjet`),779 },780 },781 // Quoted string with all the accepted special characters from the C++ test782 {783 in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"",784 out: &pb2.MyMessage{785 Count: proto.Int32(42),786 Name: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"),787 },788 },789 // Quoted string with quoted backslash790 {791 in: `count:42 name: "\\'xyz"`,792 out: &pb2.MyMessage{793 Count: proto.Int32(42),794 Name: proto.String(`\'xyz`),795 },796 },797 // Quoted string with UTF-8 bytes.798 {799 in: "count:42 name: '\303\277\302\201\x00\xAB\xCD\xEF'",800 out: &pb2.MyMessage{801 Count: proto.Int32(42),802 Name: proto.String("\303\277\302\201\x00\xAB\xCD\xEF"),803 },804 },805 // Quoted string with unicode escapes.806 {807 in: `count: 42 name: "\u0047\U00000047\uffff\U0010ffff"`,808 out: &pb2.MyMessage{809 Count: proto.Int32(42),810 Name: proto.String("GG\uffff\U0010ffff"),811 },812 },813 // Bad quoted string814 {815 in: `inner: < host: "\0" >` + "\n",816 err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`,817 },818 // Bad \u escape819 {820 in: `count: 42 name: "\u000"`,821 err: `line 1.16: invalid quoted string "\u000": \u requires 4 following digits`,822 },823 // Bad \U escape824 {825 in: `count: 42 name: "\U0000000"`,826 err: `line 1.16: invalid quoted string "\U0000000": \U requires 8 following digits`,827 },828 // Bad \U escape829 {830 in: `count: 42 name: "\xxx"`,831 err: `line 1.16: invalid quoted string "\xxx": \xxx contains non-hexadecimal digits`,832 },833 // Number too large for int64834 {835 in: "count: 1 others { key: 123456789012345678901 }",836 err: "line 1.23: invalid int64: 123456789012345678901",837 },838 // Number too large for int32839 {840 in: "count: 1234567890123",841 err: "line 1.7: invalid int32: 1234567890123",842 },843 // Number in hexadecimal844 {845 in: "count: 0x2beef",846 out: &pb2.MyMessage{847 Count: proto.Int32(0x2beef),848 },849 },850 // Number in octal851 {852 in: "count: 024601",853 out: &pb2.MyMessage{854 Count: proto.Int32(024601),855 },856 },857 // Floating point number with "f" suffix858 {859 in: "count: 4 others:< weight: 17.0f >",860 out: &pb2.MyMessage{861 Count: proto.Int32(4),862 Others: []*pb2.OtherMessage{863 {864 Weight: proto.Float32(17),865 },866 },867 },868 },869 // Floating point positive infinity870 {871 in: "count: 4 bigfloat: inf",872 out: &pb2.MyMessage{873 Count: proto.Int32(4),874 Bigfloat: proto.Float64(math.Inf(1)),875 },876 },877 // Floating point negative infinity878 {879 in: "count: 4 bigfloat: -inf",880 out: &pb2.MyMessage{881 Count: proto.Int32(4),882 Bigfloat: proto.Float64(math.Inf(-1)),883 },884 },885 // Number too large for float32886 {887 in: "others:< weight: 12345678901234567890123456789012345678901234567890 >",888 err: "line 1.17: invalid float: 12345678901234567890123456789012345678901234567890",889 },890 // Number posing as a quoted string891 {892 in: `inner: < host: 12 >` + "\n",893 err: `line 1.15: invalid string: 12`,894 },895 // Quoted string posing as int32896 {897 in: `count: "12"`,898 err: `line 1.7: invalid int32: "12"`,899 },900 // Quoted string posing a float32901 {902 in: `others:< weight: "17.4" >`,903 err: `line 1.17: invalid float: "17.4"`,904 },905 // unclosed bracket doesn't cause infinite loop906 {907 in: `[`,908 err: `line 1.0: unclosed type_url or extension name`,909 },910 // Enum911 {912 in: `count:42 bikeshed: BLUE`,913 out: &pb2.MyMessage{914 Count: proto.Int32(42),915 Bikeshed: pb2.MyMessage_BLUE.Enum(),916 },917 },918 // Repeated field919 {920 in: `count:42 pet: "horsey" pet:"bunny"`,921 out: &pb2.MyMessage{922 Count: proto.Int32(42),923 Pet: []string{"horsey", "bunny"},924 },925 },926 // Repeated field with list notation927 {928 in: `count:42 pet: ["horsey", "bunny"]`,929 out: &pb2.MyMessage{930 Count: proto.Int32(42),931 Pet: []string{"horsey", "bunny"},932 },933 },934 // Repeated message with/without colon and <>/{}935 {936 in: `count:42 others:{} others{} others:<> others:{}`,937 out: &pb2.MyMessage{938 Count: proto.Int32(42),939 Others: []*pb2.OtherMessage{940 {},941 {},942 {},943 {},944 },945 },946 },947 // Missing colon for inner message948 {949 in: `count:42 inner < host: "cauchy.syd" >`,950 out: &pb2.MyMessage{951 Count: proto.Int32(42),952 Inner: &pb2.InnerMessage{953 Host: proto.String("cauchy.syd"),954 },955 },956 },957 // Missing colon for string field958 {959 in: `name "Dave"`,960 err: `line 1.5: expected ':', found "\"Dave\""`,961 },962 // Missing colon for int32 field963 {964 in: `count 42`,965 err: `line 1.6: expected ':', found "42"`,966 },967 // Missing required field968 {969 in: `name: "Pawel"`,970 err: `required field proto2_test.MyMessage.count not set`,971 out: &pb2.MyMessage{972 Name: proto.String("Pawel"),973 },974 },975 // Missing required field in a required submessage976 {977 in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`,978 err: `required field proto2_test.InnerMessage.host not set`,979 out: &pb2.MyMessage{980 Count: proto.Int32(42),981 WeMustGoDeeper: &pb2.RequiredInnerMessage{LeoFinallyWonAnOscar: &pb2.InnerMessage{}},982 },983 },984 // Repeated non-repeated field985 {986 in: `name: "Rob" name: "Russ"`,987 err: `line 1.12: non-repeated field "name" was repeated`,988 },989 // Group990 {991 in: `count: 17 SomeGroup { group_field: 12 }`,992 out: &pb2.MyMessage{993 Count: proto.Int32(17),994 Somegroup: &pb2.MyMessage_SomeGroup{995 GroupField: proto.Int32(12),996 },997 },998 },999 // Semicolon between fields1000 {1001 in: `count:3;name:"Calvin"`,1002 out: &pb2.MyMessage{1003 Count: proto.Int32(3),1004 Name: proto.String("Calvin"),1005 },1006 },1007 // Comma between fields1008 {1009 in: `count:4,name:"Ezekiel"`,1010 out: &pb2.MyMessage{1011 Count: proto.Int32(4),1012 Name: proto.String("Ezekiel"),1013 },1014 },1015 // Boolean false1016 {1017 in: `count:42 inner { host: "example.com" connected: false }`,1018 out: &pb2.MyMessage{1019 Count: proto.Int32(42),1020 Inner: &pb2.InnerMessage{1021 Host: proto.String("example.com"),1022 Connected: proto.Bool(false),1023 },1024 },1025 },1026 // Boolean true1027 {1028 in: `count:42 inner { host: "example.com" connected: true }`,1029 out: &pb2.MyMessage{1030 Count: proto.Int32(42),1031 Inner: &pb2.InnerMessage{1032 Host: proto.String("example.com"),1033 Connected: proto.Bool(true),1034 },1035 },1036 },1037 // Boolean 01038 {1039 in: `count:42 inner { host: "example.com" connected: 0 }`,1040 out: &pb2.MyMessage{1041 Count: proto.Int32(42),1042 Inner: &pb2.InnerMessage{1043 Host: proto.String("example.com"),1044 Connected: proto.Bool(false),1045 },1046 },1047 },1048 // Boolean 11049 {1050 in: `count:42 inner { host: "example.com" connected: 1 }`,1051 out: &pb2.MyMessage{1052 Count: proto.Int32(42),1053 Inner: &pb2.InnerMessage{1054 Host: proto.String("example.com"),1055 Connected: proto.Bool(true),1056 },1057 },1058 },1059 // Boolean f1060 {1061 in: `count:42 inner { host: "example.com" connected: f }`,1062 out: &pb2.MyMessage{1063 Count: proto.Int32(42),1064 Inner: &pb2.InnerMessage{1065 Host: proto.String("example.com"),1066 Connected: proto.Bool(false),1067 },1068 },1069 },1070 // Boolean t1071 {1072 in: `count:42 inner { host: "example.com" connected: t }`,1073 out: &pb2.MyMessage{1074 Count: proto.Int32(42),1075 Inner: &pb2.InnerMessage{1076 Host: proto.String("example.com"),1077 Connected: proto.Bool(true),1078 },1079 },1080 },1081 // Boolean False1082 {1083 in: `count:42 inner { host: "example.com" connected: False }`,1084 out: &pb2.MyMessage{1085 Count: proto.Int32(42),1086 Inner: &pb2.InnerMessage{1087 Host: proto.String("example.com"),1088 Connected: proto.Bool(false),1089 },1090 },1091 },1092 // Boolean True1093 {1094 in: `count:42 inner { host: "example.com" connected: True }`,1095 out: &pb2.MyMessage{1096 Count: proto.Int32(42),1097 Inner: &pb2.InnerMessage{1098 Host: proto.String("example.com"),1099 Connected: proto.Bool(true),1100 },1101 },1102 },1103 // Extension1104 buildExtStructTest(`count: 42 [proto2_test.Ext.more]:<data:"Hello, world!" >`),1105 buildExtStructTest(`count: 42 [proto2_test.Ext.more] {data:"Hello, world!"}`),1106 buildExtDataTest(`count: 42 [proto2_test.Ext.text]:"Hello, world!" [proto2_test.Ext.number]:1729`),1107 buildExtRepStringTest(`count: 42 [proto2_test.greeting]:"bula" [proto2_test.greeting]:"hola"`),1108 {1109 in: `[proto2_test.complex]:<>`,1110 err: `line 1.20: extension field "proto2_test.complex" does not extend message "proto2_test.MyMessage"`,1111 },1112 // Big all-in-one1113 {1114 in: "count:42 # Meaning\n" +1115 `name:"Dave" ` +1116 `quote:"\"I didn't want to go.\"" ` +1117 `pet:"bunny" ` +1118 `pet:"kitty" ` +1119 `pet:"horsey" ` +1120 `inner:<` +1121 ` host:"footrest.syd" ` +1122 ` port:7001 ` +1123 ` connected:true ` +1124 `> ` +1125 `others:<` +1126 ` key:3735928559 ` +1127 ` value:"\x01A\a\f" ` +1128 `> ` +1129 `others:<` +1130 " weight:58.9 # Atomic weight of Co\n" +1131 ` inner:<` +1132 ` host:"lesha.mtv" ` +1133 ` port:8002 ` +1134 ` >` +1135 `>`,1136 out: &pb2.MyMessage{1137 Count: proto.Int32(42),1138 Name: proto.String("Dave"),1139 Quote: proto.String(`"I didn't want to go."`),1140 Pet: []string{"bunny", "kitty", "horsey"},1141 Inner: &pb2.InnerMessage{1142 Host: proto.String("footrest.syd"),1143 Port: proto.Int32(7001),1144 Connected: proto.Bool(true),1145 },1146 Others: []*pb2.OtherMessage{1147 {1148 Key: proto.Int64(3735928559),1149 Value: []byte{0x1, 'A', '\a', '\f'},1150 },1151 {1152 Weight: proto.Float32(58.9),1153 Inner: &pb2.InnerMessage{1154 Host: proto.String("lesha.mtv"),1155 Port: proto.Int32(8002),1156 },1157 },1158 },1159 },1160 },1161}1162func TestUnmarshalText(t *testing.T) {1163 for _, test := range unmarshalTextTests {1164 t.Run("", func(t *testing.T) {1165 pb := new(pb2.MyMessage)1166 err := proto.UnmarshalText(test.in, pb)1167 if test.err == "" {1168 // We don't expect failure....

Full Screen

Full Screen

proto.go

Source:proto.go Github

copy

Full Screen

...13// ToFileDescriptorProto copies a protoreflect.FileDescriptor into a14// google.protobuf.FileDescriptorProto message.15func ToFileDescriptorProto(file protoreflect.FileDescriptor) *descriptorpb.FileDescriptorProto {16 p := &descriptorpb.FileDescriptorProto{17 Name: proto.String(file.Path()),18 Package: proto.String(string(file.Package())),19 Options: proto.Clone(file.Options()).(*descriptorpb.FileOptions),20 }21 for i, imports := 0, file.Imports(); i < imports.Len(); i++ {22 imp := imports.Get(i)23 p.Dependency = append(p.Dependency, imp.Path())24 if imp.IsPublic {25 p.PublicDependency = append(p.PublicDependency, int32(i))26 }27 if imp.IsWeak {28 p.WeakDependency = append(p.WeakDependency, int32(i))29 }30 }31 for i, locs := 0, file.SourceLocations(); i < locs.Len(); i++ {32 loc := locs.Get(i)33 l := &descriptorpb.SourceCodeInfo_Location{}34 l.Path = append(l.Path, loc.Path...)35 if loc.StartLine == loc.EndLine {36 l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndColumn)}37 } else {38 l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndLine), int32(loc.EndColumn)}39 }40 l.LeadingDetachedComments = append([]string(nil), loc.LeadingDetachedComments...)41 if loc.LeadingComments != "" {42 l.LeadingComments = proto.String(loc.LeadingComments)43 }44 if loc.TrailingComments != "" {45 l.TrailingComments = proto.String(loc.TrailingComments)46 }47 if p.SourceCodeInfo == nil {48 p.SourceCodeInfo = &descriptorpb.SourceCodeInfo{}49 }50 p.SourceCodeInfo.Location = append(p.SourceCodeInfo.Location, l)51 }52 for i, messages := 0, file.Messages(); i < messages.Len(); i++ {53 p.MessageType = append(p.MessageType, ToDescriptorProto(messages.Get(i)))54 }55 for i, enums := 0, file.Enums(); i < enums.Len(); i++ {56 p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))57 }58 for i, services := 0, file.Services(); i < services.Len(); i++ {59 p.Service = append(p.Service, ToServiceDescriptorProto(services.Get(i)))60 }61 for i, exts := 0, file.Extensions(); i < exts.Len(); i++ {62 p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))63 }64 if syntax := file.Syntax(); syntax != protoreflect.Proto2 {65 p.Syntax = proto.String(file.Syntax().String())66 }67 return p68}69// ToDescriptorProto copies a protoreflect.MessageDescriptor into a70// google.protobuf.DescriptorProto message.71func ToDescriptorProto(message protoreflect.MessageDescriptor) *descriptorpb.DescriptorProto {72 p := &descriptorpb.DescriptorProto{73 Name: proto.String(string(message.Name())),74 Options: proto.Clone(message.Options()).(*descriptorpb.MessageOptions),75 }76 for i, fields := 0, message.Fields(); i < fields.Len(); i++ {77 p.Field = append(p.Field, ToFieldDescriptorProto(fields.Get(i)))78 }79 for i, exts := 0, message.Extensions(); i < exts.Len(); i++ {80 p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))81 }82 for i, messages := 0, message.Messages(); i < messages.Len(); i++ {83 p.NestedType = append(p.NestedType, ToDescriptorProto(messages.Get(i)))84 }85 for i, enums := 0, message.Enums(); i < enums.Len(); i++ {86 p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))87 }88 for i, xranges := 0, message.ExtensionRanges(); i < xranges.Len(); i++ {89 xrange := xranges.Get(i)90 p.ExtensionRange = append(p.ExtensionRange, &descriptorpb.DescriptorProto_ExtensionRange{91 Start: proto.Int32(int32(xrange[0])),92 End: proto.Int32(int32(xrange[1])),93 Options: proto.Clone(message.ExtensionRangeOptions(i)).(*descriptorpb.ExtensionRangeOptions),94 })95 }96 for i, oneofs := 0, message.Oneofs(); i < oneofs.Len(); i++ {97 p.OneofDecl = append(p.OneofDecl, ToOneofDescriptorProto(oneofs.Get(i)))98 }99 for i, ranges := 0, message.ReservedRanges(); i < ranges.Len(); i++ {100 rrange := ranges.Get(i)101 p.ReservedRange = append(p.ReservedRange, &descriptorpb.DescriptorProto_ReservedRange{102 Start: proto.Int32(int32(rrange[0])),103 End: proto.Int32(int32(rrange[1])),104 })105 }106 for i, names := 0, message.ReservedNames(); i < names.Len(); i++ {107 p.ReservedName = append(p.ReservedName, string(names.Get(i)))108 }109 return p110}111// ToFieldDescriptorProto copies a protoreflect.FieldDescriptor into a112// google.protobuf.FieldDescriptorProto message.113func ToFieldDescriptorProto(field protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto {114 p := &descriptorpb.FieldDescriptorProto{115 Name: proto.String(string(field.Name())),116 Number: proto.Int32(int32(field.Number())),117 Label: descriptorpb.FieldDescriptorProto_Label(field.Cardinality()).Enum(),118 Options: proto.Clone(field.Options()).(*descriptorpb.FieldOptions),119 }120 if field.IsExtension() {121 p.Extendee = fullNameOf(field.ContainingMessage())122 }123 if field.Kind().IsValid() {124 p.Type = descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum()125 }126 if field.Enum() != nil {127 p.TypeName = fullNameOf(field.Enum())128 }129 if field.Message() != nil {130 p.TypeName = fullNameOf(field.Message())131 }132 if field.HasJSONName() {133 p.JsonName = proto.String(field.JSONName())134 }135 if field.Syntax() == protoreflect.Proto3 && field.HasOptionalKeyword() {136 p.Proto3Optional = proto.Bool(true)137 }138 if field.HasDefault() {139 def, err := defval.Marshal(field.Default(), field.DefaultEnumValue(), field.Kind(), defval.Descriptor)140 if err != nil && field.DefaultEnumValue() != nil {141 def = string(field.DefaultEnumValue().Name()) // occurs for unresolved enum values142 } else if err != nil {143 panic(fmt.Sprintf("%v: %v", field.FullName(), err))144 }145 p.DefaultValue = proto.String(def)146 }147 if oneof := field.ContainingOneof(); oneof != nil {148 p.OneofIndex = proto.Int32(int32(oneof.Index()))149 }150 return p151}152// ToOneofDescriptorProto copies a protoreflect.OneofDescriptor into a153// google.protobuf.OneofDescriptorProto message.154func ToOneofDescriptorProto(oneof protoreflect.OneofDescriptor) *descriptorpb.OneofDescriptorProto {155 return &descriptorpb.OneofDescriptorProto{156 Name: proto.String(string(oneof.Name())),157 Options: proto.Clone(oneof.Options()).(*descriptorpb.OneofOptions),158 }159}160// ToEnumDescriptorProto copies a protoreflect.EnumDescriptor into a161// google.protobuf.EnumDescriptorProto message.162func ToEnumDescriptorProto(enum protoreflect.EnumDescriptor) *descriptorpb.EnumDescriptorProto {163 p := &descriptorpb.EnumDescriptorProto{164 Name: proto.String(string(enum.Name())),165 Options: proto.Clone(enum.Options()).(*descriptorpb.EnumOptions),166 }167 for i, values := 0, enum.Values(); i < values.Len(); i++ {168 p.Value = append(p.Value, ToEnumValueDescriptorProto(values.Get(i)))169 }170 for i, ranges := 0, enum.ReservedRanges(); i < ranges.Len(); i++ {171 rrange := ranges.Get(i)172 p.ReservedRange = append(p.ReservedRange, &descriptorpb.EnumDescriptorProto_EnumReservedRange{173 Start: proto.Int32(int32(rrange[0])),174 End: proto.Int32(int32(rrange[1])),175 })176 }177 for i, names := 0, enum.ReservedNames(); i < names.Len(); i++ {178 p.ReservedName = append(p.ReservedName, string(names.Get(i)))179 }180 return p181}182// ToEnumValueDescriptorProto copies a protoreflect.EnumValueDescriptor into a183// google.protobuf.EnumValueDescriptorProto message.184func ToEnumValueDescriptorProto(value protoreflect.EnumValueDescriptor) *descriptorpb.EnumValueDescriptorProto {185 return &descriptorpb.EnumValueDescriptorProto{186 Name: proto.String(string(value.Name())),187 Number: proto.Int32(int32(value.Number())),188 Options: proto.Clone(value.Options()).(*descriptorpb.EnumValueOptions),189 }190}191// ToServiceDescriptorProto copies a protoreflect.ServiceDescriptor into a192// google.protobuf.ServiceDescriptorProto message.193func ToServiceDescriptorProto(service protoreflect.ServiceDescriptor) *descriptorpb.ServiceDescriptorProto {194 p := &descriptorpb.ServiceDescriptorProto{195 Name: proto.String(string(service.Name())),196 Options: proto.Clone(service.Options()).(*descriptorpb.ServiceOptions),197 }198 for i, methods := 0, service.Methods(); i < methods.Len(); i++ {199 p.Method = append(p.Method, ToMethodDescriptorProto(methods.Get(i)))200 }201 return p202}203// ToMethodDescriptorProto copies a protoreflect.MethodDescriptor into a204// google.protobuf.MethodDescriptorProto message.205func ToMethodDescriptorProto(method protoreflect.MethodDescriptor) *descriptorpb.MethodDescriptorProto {206 p := &descriptorpb.MethodDescriptorProto{207 Name: proto.String(string(method.Name())),208 InputType: fullNameOf(method.Input()),209 OutputType: fullNameOf(method.Output()),210 Options: proto.Clone(method.Options()).(*descriptorpb.MethodOptions),211 }212 if method.IsStreamingClient() {213 p.ClientStreaming = proto.Bool(true)214 }215 if method.IsStreamingServer() {216 p.ServerStreaming = proto.Bool(true)217 }218 return p219}220func fullNameOf(d protoreflect.Descriptor) *string {221 if d == nil {222 return nil223 }224 if strings.HasPrefix(string(d.FullName()), unknownPrefix) {225 return proto.String(string(d.FullName()[len(unknownPrefix):]))226 }227 return proto.String("." + string(d.FullName()))228}...

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 t := &timestamp.Timestamp{4 }5 w := &wrappers.StringValue{6 }7 fmt.Println(proto.MarshalTextString(t))8 fmt.Println(proto.MarshalTextString(w))9 fmt.Println(proto.MarshalTextString(timestamppb.Now()))10}

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 any, err := anypb.New(&Address{Street: "123 Main St"})4 if err != nil {5 log.Fatal(err)6 }7 fmt.Println(any)8 if err := any.UnmarshalTo(&addr); err != nil {9 log.Fatal(err)10 }11 fmt.Println(addr)12 fmt.Println(any.TypeUrl)13}14import (15func main() {16 any, err := anypb.New(&Address{Street: "123 Main St"})17 if err != nil {18 log.Fatal(err)19 }20 fmt.Println(any)21 if err := any.UnmarshalTo(&addr); err != nil {22 log.Fatal(err)23 }24 fmt.Println(addr)25 fmt.Println(any.TypeUrl)26 data, err := proto.Marshal(&addr)27 if err != nil {28 log.Fatal(err)29 }30 fmt.Println(data)31}32import (33func main() {34 any, err := anypb.New(&Address{Street: "123 Main St"})35 if err != nil {36 log.Fatal(err)37 }38 fmt.Println(any)39 if err := any.UnmarshalTo(&addr); err != nil {40 log.Fatal(err)41 }42 fmt.Println(addr)43 fmt.Println(any.Type

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p := &Person{4 }5 data, err := proto.Marshal(p)6 if err != nil {7 fmt.Println("Marshaling error: ", err)8 }9 newP := &Person{}10 err = proto.Unmarshal(data, newP)11 if err != nil {12 fmt.Println("Unmarshaling error: ", err)13 }14 fmt.Println(newP.GetName())15 fmt.Println(newP.GetAge())16}

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 sm := example.StringMessage{4 }5 fmt.Println(sm)6 fmt.Printf("%T\n", sm)7 fmt.Printf("%p\n", &sm)8 data, err := proto.Marshal(&sm)9 if err != nil {10 fmt.Println("There was an error marshaling the data to a byte slice:", err)11 }12 fmt.Println(data)13 fmt.Printf("%T\n", data)14 fmt.Printf("%p\n", data)15 sm2 := &example.StringMessage{}16 fmt.Println(sm2)17 fmt.Printf("%T\n", sm2)18 fmt.Printf("%p\n", sm2)19 err = proto.Unmarshal(data, sm2)20 if err != nil {21 fmt.Println("There was an error unmarshaling the data to a StringMessage:", err)22 }23 fmt.Println(sm2)24 fmt.Printf("%T\n", sm2)25 fmt.Printf("%p\n", sm2)26 fmt.Println(sm2.GetValue())27}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Rod automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful