extension_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style.
  3. // license that can be found in the LICENSE file.
  4. package proto_test
  5. import (
  6. "fmt"
  7. "testing"
  8. "github.com/google/go-cmp/cmp"
  9. "google.golang.org/protobuf/proto"
  10. pref "google.golang.org/protobuf/reflect/protoreflect"
  11. "google.golang.org/protobuf/runtime/protoimpl"
  12. legacy1pb "google.golang.org/protobuf/internal/testprotos/legacy/proto2.v0.0.0-20160225-2fc053c5"
  13. testpb "google.golang.org/protobuf/internal/testprotos/test"
  14. )
  15. func TestExtensionFuncs(t *testing.T) {
  16. for _, test := range []struct {
  17. message proto.Message
  18. ext pref.ExtensionType
  19. wantDefault interface{}
  20. value interface{}
  21. }{
  22. {
  23. message: &testpb.TestAllExtensions{},
  24. ext: testpb.E_OptionalInt32Extension,
  25. wantDefault: int32(0),
  26. value: int32(1),
  27. },
  28. {
  29. message: &testpb.TestAllExtensions{},
  30. ext: testpb.E_RepeatedStringExtension,
  31. wantDefault: ([]string)(nil),
  32. value: []string{"a", "b", "c"},
  33. },
  34. {
  35. message: protoimpl.X.MessageOf(&legacy1pb.Message{}).Interface(),
  36. ext: legacy1pb.E_Message_ExtensionOptionalBool,
  37. wantDefault: false,
  38. value: true,
  39. },
  40. } {
  41. desc := fmt.Sprintf("Extension %v, value %v", test.ext.TypeDescriptor().FullName(), test.value)
  42. if proto.HasExtension(test.message, test.ext) {
  43. t.Errorf("%v:\nbefore setting extension HasExtension(...) = true, want false", desc)
  44. }
  45. got := proto.GetExtension(test.message, test.ext)
  46. if d := cmp.Diff(test.wantDefault, got); d != "" {
  47. t.Errorf("%v:\nbefore setting extension GetExtension(...) returns unexpected value (-want,+got):\n%v", desc, d)
  48. }
  49. proto.SetExtension(test.message, test.ext, test.value)
  50. if !proto.HasExtension(test.message, test.ext) {
  51. t.Errorf("%v:\nafter setting extension HasExtension(...) = false, want true", desc)
  52. }
  53. got = proto.GetExtension(test.message, test.ext)
  54. if d := cmp.Diff(test.value, got); d != "" {
  55. t.Errorf("%v:\nafter setting extension GetExtension(...) returns unexpected value (-want,+got):\n%v", desc, d)
  56. }
  57. proto.ClearExtension(test.message, test.ext)
  58. if proto.HasExtension(test.message, test.ext) {
  59. t.Errorf("%v:\nafter clearing extension HasExtension(...) = true, want false", desc)
  60. }
  61. }
  62. }