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