weak_test.go 2.2 KB

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