kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/go/util/ptypes/ptypes_test.go (about) 1 /* 2 * Copyright 2016 The Kythe Authors. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package ptypes 18 19 import ( 20 "testing" 21 22 "github.com/golang/protobuf/proto" 23 24 anypb "github.com/golang/protobuf/ptypes/any" 25 ) 26 27 // A dummy implementation of proto.Message for testing. 28 type dummy struct { 29 S string `protobuf:"bytes,1,opt,name=s"` 30 31 name string 32 } 33 34 func (d *dummy) Reset() { d.S = "" } 35 func (d *dummy) String() string { return "dummy proto" } 36 func (d *dummy) XXX_MessageName() string { return d.name } 37 func (d *dummy) Marshal() ([]byte, error) { return []byte("S=" + d.S), nil } 38 func (d *dummy) Unmarshal(data []byte) error { d.S = string(data); return nil } 39 func (*dummy) ProtoMessage() {} 40 41 func TestMarshalAny(t *testing.T) { 42 tests := []struct { 43 input proto.Message 44 want, data string 45 }{ 46 {&dummy{S: "foo", name: "some.Message"}, "type.googleapis.com/some.Message", "S=foo"}, 47 {&dummy{S: "bar", name: "kythe.Foo"}, "kythe.io/proto/kythe.Foo", "S=bar"}, 48 } 49 for _, test := range tests { 50 msg, err := MarshalAny(test.input) 51 if err != nil { 52 t.Errorf("MarshalAny %+v failed: %v", test.input, err) 53 continue 54 } 55 if got := msg.TypeUrl; got != test.want { 56 t.Errorf("MarshalAny %+v URL: got %q, want %q", test.input, got, test.want) 57 } 58 if got := string(msg.Value); got != test.data { 59 t.Errorf("MarshalAny %+v value: got %q, want %q", test.input, got, test.data) 60 } 61 } 62 } 63 64 func TestUnmarshalAny(t *testing.T) { 65 tests := []struct { 66 url, data string 67 want *dummy 68 }{ 69 {"type.googleapis.com/fuzzy", "wuzzy", &dummy{name: "fuzzy", S: "wuzzy"}}, 70 {"kythe.io/proto/kythe.Blah", "evil dog", &dummy{name: "kythe.Blah", S: "evil dog"}}, 71 } 72 for _, test := range tests { 73 got := &dummy{name: test.want.name} 74 if err := UnmarshalAny(&anypb.Any{ 75 TypeUrl: test.url, 76 Value: []byte(test.data), 77 }, got); err != nil { 78 t.Errorf("Unmarshaling URL %q, data %q: error %v", test.url, test.data, err) 79 } 80 if *got != *test.want { 81 t.Errorf("Unmarshaling failed: got %+v, want %+v", got, test.want) 82 } 83 } 84 }