github.com/bazelbuild/bazel-gazelle@v0.36.1-0.20240520142334-61b277ba6fed/internal/wspace/finder_test.go (about) 1 /* 2 Copyright 2016 The Bazel Authors. All rights reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 package wspace 17 18 import ( 19 "os" 20 "path/filepath" 21 "testing" 22 ) 23 24 func TestFind(t *testing.T) { 25 tmp, err := os.MkdirTemp(os.Getenv("TEST_TEMPDIR"), "") 26 if err != nil { 27 t.Fatal(err) 28 } 29 defer os.RemoveAll(tmp) 30 tmp, err = filepath.EvalSymlinks(tmp) // on macOS, TEST_TEMPDIR is a symlink 31 if err != nil { 32 t.Fatal(err) 33 } 34 if parent, err := FindRepoRoot(tmp); err == nil { 35 t.Skipf("WORKSPACE visible in parent %q of tmp %q", parent, tmp) 36 } 37 38 for _, tc := range []struct { 39 file, testdir string // file == "" ==> do not create file 40 shouldSucceed bool 41 }{ 42 {"", tmp, false}, 43 {filepath.Join(tmp, "WORKSPACE"), tmp, true}, 44 {filepath.Join(tmp, "WORKSPACE.bazel"), tmp, true}, 45 {filepath.Join(tmp, "WORKSPACE.bazel"), filepath.Join(tmp, "dir1"), true}, 46 // Test within a directory name WORKSPACE 47 {filepath.Join(tmp, "WORKSPACE"), filepath.Join(tmp, "dir1", "WORKSPACE", "dir2"), true}, 48 {filepath.Join(tmp, "WORKSPACE.bazel"), filepath.Join(tmp, "dir1", "WORKSPACE", "dir2"), true}, 49 // Test outside a workspace but within a directory named WORKSPACE 50 {filepath.Join(tmp, "WORKSPACE", "file.txt"), filepath.Join(tmp, "dir1"), false}, 51 {filepath.Join(tmp, "WORKSPACE", "file.txt"), filepath.Join(tmp, "WORKSPACE", "dir1"), false}, 52 } { 53 t.Run(tc.file, func(t *testing.T) { 54 if err := os.RemoveAll(tmp); err != nil { 55 t.Fatal(err) 56 } 57 58 if tc.file != "" { 59 // Create a WORKSPACE file 60 if err := os.MkdirAll(filepath.Dir(tc.file), 0o755); err != nil { 61 t.Fatal(err) 62 } 63 64 if err := os.WriteFile(tc.file, nil, 0o755); err != nil { 65 t.Fatal(err) 66 } 67 } 68 69 // Create the testdir dir 70 if err := os.MkdirAll(tc.testdir, 0o755); err != nil { 71 t.Fatal(err) 72 } 73 74 // Look for the file 75 dir, err := FindRepoRoot(tc.testdir) 76 77 if !tc.shouldSucceed { 78 if err == nil { 79 t.Errorf("FindRoot(%q): got %v, wanted failure", tc.testdir, dir) 80 } 81 return 82 } 83 84 if err != nil { 85 t.Errorf("FindRoot(%q): got error %v, wanted %v", tc.testdir, err, tc.file) 86 } 87 88 file := FindWORKSPACEFile(dir) 89 if file != tc.file { 90 t.Errorf("FindWorkspaceFile(FindRoot(%q)): got %v, wanted %v", tc.testdir, file, tc.file) 91 } 92 }) 93 } 94 }