checkinit_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. "strings"
  8. "testing"
  9. "google.golang.org/protobuf/encoding/prototext"
  10. "google.golang.org/protobuf/internal/flags"
  11. "google.golang.org/protobuf/proto"
  12. testpb "google.golang.org/protobuf/internal/testprotos/test"
  13. weakpb "google.golang.org/protobuf/internal/testprotos/test/weak1"
  14. )
  15. func TestCheckInitializedErrors(t *testing.T) {
  16. type test struct {
  17. m proto.Message
  18. want string
  19. skip bool
  20. }
  21. tests := []test{{
  22. m: &testpb.TestRequired{},
  23. want: `goproto.proto.test.TestRequired.required_field`,
  24. }, {
  25. m: &testpb.TestRequiredForeign{
  26. OptionalMessage: &testpb.TestRequired{},
  27. },
  28. want: `goproto.proto.test.TestRequired.required_field`,
  29. }, {
  30. m: &testpb.TestRequiredForeign{
  31. RepeatedMessage: []*testpb.TestRequired{
  32. {RequiredField: proto.Int32(1)},
  33. {},
  34. },
  35. },
  36. want: `goproto.proto.test.TestRequired.required_field`,
  37. }, {
  38. m: &testpb.TestRequiredForeign{
  39. MapMessage: map[int32]*testpb.TestRequired{
  40. 1: {},
  41. },
  42. },
  43. want: `goproto.proto.test.TestRequired.required_field`,
  44. }, {
  45. m: &testpb.TestWeak{},
  46. want: `<nil>`,
  47. skip: !flags.ProtoLegacy,
  48. }, {
  49. m: func() proto.Message {
  50. m := &testpb.TestWeak{}
  51. m.SetWeakMessage1(&weakpb.WeakImportMessage1{})
  52. return m
  53. }(),
  54. want: `goproto.proto.test.weak.WeakImportMessage1.a`,
  55. skip: !flags.ProtoLegacy,
  56. }, {
  57. m: func() proto.Message {
  58. m := &testpb.TestWeak{}
  59. m.SetWeakMessage1(&weakpb.WeakImportMessage1{
  60. A: proto.Int32(1),
  61. })
  62. return m
  63. }(),
  64. want: `<nil>`,
  65. skip: !flags.ProtoLegacy,
  66. }}
  67. for _, tt := range tests {
  68. t.Run("", func(t *testing.T) {
  69. if tt.skip {
  70. t.SkipNow()
  71. }
  72. err := proto.CheckInitialized(tt.m)
  73. got := "<nil>"
  74. if err != nil {
  75. got = fmt.Sprintf("%q", err)
  76. }
  77. if !strings.Contains(got, tt.want) {
  78. t.Errorf("CheckInitialized(m):\n got: %v\nwant contains: %v\nMessage:\n%v", got, tt.want, prototext.Format(tt.m))
  79. }
  80. })
  81. }
  82. }