annotation_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2018 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 main
  5. import (
  6. "bytes"
  7. "io/ioutil"
  8. "testing"
  9. "google.golang.org/protobuf/encoding/prototext"
  10. "google.golang.org/protobuf/internal/fieldnum"
  11. "google.golang.org/protobuf/proto"
  12. "google.golang.org/protobuf/types/descriptorpb"
  13. )
  14. func TestAnnotations(t *testing.T) {
  15. sourceFile, err := ioutil.ReadFile("testdata/annotations/annotations.pb.go")
  16. if err != nil {
  17. t.Fatal(err)
  18. }
  19. metaFile, err := ioutil.ReadFile("testdata/annotations/annotations.pb.go.meta")
  20. if err != nil {
  21. t.Fatal(err)
  22. }
  23. gotInfo := &descriptorpb.GeneratedCodeInfo{}
  24. if err := prototext.Unmarshal(metaFile, gotInfo); err != nil {
  25. t.Fatalf("can't parse meta file: %v", err)
  26. }
  27. wantInfo := &descriptorpb.GeneratedCodeInfo{}
  28. for _, want := range []struct {
  29. prefix, text, suffix string
  30. path []int32
  31. }{{
  32. "type ", "AnnotationsTestEnum", " int32",
  33. []int32{fieldnum.FileDescriptorProto_EnumType, 0},
  34. }, {
  35. "\t", "AnnotationsTestEnum_ANNOTATIONS_TEST_ENUM_VALUE", " AnnotationsTestEnum = 0",
  36. []int32{fieldnum.FileDescriptorProto_EnumType, 0, fieldnum.EnumDescriptorProto_Value, 0},
  37. }, {
  38. "type ", "AnnotationsTestMessage", " struct {",
  39. []int32{fieldnum.FileDescriptorProto_MessageType, 0},
  40. }, {
  41. "\t", "AnnotationsTestField", " ",
  42. []int32{fieldnum.FileDescriptorProto_MessageType, 0, fieldnum.DescriptorProto_Field, 0},
  43. }, {
  44. "func (x *AnnotationsTestMessage) ", "GetAnnotationsTestField", "() string {",
  45. []int32{fieldnum.FileDescriptorProto_MessageType, 0, fieldnum.DescriptorProto_Field, 0},
  46. }} {
  47. s := want.prefix + want.text + want.suffix
  48. pos := bytes.Index(sourceFile, []byte(s))
  49. if pos < 0 {
  50. t.Errorf("source file does not contain: %v", s)
  51. continue
  52. }
  53. begin := pos + len(want.prefix)
  54. end := begin + len(want.text)
  55. wantInfo.Annotation = append(wantInfo.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
  56. Path: want.path,
  57. Begin: proto.Int32(int32(begin)),
  58. End: proto.Int32(int32(end)),
  59. SourceFile: proto.String("annotations/annotations.proto"),
  60. })
  61. }
  62. if !proto.Equal(gotInfo, wantInfo) {
  63. t.Errorf("unexpected annotations for annotations.proto; got:\n%v\nwant:\n%v", gotInfo, wantInfo)
  64. }
  65. }