github.com/wolfd/bazel-gazelle@v0.14.0/cmd/gazelle/fix_test.go (about)

     1  /* Copyright 2016 The Bazel Authors. All rights reserved.
     2  
     3  Licensed under the Apache License, Version 2.0 (the "License");
     4  you may not use this file except in compliance with the License.
     5  You may obtain a copy of the License at
     6  
     7     http://www.apache.org/licenses/LICENSE-2.0
     8  
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package main
    17  
    18  import (
    19  	"flag"
    20  	"io/ioutil"
    21  	"os"
    22  	"path/filepath"
    23  	"strings"
    24  	"testing"
    25  
    26  	bzl "github.com/bazelbuild/buildtools/build"
    27  )
    28  
    29  func TestMain(m *testing.M) {
    30  	tmpdir := os.Getenv("TEST_TMPDIR")
    31  	flag.Set("repo_root", tmpdir)
    32  	os.Exit(m.Run())
    33  }
    34  
    35  func defaultArgs(dir string) []string {
    36  	return []string{
    37  		"-repo_root", dir,
    38  		"-go_prefix", "example.com/repo",
    39  		dir,
    40  	}
    41  }
    42  
    43  func TestFixFile(t *testing.T) {
    44  	tmpdir := os.Getenv("TEST_TMPDIR")
    45  	dir, err := ioutil.TempDir(tmpdir, "")
    46  	if err != nil {
    47  		t.Fatalf("ioutil.TempDir(%q, %q) failed with %v; want success", tmpdir, "", err)
    48  	}
    49  	defer os.RemoveAll(dir)
    50  
    51  	stubFile := &bzl.File{
    52  		Path: filepath.Join(dir, "BUILD.bazel"),
    53  		Stmt: []bzl.Expr{
    54  			&bzl.CallExpr{
    55  				X: &bzl.LiteralExpr{Token: "foo_rule"},
    56  				List: []bzl.Expr{
    57  					&bzl.BinaryExpr{
    58  						X:  &bzl.LiteralExpr{Token: "name"},
    59  						Op: "=",
    60  						Y:  &bzl.StringExpr{Value: "bar"},
    61  					},
    62  				},
    63  			},
    64  		},
    65  	}
    66  	if err := fixFile(stubFile.Path, bzl.Format(stubFile)); err != nil {
    67  		t.Errorf("fixFile(%#v) failed with %v; want success", stubFile, err)
    68  		return
    69  	}
    70  
    71  	buf, err := ioutil.ReadFile(stubFile.Path)
    72  	if err != nil {
    73  		t.Errorf("ioutil.ReadFile(%q) failed with %v; want success", stubFile.Path, err)
    74  		return
    75  	}
    76  	if got, want := string(buf), bzl.FormatString(stubFile); got != want {
    77  		t.Errorf("buf = %q; want %q", got, want)
    78  	}
    79  }
    80  
    81  func TestCreateFile(t *testing.T) {
    82  	// Create a directory with a simple .go file.
    83  	tmpdir := os.Getenv("TEST_TMPDIR")
    84  	dir, err := ioutil.TempDir(tmpdir, "")
    85  	if err != nil {
    86  		t.Fatalf("ioutil.TempDir(%q, %q) failed with %v; want success", tmpdir, "", err)
    87  	}
    88  	defer os.RemoveAll(dir)
    89  
    90  	goFile := filepath.Join(dir, "main.go")
    91  	if err = ioutil.WriteFile(goFile, []byte("package main"), 0600); err != nil {
    92  		t.Fatalf("error writing file %q: %v", goFile, err)
    93  	}
    94  
    95  	// Check that Gazelle creates a new file named "BUILD.bazel".
    96  	run(defaultArgs(dir))
    97  
    98  	buildFile := filepath.Join(dir, "BUILD.bazel")
    99  	if _, err = os.Stat(buildFile); err != nil {
   100  		t.Errorf("could not stat BUILD.bazel: %v", err)
   101  	}
   102  }
   103  
   104  func TestUpdateFile(t *testing.T) {
   105  	// Create a directory with a simple .go file and an empty BUILD file.
   106  	tmpdir := os.Getenv("TEST_TMPDIR")
   107  	dir, err := ioutil.TempDir(tmpdir, "")
   108  	if err != nil {
   109  		t.Fatalf("ioutil.TempDir(%q, %q) failed with %v; want success", tmpdir, "", err)
   110  	}
   111  	defer os.RemoveAll(dir)
   112  
   113  	goFile := filepath.Join(dir, "main.go")
   114  	if err = ioutil.WriteFile(goFile, []byte("package main"), 0600); err != nil {
   115  		t.Fatalf("error writing file %q: %v", goFile, err)
   116  	}
   117  
   118  	buildFile := filepath.Join(dir, "BUILD")
   119  	if err = ioutil.WriteFile(buildFile, nil, 0600); err != nil {
   120  		t.Fatalf("error writing file %q: %v", buildFile, err)
   121  	}
   122  
   123  	// Check that Gazelle updates the BUILD file in place.
   124  	run(defaultArgs(dir))
   125  	if st, err := os.Stat(buildFile); err != nil {
   126  		t.Errorf("could not stat BUILD: %v", err)
   127  	} else if st.Size() == 0 {
   128  		t.Errorf("BUILD was not updated")
   129  	}
   130  
   131  	if _, err = os.Stat(filepath.Join(dir, "BUILD.bazel")); err == nil {
   132  		t.Errorf("BUILD.bazel should not exist")
   133  	}
   134  }
   135  
   136  func TestReadWriteDir(t *testing.T) {
   137  	buildInFile := fileSpec{
   138  		path: "in/BUILD.in",
   139  		content: `
   140  go_binary(
   141      name = "hello",
   142      pure = "on",
   143  )
   144  `,
   145  	}
   146  	buildSrcFile := fileSpec{
   147  		path:    "src/BUILD.bazel",
   148  		content: `# src build file`,
   149  	}
   150  	oldFiles := []fileSpec{
   151  		buildInFile,
   152  		buildSrcFile,
   153  		{
   154  			path: "src/hello.go",
   155  			content: `
   156  package main
   157  
   158  func main() {}
   159  `,
   160  		}, {
   161  			path:    "out/BUILD",
   162  			content: `this should get replaced`,
   163  		},
   164  	}
   165  
   166  	for _, tc := range []struct {
   167  		desc string
   168  		args []string
   169  		want []fileSpec
   170  	}{
   171  		{
   172  			desc: "read",
   173  			args: []string{
   174  				"-repo_root={{dir}}/src",
   175  				"-experimental_read_build_files_dir={{dir}}/in",
   176  				"-build_file_name=BUILD.bazel,BUILD,BUILD.in",
   177  				"-go_prefix=example.com/repo",
   178  				"{{dir}}/src",
   179  			},
   180  			want: []fileSpec{
   181  				buildInFile,
   182  				{
   183  					path: "src/BUILD.bazel",
   184  					content: `
   185  load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
   186  
   187  go_binary(
   188      name = "hello",
   189      embed = [":go_default_library"],
   190      pure = "on",
   191      visibility = ["//visibility:public"],
   192  )
   193  
   194  go_library(
   195      name = "go_default_library",
   196      srcs = ["hello.go"],
   197      importpath = "example.com/repo",
   198      visibility = ["//visibility:private"],
   199  )
   200  `,
   201  				},
   202  			},
   203  		}, {
   204  			desc: "write",
   205  			args: []string{
   206  				"-repo_root={{dir}}/src",
   207  				"-experimental_write_build_files_dir={{dir}}/out",
   208  				"-build_file_name=BUILD.bazel,BUILD,BUILD.in",
   209  				"-go_prefix=example.com/repo",
   210  				"{{dir}}/src",
   211  			},
   212  			want: []fileSpec{
   213  				buildInFile,
   214  				buildSrcFile,
   215  				{
   216  					path: "out/BUILD",
   217  					content: `
   218  load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
   219  
   220  # src build file
   221  
   222  go_library(
   223      name = "go_default_library",
   224      srcs = ["hello.go"],
   225      importpath = "example.com/repo",
   226      visibility = ["//visibility:private"],
   227  )
   228  
   229  go_binary(
   230      name = "repo",
   231      embed = [":go_default_library"],
   232      visibility = ["//visibility:public"],
   233  )
   234  `,
   235  				},
   236  			},
   237  		}, {
   238  			desc: "read_and_write",
   239  			args: []string{
   240  				"-repo_root={{dir}}/src",
   241  				"-experimental_read_build_files_dir={{dir}}/in",
   242  				"-experimental_write_build_files_dir={{dir}}/out",
   243  				"-build_file_name=BUILD.bazel,BUILD,BUILD.in",
   244  				"-go_prefix=example.com/repo",
   245  				"{{dir}}/src",
   246  			},
   247  			want: []fileSpec{
   248  				buildInFile,
   249  				{
   250  					path: "out/BUILD",
   251  					content: `
   252  load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
   253  
   254  go_binary(
   255      name = "hello",
   256      embed = [":go_default_library"],
   257      pure = "on",
   258      visibility = ["//visibility:public"],
   259  )
   260  
   261  go_library(
   262      name = "go_default_library",
   263      srcs = ["hello.go"],
   264      importpath = "example.com/repo",
   265      visibility = ["//visibility:private"],
   266  )
   267  `,
   268  				},
   269  			},
   270  		},
   271  	} {
   272  		t.Run(tc.desc, func(t *testing.T) {
   273  			dir, err := createFiles(oldFiles)
   274  			if err != nil {
   275  				t.Fatal(err)
   276  			}
   277  			defer os.RemoveAll(dir)
   278  			replacer := strings.NewReplacer("{{dir}}", dir, "/", string(os.PathSeparator))
   279  			for i := range tc.args {
   280  				tc.args[i] = replacer.Replace(tc.args[i])
   281  			}
   282  			if err := run(tc.args); err != nil {
   283  				t.Error(err)
   284  			}
   285  			checkFiles(t, dir, tc.want)
   286  		})
   287  	}
   288  }