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