protogen_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 protogen
  5. import (
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "testing"
  12. "github.com/golang/protobuf/proto"
  13. pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin"
  14. )
  15. func TestFiles(t *testing.T) {
  16. gen, err := New(makeRequest(t, "testdata/go_package/no_go_package_import.proto"))
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. for _, test := range []struct {
  21. path string
  22. wantGenerate bool
  23. }{
  24. {
  25. path: "go_package/no_go_package_import.proto",
  26. wantGenerate: true,
  27. },
  28. {
  29. path: "go_package/no_go_package.proto",
  30. wantGenerate: false,
  31. },
  32. } {
  33. f, ok := gen.FileByName(test.path)
  34. if !ok {
  35. t.Errorf("%q: not found by gen.FileByName", test.path)
  36. continue
  37. }
  38. if f.Generate != test.wantGenerate {
  39. t.Errorf("%q: Generate=%v, want %v", test.path, f.Generate, test.wantGenerate)
  40. }
  41. }
  42. }
  43. // makeRequest returns a CodeGeneratorRequest for the given protoc inputs.
  44. //
  45. // It does this by running protoc with the current binary as the protoc-gen-go
  46. // plugin. This "plugin" produces a single file, named 'request', which contains
  47. // the code generator request.
  48. func makeRequest(t *testing.T, args ...string) *pluginpb.CodeGeneratorRequest {
  49. workdir, err := ioutil.TempDir("", "test")
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. defer os.RemoveAll(workdir)
  54. cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
  55. cmd.Args = append(cmd.Args, "--go_out="+workdir, "-Itestdata")
  56. cmd.Args = append(cmd.Args, args...)
  57. cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_PLUGIN=1")
  58. out, err := cmd.CombinedOutput()
  59. if len(out) > 0 || err != nil {
  60. t.Log("RUNNING: ", strings.Join(cmd.Args, " "))
  61. }
  62. if len(out) > 0 {
  63. t.Log(string(out))
  64. }
  65. if err != nil {
  66. t.Fatalf("protoc: %v", err)
  67. }
  68. b, err := ioutil.ReadFile(filepath.Join(workdir, "request"))
  69. if err != nil {
  70. t.Fatal(err)
  71. }
  72. req := &pluginpb.CodeGeneratorRequest{}
  73. if err := proto.UnmarshalText(string(b), req); err != nil {
  74. t.Fatal(err)
  75. }
  76. return req
  77. }
  78. func init() {
  79. if os.Getenv("RUN_AS_PROTOC_PLUGIN") != "" {
  80. Run(func(p *Plugin) error {
  81. g := p.NewGeneratedFile("request")
  82. return proto.MarshalText(g, p.Request)
  83. })
  84. os.Exit(0)
  85. }
  86. }