(t *testing.T)
| 941 | } |
| 942 | |
| 943 | func TestAnyWithCustomResolver(t *testing.T) { |
| 944 | var resolvedTypeUrls []string |
| 945 | resolver := funcResolver(func(turl string) (proto.Message, error) { |
| 946 | resolvedTypeUrls = append(resolvedTypeUrls, turl) |
| 947 | return new(pb2.Simple), nil |
| 948 | }) |
| 949 | msg := &pb2.Simple{ |
| 950 | OBytes: []byte{1, 2, 3, 4}, |
| 951 | OBool: proto.Bool(true), |
| 952 | OString: proto.String("foobar"), |
| 953 | OInt64: proto.Int64(1020304), |
| 954 | } |
| 955 | msgBytes, err := proto.Marshal(msg) |
| 956 | if err != nil { |
| 957 | t.Errorf("an unexpected error while marshaling message: %v", err) |
| 958 | } |
| 959 | // make an Any with a type URL that won't resolve w/out custom resolver |
| 960 | any := &anypb.Any{ |
| 961 | TypeUrl: "https://foobar.com/some.random.MessageKind", |
| 962 | Value: msgBytes, |
| 963 | } |
| 964 | |
| 965 | m := Marshaler{AnyResolver: resolver} |
| 966 | js, err := m.MarshalToString(any) |
| 967 | if err != nil { |
| 968 | t.Errorf("an unexpected error while marshaling any to JSON: %v", err) |
| 969 | } |
| 970 | if len(resolvedTypeUrls) != 1 { |
| 971 | t.Errorf("custom resolver was not invoked during marshaling") |
| 972 | } else if resolvedTypeUrls[0] != "https://foobar.com/some.random.MessageKind" { |
| 973 | t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[0], "https://foobar.com/some.random.MessageKind") |
| 974 | } |
| 975 | wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}` |
| 976 | if js != wanted { |
| 977 | t.Errorf("marshaling JSON produced incorrect output: got %s, wanted %s", js, wanted) |
| 978 | } |
| 979 | |
| 980 | u := Unmarshaler{AnyResolver: resolver} |
| 981 | roundTrip := &anypb.Any{} |
| 982 | err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip) |
| 983 | if err != nil { |
| 984 | t.Errorf("an unexpected error while unmarshaling any from JSON: %v", err) |
| 985 | } |
| 986 | if len(resolvedTypeUrls) != 2 { |
| 987 | t.Errorf("custom resolver was not invoked during marshaling") |
| 988 | } else if resolvedTypeUrls[1] != "https://foobar.com/some.random.MessageKind" { |
| 989 | t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind") |
| 990 | } |
| 991 | if !proto.Equal(any, roundTrip) { |
| 992 | t.Errorf("message contents not set correctly after unmarshaling JSON: got %s, wanted %s", roundTrip, any) |
| 993 | } |
| 994 | } |
| 995 | |
| 996 | func TestUnmarshalJSONPBUnmarshaler(t *testing.T) { |
| 997 | rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` |
nothing calls this directly
no test coverage detected