github.com/bazelbuild/bazel-watcher@v0.25.2/internal/e2e/symlink_dir/symlink_dir_test.go (about)

     1  package symlink_dir
     2  
     3  import (
     4  	"log"
     5  	"os"
     6  	"path/filepath"
     7  	"testing"
     8  
     9  	"github.com/bazelbuild/bazel-watcher/internal/e2e"
    10  	"github.com/bazelbuild/rules_go/go/tools/bazel_testing"
    11  )
    12  
    13  // bazel_testing.TestMain automatically creates a `WORKSPACE` file at the root if not provided
    14  const mainFiles = `
    15  -- BUILD.bazel --
    16  sh_binary(
    17    name = "simple",
    18    srcs = ["simple.sh"],
    19  )
    20  
    21  -- simple.sh --
    22  printf "Started 1!"
    23  `
    24  
    25  func TestMain(m *testing.M) {
    26  	bazel_testing.TestMain(m, bazel_testing.Args{
    27  		Main: mainFiles,
    28  		SetUp: func() error {
    29  			// creates a directory `./holder` and symlink
    30  			// `./holder/symlinked-workspace` pointing to the normal working
    31  			// directory `./main` created by `bazel_testing.TestMain`
    32  
    33  			// create holder directory
    34  			holder, err := filepath.Abs(filepath.Join("..", "holder"))
    35  			if err != nil {
    36  				log.Fatalf("Error determining absolute path: %v", err)
    37  			}
    38  
    39  			if err = os.Mkdir(holder, 0777); err != nil {
    40  				log.Fatalf("Error making directory: %v", err)
    41  			}
    42  
    43  			// create symlink pointing to the main workspace
    44  			symlinkWd, err := filepath.Abs(filepath.Join(holder, "symlinked-workspace"))
    45  			if err != nil {
    46  				log.Fatalf("Error determining absolute path: %v", err)
    47  			}
    48  
    49  			cwd, err := os.Getwd()
    50  			if err != nil {
    51  				log.Fatalf("Error getting working directory: %v", err)
    52  			}
    53  
    54  			if err = os.Symlink(cwd, symlinkWd); err != nil {
    55  				log.Fatalf("Error creating symlink: %v", err)
    56  			}
    57  
    58  			// chdir via the symlink
    59  			if err = os.Chdir(symlinkWd); err != nil {
    60  				log.Fatalf("Error changing directory: %v", err)
    61  			}
    62  
    63  			return err
    64  		},
    65  	})
    66  }
    67  
    68  // note: the implementation of `workspace.go` uses `os.Getwd` which states "If
    69  // the current directory can be reached via multiple paths (due to symbolic
    70  // links), Getwd may return any one of them." This resulted in inconsistent
    71  // automatic rebuild behavior because `ibazel.go` was not evaluating symlinks.
    72  func TestSymlinkRun(t *testing.T) {
    73  	ibazel := e2e.SetUp(t)
    74  	ibazel.Run([]string{}, "//:simple")
    75  	defer ibazel.Kill()
    76  
    77  	ibazel.ExpectOutput("Started 1!")
    78  
    79  	e2e.MustWriteFile(t, "simple.sh", `printf "Started 2!"`)
    80  	ibazel.ExpectOutput("Started 2!")
    81  }