| 1 | // Copyright 2014 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 | |
| 5 | // No testdata on Android. |
| 6 | |
| 7 | //go:build !android |
| 8 | |
| 9 | package eg_test |
| 10 | |
| 11 | import ( |
| 12 | "bytes" |
| 13 | "flag" |
| 14 | "fmt" |
| 15 | "go/constant" |
| 16 | "go/format" |
| 17 | "go/types" |
| 18 | "os" |
| 19 | "path/filepath" |
| 20 | "runtime" |
| 21 | "strings" |
| 22 | "testing" |
| 23 | |
| 24 | "github.com/google/go-cmp/cmp" |
| 25 | "golang.org/x/tools/go/packages" |
| 26 | "golang.org/x/tools/internal/testenv" |
| 27 | "golang.org/x/tools/internal/testfiles" |
| 28 | "golang.org/x/tools/refactor/eg" |
| 29 | "golang.org/x/tools/txtar" |
| 30 | ) |
| 31 | |
| 32 | // TODO(adonovan): more tests: |
| 33 | // - of command-line tool |
| 34 | // - of all parts of syntax |
| 35 | // - of applying a template to a package it imports: |
| 36 | // the replacement syntax should use unqualified names for its objects. |
| 37 | |
| 38 | var ( |
| 39 | updateFlag = flag.Bool("update", false, "update the golden files") |
| 40 | verboseFlag = flag.Bool("verbose", false, "show matcher information") |
| 41 | ) |
| 42 | |
| 43 | func Test(t *testing.T) { |
| 44 | testenv.NeedsGoPackages(t) |
| 45 | |
| 46 | switch runtime.GOOS { |
| 47 | case "windows": |
| 48 | t.Skipf("skipping test on %q (no /usr/bin/diff)", runtime.GOOS) |
| 49 | } |
| 50 | |
| 51 | // Each txtar defines a package example.com/template and zero |
| 52 | // or more input packages example.com/in/... on which to apply |
| 53 | // it. The outputs are compared with the corresponding files |
| 54 | // in example.com/out/... |
| 55 | for _, filename := range []string{ |
| 56 | "testdata/a.txtar", |
| 57 | "testdata/b.txtar", |
| 58 | "testdata/c.txtar", |
| 59 | "testdata/d.txtar", |
| 60 | "testdata/e.txtar", |
| 61 | "testdata/f.txtar", |
| 62 | "testdata/g.txtar", |
| 63 | "testdata/h.txtar", |
| 64 | "testdata/i.txtar", |
| 65 | "testdata/j.txtar", |
| 66 | "testdata/bad_type.txtar", |
| 67 | "testdata/no_before.txtar", |
| 68 | "testdata/no_after_return.txtar", |
| 69 | "testdata/type_mismatch.txtar", |
| 70 | "testdata/expr_type_mismatch.txtar", |
| 71 | } { |
| 72 | t.Run(filename, func(t *testing.T) { |
| 73 | // Extract and load packages from test archive. |
| 74 | dir := testfiles.ExtractTxtarFileToTmp(t, filename) |
| 75 | cfg := packages.Config{ |
| 76 | Mode: packages.LoadAllSyntax, |
| 77 | Dir: dir, |
| 78 | } |
| 79 | pkgs, err := packages.Load(&cfg, "example.com/template", "example.com/in/...") |
| 80 | if err != nil { |
| 81 | t.Fatal(err) |
| 82 | } |
| 83 | if packages.PrintErrors(pkgs) > 0 { |
| 84 | t.Fatal("Load: there were errors") |
| 85 | } |
| 86 | |
| 87 | // Find and compile the template. |
| 88 | var template *packages.Package |
| 89 | var inputs []*packages.Package |
| 90 | for _, pkg := range pkgs { |
| 91 | if pkg.Types.Name() == "template" { |
| 92 | template = pkg |
| 93 | } else { |
| 94 | inputs = append(inputs, pkg) |
| 95 | } |
| 96 | } |
| 97 | if template == nil { |
| 98 | t.Fatal("no template package") |
| 99 | } |
| 100 | shouldFail, _ := template.Types.Scope().Lookup("shouldFail").(*types.Const) |
| 101 | xform, err := eg.NewTransformer(template.Fset, template.Types, template.Syntax[0], template.TypesInfo, *verboseFlag) |
| 102 | if err != nil { |
| 103 | if shouldFail == nil { |
| 104 | t.Errorf("NewTransformer(%s): %s", filename, err) |
| 105 | } else if want := constant.StringVal(shouldFail.Val()); !strings.Contains(normalizeAny(err.Error()), want) { |
| 106 | t.Errorf("NewTransformer(%s): got error %q, want error %q", filename, err, want) |
| 107 | } |
| 108 | } else if shouldFail != nil { |
| 109 | t.Errorf("NewTransformer(%s) succeeded unexpectedly; want error %q", |
| 110 | filename, shouldFail.Val()) |
| 111 | } |
| 112 | |
| 113 | // Apply template to each input package. |
| 114 | updated := make(map[string][]byte) |
| 115 | for _, pkg := range inputs { |
| 116 | for _, file := range pkg.Syntax { |
| 117 | filename, err := filepath.Rel(dir, pkg.Fset.File(file.FileStart).Name()) |
| 118 | if err != nil { |
| 119 | t.Fatalf("can't relativize filename: %v", err) |
| 120 | } |
| 121 | |
| 122 | // Apply the transform and reformat. |
| 123 | n := xform.Transform(pkg.TypesInfo, pkg.Types, file) |
| 124 | if n == 0 { |
| 125 | t.Fatalf("%s: no replacements", filename) |
| 126 | } |
| 127 | var got []byte |
| 128 | { |
| 129 | var out bytes.Buffer |
| 130 | format.Node(&out, pkg.Fset, file) // ignore error |
| 131 | got = out.Bytes() |
| 132 | } |
| 133 | |
| 134 | // Compare formatted output with out/<filename> |
| 135 | // Errors here are not fatal, so we can proceed to -update. |
| 136 | outfile := strings.Replace(filename, "in", "out", 1) |
| 137 | updated[outfile] = got |
| 138 | want, err := os.ReadFile(filepath.Join(dir, outfile)) |
| 139 | if err != nil { |
| 140 | t.Errorf("can't read output file: %v", err) |
| 141 | } else if diff := cmp.Diff(want, got); diff != "" { |
| 142 | t.Errorf("Unexpected output:\n%s\n\ngot %s:\n%s\n\nwant %s:\n%s", |
| 143 | diff, |
| 144 | filename, got, outfile, want) |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // -update: replace the .txtar. |
| 150 | if *updateFlag { |
| 151 | ar, err := txtar.ParseFile(filename) |
| 152 | if err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | |
| 156 | var new bytes.Buffer |
| 157 | new.Write(ar.Comment) |
| 158 | for _, file := range ar.Files { |
| 159 | data, ok := updated[file.Name] |
| 160 | if !ok { |
| 161 | data = file.Data |
| 162 | } |
| 163 | fmt.Fprintf(&new, "-- %s --\n%s", file.Name, data) |
| 164 | } |
| 165 | t.Logf("Updating %s...", filename) |
| 166 | os.Remove(filename + ".bak") // ignore error |
| 167 | os.Rename(filename, filename+".bak") // ignore error |
| 168 | if err := os.WriteFile(filename, new.Bytes(), 0666); err != nil { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | } |
| 172 | }) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // normalizeAny replaces occurrences of interface{} with any, for consistent |
| 177 | // output. |
| 178 | func normalizeAny(s string) string { |
| 179 | return strings.ReplaceAll(s, "interface{}", "any") |
| 180 | } |