github.com/bazelbuild/bazel-gazelle@v0.36.1-0.20240520142334-61b277ba6fed/internal/go_repository_test.go (about)

     1  /* Copyright 2019 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 bazel_test
    17  
    18  import (
    19  	"bytes"
    20  	"os"
    21  	"os/exec"
    22  	"path/filepath"
    23  	"strings"
    24  	"testing"
    25  
    26  	"github.com/bazelbuild/bazel-gazelle/testtools"
    27  	"github.com/bazelbuild/rules_go/go/tools/bazel_testing"
    28  )
    29  
    30  var testArgs = bazel_testing.Args{
    31  	Main: `
    32  -- BUILD.bazel --
    33  load("@bazel_gazelle//:def.bzl", "gazelle")
    34  
    35  # gazelle:prefix example.com/m
    36  
    37  gazelle(name = "gazelle")
    38  
    39  gazelle(
    40      name = "gazelle-update-repos",
    41      args = [
    42          "-from_file=go.mod",
    43          "-to_macro=deps.bzl%go_repositories",
    44      ],
    45      command = "update-repos",
    46  )
    47  
    48  -- go.mod --
    49  module example.com/m
    50  
    51  go 1.15
    52  -- hello.go --
    53  package main
    54  
    55  func main() {}
    56  `,
    57  	WorkspaceSuffix: `
    58  load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")
    59  
    60  gazelle_dependencies(
    61  	go_env = {
    62  		"GOPRIVATE": "example.com/m",
    63  		"GOSUMDB": "off",
    64  	},
    65  )
    66  
    67  # gazelle:repo test
    68  
    69  go_repository(
    70      name = "errors_go_git",
    71      importpath = "github.com/pkg/errors",
    72      commit = "30136e27e2ac8d167177e8a583aa4c3fea5be833",
    73      patches = ["@bazel_gazelle//internal:repository_rules_test_errors.patch"],
    74      patch_args = ["-p1"],
    75      build_naming_convention = "go_default_library",
    76  )
    77  
    78  go_repository(
    79      name = "errors_go_mod",
    80      importpath = "github.com/pkg/errors",
    81      version = "v0.8.1",
    82      sum ="h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=",
    83  )
    84  
    85  go_repository(
    86      name = "org_golang_x_xerrors",    
    87  		importpath = "golang.org/x/xerrors",
    88      sum = "h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=",
    89      version = "v0.0.0-20200804184101-5ec99f83aff1",
    90  )
    91  
    92  go_repository(
    93  		name = "com_github_apex_log",
    94  		build_directives = ["gazelle:exclude handlers"],
    95  		importpath = "github.com/apex/log",
    96  		sum = "h1:J5rld6WVFi6NxA6m8GJ1LJqu3+GiTFIt3mYv27gdQWI=",
    97  		version = "v1.1.0",
    98  )
    99  `,
   100  }
   101  
   102  func TestMain(m *testing.M) {
   103  	bazel_testing.TestMain(m, testArgs)
   104  }
   105  
   106  func TestBuild(t *testing.T) {
   107  	if err := bazel_testing.RunBazel("build", "@errors_go_git//:errors", "@errors_go_mod//:go_default_library"); err != nil {
   108  		t.Fatal(err)
   109  	}
   110  }
   111  
   112  func TestDirectives(t *testing.T) {
   113  	err := bazel_testing.RunBazel("query", "@com_github_apex_log//handlers/...")
   114  	if err == nil {
   115  		t.Fatal("Should not generate build files for @com_github_apex_log//handlers/...")
   116  	}
   117  	if !strings.Contains(err.Error(), "no targets found beneath 'handlers'") {
   118  		t.Fatal("Unexpected error:\n", err)
   119  	}
   120  }
   121  
   122  func TestRepoConfig(t *testing.T) {
   123  	if err := bazel_testing.RunBazel("build", "@bazel_gazelle_go_repository_config//:all"); err != nil {
   124  		t.Fatal(err)
   125  	}
   126  	outputBase, err := getBazelOutputBase()
   127  	if err != nil {
   128  		t.Fatal(err)
   129  	}
   130  	outDir := filepath.Join(outputBase, "external/bazel_gazelle_go_repository_config")
   131  	testtools.CheckFiles(t, outDir, []testtools.FileSpec{
   132  		{
   133  			Path: "WORKSPACE",
   134  			Content: `
   135  # Code generated by generate_repo_config.go; DO NOT EDIT.
   136  
   137  go_repository(
   138      name = "com_github_apex_log",
   139      importpath = "github.com/apex/log",
   140  )
   141  
   142  go_repository(
   143      name = "errors_go_git",
   144      build_naming_convention = "go_default_library",
   145      importpath = "github.com/pkg/errors",
   146  )
   147  
   148  go_repository(
   149      name = "errors_go_mod",
   150      importpath = "github.com/pkg/errors",
   151  )
   152  
   153  go_repository(
   154      name = "org_golang_x_xerrors",
   155      importpath = "golang.org/x/xerrors",
   156  )
   157  `,
   158  		},
   159  	})
   160  }
   161  
   162  func TestModcacheRW(t *testing.T) {
   163  	if err := bazel_testing.RunBazel("query", "@errors_go_mod//:go_default_library"); err != nil {
   164  		t.Fatal(err)
   165  	}
   166  	out, err := bazel_testing.BazelOutput("info", "output_base")
   167  	if err != nil {
   168  		t.Fatal(err)
   169  	}
   170  	outputBase := strings.TrimSpace(string(out))
   171  	dir := filepath.Join(outputBase, "external/bazel_gazelle_go_repository_cache/pkg/mod/github.com/pkg/errors@v0.8.1")
   172  	info, err := os.Stat(dir)
   173  	if err != nil {
   174  		t.Fatal(err)
   175  	}
   176  	if info.Mode()&0o200 == 0 {
   177  		t.Fatal("module cache is read-only")
   178  	}
   179  }
   180  
   181  func TestRepoCacheContainsGoEnv(t *testing.T) {
   182  	if err := bazel_testing.RunBazel("query", "@errors_go_mod//:go_default_library"); err != nil {
   183  		t.Fatal(err)
   184  	}
   185  	outputBase, err := getBazelOutputBase()
   186  	if err != nil {
   187  		t.Fatal(err)
   188  	}
   189  	goEnvPath := filepath.Join(outputBase, "external/bazel_gazelle_go_repository_cache", "go.env")
   190  	gotBytes, err := os.ReadFile(goEnvPath)
   191  	if err != nil {
   192  		t.Fatalf("could not read file %s: %v", goEnvPath, err)
   193  	}
   194  	for _, want := range []string{"GOPRIVATE='example.com/m'", "GOSUMDB='off'"} {
   195  		if !strings.Contains(string(gotBytes), want) {
   196  			t.Fatalf("go.env did not contain %s", want)
   197  		}
   198  	}
   199  }
   200  
   201  // TODO(bazelbuild/rules_go#2189): call bazel_testing.BazelOutput once implemented.
   202  func getBazelOutputBase() (string, error) {
   203  	cmd := exec.Command("bazel", "info", "output_base")
   204  	for _, e := range os.Environ() {
   205  		// Filter environment variables set by the bazel test wrapper script.
   206  		// These confuse recursive invocations of Bazel.
   207  		if strings.HasPrefix(e, "TEST_") || strings.HasPrefix(e, "RUNFILES_") {
   208  			continue
   209  		}
   210  		cmd.Env = append(cmd.Env, e)
   211  	}
   212  	buf := &bytes.Buffer{}
   213  	cmd.Stdout = buf
   214  	if err := cmd.Run(); err != nil {
   215  		return "", err
   216  	}
   217  	return strings.TrimSpace(buf.String()), nil
   218  }