protogen_test.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. "flag"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strings"
  13. "testing"
  14. "github.com/golang/protobuf/proto"
  15. descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
  16. pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin"
  17. )
  18. func TestPluginParameters(t *testing.T) {
  19. var flags flag.FlagSet
  20. value := flags.Int("integer", 0, "")
  21. opts := &Options{
  22. ParamFunc: flags.Set,
  23. }
  24. const params = "integer=2"
  25. _, err := New(&pluginpb.CodeGeneratorRequest{
  26. Parameter: proto.String(params),
  27. }, opts)
  28. if err != nil {
  29. t.Errorf("New(generator parameters %q): %v", params, err)
  30. }
  31. if *value != 2 {
  32. t.Errorf("New(generator parameters %q): integer=%v, want 2", params, *value)
  33. }
  34. }
  35. func TestPluginParameterErrors(t *testing.T) {
  36. for _, parameter := range []string{
  37. "unknown=1",
  38. "boolean=error",
  39. } {
  40. var flags flag.FlagSet
  41. flags.Bool("boolean", false, "")
  42. opts := &Options{
  43. ParamFunc: flags.Set,
  44. }
  45. _, err := New(&pluginpb.CodeGeneratorRequest{
  46. Parameter: proto.String(parameter),
  47. }, opts)
  48. if err == nil {
  49. t.Errorf("New(generator parameters %q): want error, got nil", parameter)
  50. }
  51. }
  52. }
  53. func TestFiles(t *testing.T) {
  54. gen, err := New(makeRequest(t, "testdata/go_package/no_go_package_import.proto"), nil)
  55. if err != nil {
  56. t.Fatal(err)
  57. }
  58. for _, test := range []struct {
  59. path string
  60. wantGenerate bool
  61. }{
  62. {
  63. path: "go_package/no_go_package_import.proto",
  64. wantGenerate: true,
  65. },
  66. {
  67. path: "go_package/no_go_package.proto",
  68. wantGenerate: false,
  69. },
  70. } {
  71. f, ok := gen.FileByName(test.path)
  72. if !ok {
  73. t.Errorf("%q: not found by gen.FileByName", test.path)
  74. continue
  75. }
  76. if f.Generate != test.wantGenerate {
  77. t.Errorf("%q: Generate=%v, want %v", test.path, f.Generate, test.wantGenerate)
  78. }
  79. }
  80. }
  81. func TestPackageNamesAndPaths(t *testing.T) {
  82. const (
  83. filename = "dir/filename.proto"
  84. protoPackageName = "proto.package"
  85. )
  86. for _, test := range []struct {
  87. desc string
  88. parameter string
  89. goPackageOption string
  90. generate bool
  91. wantPackageName GoPackageName
  92. wantImportPath GoImportPath
  93. wantFilenamePrefix string
  94. }{
  95. {
  96. desc: "no parameters, no go_package option",
  97. generate: true,
  98. wantPackageName: "proto_package",
  99. wantImportPath: "dir",
  100. wantFilenamePrefix: "dir/filename",
  101. },
  102. {
  103. desc: "go_package option sets import path",
  104. goPackageOption: "golang.org/x/foo",
  105. generate: true,
  106. wantPackageName: "foo",
  107. wantImportPath: "golang.org/x/foo",
  108. wantFilenamePrefix: "golang.org/x/foo/filename",
  109. },
  110. {
  111. desc: "go_package option sets import path and package",
  112. goPackageOption: "golang.org/x/foo;bar",
  113. generate: true,
  114. wantPackageName: "bar",
  115. wantImportPath: "golang.org/x/foo",
  116. wantFilenamePrefix: "golang.org/x/foo/filename",
  117. },
  118. {
  119. desc: "go_package option sets package",
  120. goPackageOption: "foo",
  121. generate: true,
  122. wantPackageName: "foo",
  123. wantImportPath: "dir",
  124. wantFilenamePrefix: "dir/filename",
  125. },
  126. {
  127. desc: "command line sets import path for a file",
  128. parameter: "Mdir/filename.proto=golang.org/x/bar",
  129. goPackageOption: "golang.org/x/foo",
  130. generate: true,
  131. wantPackageName: "foo",
  132. wantImportPath: "golang.org/x/bar",
  133. wantFilenamePrefix: "golang.org/x/foo/filename",
  134. },
  135. {
  136. desc: "import_path parameter sets import path of generated files",
  137. parameter: "import_path=golang.org/x/bar",
  138. goPackageOption: "golang.org/x/foo",
  139. generate: true,
  140. wantPackageName: "foo",
  141. wantImportPath: "golang.org/x/bar",
  142. wantFilenamePrefix: "golang.org/x/foo/filename",
  143. },
  144. {
  145. desc: "import_path parameter does not set import path of dependencies",
  146. parameter: "import_path=golang.org/x/bar",
  147. goPackageOption: "golang.org/x/foo",
  148. generate: false,
  149. wantPackageName: "foo",
  150. wantImportPath: "golang.org/x/foo",
  151. wantFilenamePrefix: "golang.org/x/foo/filename",
  152. },
  153. } {
  154. context := fmt.Sprintf(`
  155. TEST: %v
  156. --go_out=%v:.
  157. file %q: generate=%v
  158. option go_package = %q;
  159. `,
  160. test.desc, test.parameter, filename, test.generate, test.goPackageOption)
  161. req := &pluginpb.CodeGeneratorRequest{
  162. Parameter: proto.String(test.parameter),
  163. ProtoFile: []*descpb.FileDescriptorProto{
  164. {
  165. Name: proto.String(filename),
  166. Package: proto.String(protoPackageName),
  167. Options: &descpb.FileOptions{
  168. GoPackage: proto.String(test.goPackageOption),
  169. },
  170. },
  171. },
  172. }
  173. if test.generate {
  174. req.FileToGenerate = []string{filename}
  175. }
  176. gen, err := New(req, nil)
  177. if err != nil {
  178. t.Errorf("%vNew(req) = %v", context, err)
  179. continue
  180. }
  181. gotFile, ok := gen.FileByName(filename)
  182. if !ok {
  183. t.Errorf("%v%v: missing file info", context, filename)
  184. continue
  185. }
  186. if got, want := gotFile.GoPackageName, test.wantPackageName; got != want {
  187. t.Errorf("%vGoPackageName=%v, want %v", context, got, want)
  188. }
  189. if got, want := gotFile.GoImportPath, test.wantImportPath; got != want {
  190. t.Errorf("%vGoImportPath=%v, want %v", context, got, want)
  191. }
  192. if got, want := gotFile.GeneratedFilenamePrefix, test.wantFilenamePrefix; got != want {
  193. t.Errorf("%vGeneratedFilenamePrefix=%v, want %v", context, got, want)
  194. }
  195. }
  196. }
  197. func TestPackageNameInference(t *testing.T) {
  198. gen, err := New(&pluginpb.CodeGeneratorRequest{
  199. ProtoFile: []*descpb.FileDescriptorProto{
  200. {
  201. Name: proto.String("dir/file1.proto"),
  202. Package: proto.String("proto.package"),
  203. },
  204. {
  205. Name: proto.String("dir/file2.proto"),
  206. Package: proto.String("proto.package"),
  207. Options: &descpb.FileOptions{
  208. GoPackage: proto.String("foo"),
  209. },
  210. },
  211. },
  212. FileToGenerate: []string{"dir/file1.proto", "dir/file2.proto"},
  213. }, nil)
  214. if err != nil {
  215. t.Fatalf("New(req) = %v", err)
  216. }
  217. if f1, ok := gen.FileByName("dir/file1.proto"); !ok {
  218. t.Errorf("missing file info for dir/file1.proto")
  219. } else if f1.GoPackageName != "foo" {
  220. t.Errorf("dir/file1.proto: GoPackageName=%v, want foo; package name should be derived from dir/file2.proto", f1.GoPackageName)
  221. }
  222. }
  223. func TestInconsistentPackageNames(t *testing.T) {
  224. _, err := New(&pluginpb.CodeGeneratorRequest{
  225. ProtoFile: []*descpb.FileDescriptorProto{
  226. {
  227. Name: proto.String("dir/file1.proto"),
  228. Package: proto.String("proto.package"),
  229. Options: &descpb.FileOptions{
  230. GoPackage: proto.String("golang.org/x/foo"),
  231. },
  232. },
  233. {
  234. Name: proto.String("dir/file2.proto"),
  235. Package: proto.String("proto.package"),
  236. Options: &descpb.FileOptions{
  237. GoPackage: proto.String("golang.org/x/foo;bar"),
  238. },
  239. },
  240. },
  241. FileToGenerate: []string{"dir/file1.proto", "dir/file2.proto"},
  242. }, nil)
  243. if err == nil {
  244. t.Fatalf("inconsistent package names for the same import path: New(req) = nil, want error")
  245. }
  246. }
  247. func TestImports(t *testing.T) {
  248. gen, err := New(&pluginpb.CodeGeneratorRequest{}, nil)
  249. if err != nil {
  250. t.Fatal(err)
  251. }
  252. g := gen.NewGeneratedFile("foo.go", "golang.org/x/foo")
  253. g.P("package foo")
  254. g.P()
  255. for _, importPath := range []GoImportPath{
  256. "golang.org/x/foo",
  257. // Multiple references to the same package.
  258. "golang.org/x/bar",
  259. "golang.org/x/bar",
  260. // Reference to a different package with the same basename.
  261. "golang.org/y/bar",
  262. "golang.org/x/baz",
  263. } {
  264. g.P("var _ = ", GoIdent{GoName: "X", GoImportPath: importPath}, " // ", importPath)
  265. }
  266. want := `package foo
  267. import (
  268. bar "golang.org/x/bar"
  269. baz "golang.org/x/baz"
  270. bar1 "golang.org/y/bar"
  271. )
  272. var _ = X // "golang.org/x/foo"
  273. var _ = bar.X // "golang.org/x/bar"
  274. var _ = bar.X // "golang.org/x/bar"
  275. var _ = bar1.X // "golang.org/y/bar"
  276. var _ = baz.X // "golang.org/x/baz"
  277. `
  278. got, err := g.Content()
  279. if err != nil {
  280. t.Fatalf("g.Content() = %v", err)
  281. }
  282. if want != string(got) {
  283. t.Fatalf(`want:
  284. ==========
  285. %v
  286. ==========
  287. got:
  288. ==========
  289. %v
  290. ==========`,
  291. want, string(got))
  292. }
  293. }
  294. // makeRequest returns a CodeGeneratorRequest for the given protoc inputs.
  295. //
  296. // It does this by running protoc with the current binary as the protoc-gen-go
  297. // plugin. This "plugin" produces a single file, named 'request', which contains
  298. // the code generator request.
  299. func makeRequest(t *testing.T, args ...string) *pluginpb.CodeGeneratorRequest {
  300. workdir, err := ioutil.TempDir("", "test")
  301. if err != nil {
  302. t.Fatal(err)
  303. }
  304. defer os.RemoveAll(workdir)
  305. cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
  306. cmd.Args = append(cmd.Args, "--go_out="+workdir, "-Itestdata")
  307. cmd.Args = append(cmd.Args, args...)
  308. cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_PLUGIN=1")
  309. out, err := cmd.CombinedOutput()
  310. if len(out) > 0 || err != nil {
  311. t.Log("RUNNING: ", strings.Join(cmd.Args, " "))
  312. }
  313. if len(out) > 0 {
  314. t.Log(string(out))
  315. }
  316. if err != nil {
  317. t.Fatalf("protoc: %v", err)
  318. }
  319. b, err := ioutil.ReadFile(filepath.Join(workdir, "request"))
  320. if err != nil {
  321. t.Fatal(err)
  322. }
  323. req := &pluginpb.CodeGeneratorRequest{}
  324. if err := proto.UnmarshalText(string(b), req); err != nil {
  325. t.Fatal(err)
  326. }
  327. return req
  328. }
  329. func init() {
  330. if os.Getenv("RUN_AS_PROTOC_PLUGIN") != "" {
  331. Run(nil, func(p *Plugin) error {
  332. g := p.NewGeneratedFile("request", "")
  333. return proto.MarshalText(g, p.Request)
  334. })
  335. os.Exit(0)
  336. }
  337. }