blob: 992db0dda3e9df5078cb0f483f2fc574301509d6 [file] [log] [blame]
Damien Neil6e40b322019-10-01 13:05:16 -07001// 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 "testing"
9
10 "google.golang.org/protobuf/internal/encoding/pack"
11 "google.golang.org/protobuf/internal/flags"
12 "google.golang.org/protobuf/proto"
13
14 testpb "google.golang.org/protobuf/internal/testprotos/test"
15 weakpb "google.golang.org/protobuf/internal/testprotos/test/weak1"
16)
17
18func TestWeak(t *testing.T) {
19 if !flags.ProtoLegacy {
20 t.SkipNow()
21 }
22
23 m := new(testpb.TestWeak)
24 b := pack.Message{
25 pack.Tag{1, pack.BytesType}, pack.LengthPrefix(pack.Message{
26 pack.Tag{1, pack.VarintType}, pack.Varint(1000),
27 }),
28 pack.Tag{2, pack.BytesType}, pack.LengthPrefix(pack.Message{
29 pack.Tag{1, pack.VarintType}, pack.Varint(2000),
30 }),
31 }.Marshal()
32 if err := proto.Unmarshal(b, m); err != nil {
33 t.Errorf("Unmarshal error: %v", err)
34 }
35
36 mw := m.GetWeakMessage1().(*weakpb.WeakImportMessage1)
37 if mw.GetA() != 1000 {
38 t.Errorf("m.WeakMessage1.a = %d, want %d", mw.GetA(), 1000)
39 }
40
41 if len(m.ProtoReflect().GetUnknown()) == 0 {
42 t.Errorf("m has no unknown fields, expected at least something")
43 }
44
45 if n := proto.Size(m); n != len(b) {
46 t.Errorf("Size() = %d, want %d", n, len(b))
47 }
48
49 b2, err := proto.Marshal(m)
50 if err != nil {
51 t.Errorf("Marshal error: %v", err)
52 }
53 if len(b2) != len(b) {
54 t.Errorf("len(Marshal) = %d, want %d", len(b2), len(b))
55 }
56}
57
58func TestWeakNil(t *testing.T) {
59 if !flags.ProtoLegacy {
60 t.SkipNow()
61 }
62
63 m := new(testpb.TestWeak)
64 if v, ok := m.GetWeakMessage1().(*weakpb.WeakImportMessage1); !ok || v != nil {
65 t.Errorf("m.GetWeakMessage1() = type %[1]T(%[1]v), want (*weakpb.WeakImportMessage1)", v)
66 }
67}
68
69func TestWeakMarshalNil(t *testing.T) {
70 if !flags.ProtoLegacy {
71 t.SkipNow()
72 }
73
74 m := new(testpb.TestWeak)
75 m.SetWeakMessage1(nil)
76 if b, err := proto.Marshal(m); err != nil || len(b) != 0 {
77 t.Errorf("Marshal(weak field set to nil) = [%x], %v; want [], nil", b, err)
78 }
79 m.SetWeakMessage1((*weakpb.WeakImportMessage1)(nil))
80 if b, err := proto.Marshal(m); err != nil || len(b) != 0 {
81 t.Errorf("Marshal(weak field set to typed nil) = [%x], %v; want [], nil", b, err)
82 }
83}