blob: d0ed8eaa8578549065e3579dd0f4e999ad1180fb [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 main
6
7import (
8 "bytes"
9 "flag"
10 "go/build"
11 "io/ioutil"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "strings"
17 "testing"
18)
19
20// Set --regenerate to regenerate the golden files.
21var regenerate = flag.Bool("regenerate", false, "regenerate golden files")
22
23// When the environment variable RUN_AS_PROTOC_GEN_GO is set, we skip running
24// tests and instead act as protoc-gen-go. This allows the test binary to
25// pass itself to protoc.
26func init() {
27 if os.Getenv("RUN_AS_PROTOC_GEN_GO") != "" {
28 main()
29 os.Exit(0)
30 }
31}
32
33func TestGolden(t *testing.T) {
34 workdir, err := ioutil.TempDir("", "proto-test")
35 if err != nil {
36 t.Fatal(err)
37 }
38 defer os.RemoveAll(workdir)
39
40 // Find all the proto files we need to compile. We assume that each directory
41 // contains the files for a single package.
42 supportTypeAliases := hasReleaseTag("go1.9")
43 packages := map[string][]string{}
44 err = filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error {
45 if filepath.Base(path) == "import_public" && !supportTypeAliases {
46 // Public imports require type alias support.
47 return filepath.SkipDir
48 }
49 if !strings.HasSuffix(path, ".proto") {
50 return nil
51 }
52 dir := filepath.Dir(path)
53 packages[dir] = append(packages[dir], path)
54 return nil
55 })
56 if err != nil {
57 t.Fatal(err)
58 }
59
60 // Compile each package, using this binary as protoc-gen-go.
61 for _, sources := range packages {
62 args := []string{"-Itestdata", "--go_out=plugins=grpc,paths=source_relative:" + workdir}
63 args = append(args, sources...)
64 protoc(t, args)
65 }
66
67 // Compare each generated file to the golden version.
68 filepath.Walk(workdir, func(genPath string, info os.FileInfo, _ error) error {
69 if info.IsDir() {
70 return nil
71 }
72
73 // For each generated file, figure out the path to the corresponding
74 // golden file in the testdata directory.
75 relPath, err := filepath.Rel(workdir, genPath)
76 if err != nil {
77 t.Errorf("filepath.Rel(%q, %q): %v", workdir, genPath, err)
78 return nil
79 }
80 if filepath.SplitList(relPath)[0] == ".." {
81 t.Errorf("generated file %q is not relative to %q", genPath, workdir)
82 }
83 goldenPath := filepath.Join("testdata", relPath)
84
85 got, err := ioutil.ReadFile(genPath)
86 if err != nil {
87 t.Error(err)
88 return nil
89 }
90 if *regenerate {
91 // If --regenerate set, just rewrite the golden files.
92 err := ioutil.WriteFile(goldenPath, got, 0666)
93 if err != nil {
94 t.Error(err)
95 }
96 return nil
97 }
98
99 want, err := ioutil.ReadFile(goldenPath)
100 if err != nil {
101 t.Error(err)
102 return nil
103 }
104
105 want = fdescRE.ReplaceAll(want, nil)
106 got = fdescRE.ReplaceAll(got, nil)
107 if bytes.Equal(got, want) {
108 return nil
109 }
110
111 cmd := exec.Command("diff", "-u", goldenPath, genPath)
112 out, _ := cmd.CombinedOutput()
113 t.Errorf("golden file differs: %v\n%v", relPath, string(out))
114 return nil
115 })
116}
117
118var fdescRE = regexp.MustCompile(`(?ms)^var fileDescriptor.*}`)
119
120func protoc(t *testing.T, args []string) {
121 cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
122 cmd.Args = append(cmd.Args, args...)
123 // We set the RUN_AS_PROTOC_GEN_GO environment variable to indicate that
124 // the subprocess should act as a proto compiler rather than a test.
125 cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_GEN_GO=1")
126 out, err := cmd.CombinedOutput()
127 if len(out) > 0 || err != nil {
128 t.Log("RUNNING: ", strings.Join(cmd.Args, " "))
129 }
130 if len(out) > 0 {
131 t.Log(string(out))
132 }
133 if err != nil {
134 t.Fatalf("protoc: %v", err)
135 }
136}
137
138func hasReleaseTag(want string) bool {
139 for _, tag := range build.Default.ReleaseTags {
140 if tag == want {
141 return true
142 }
143 }
144 return false
145}