forked from phst/runfiles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunfiles_test.go
103 lines (95 loc) · 2.49 KB
/
runfiles_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright 2020, 2021, 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runfiles_test
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/phst/runfiles"
)
func ExamplePath() {
path, err := runfiles.Path("com_github_phst_runfiles/test.txt")
if err != nil {
panic(err)
}
b, err := os.ReadFile(path)
if err != nil {
panic(err)
}
fmt.Println(string(b))
// Output: hi!
}
func ExampleRunfiles() {
r, err := runfiles.New()
if err != nil {
panic(err)
}
// The binary “testprog” is itself built with Bazel, and needs
// runfiles.
prog, err := r.Path("com_github_phst_runfiles/testprog/testprog")
if err != nil {
panic(err)
}
cmd := exec.Command(prog)
// We add r.Env() after os.Environ() so that runfile environment
// variables override anything set in the process environment.
cmd.Env = append(os.Environ(), r.Env()...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
// Output: hi!
}
func TestPath_errors(t *testing.T) {
r, err := runfiles.New()
if err != nil {
t.Fatal(err)
}
for _, s := range []string{"", "..", "../", "a/../b", "a//b", "a/./b", "/a"} {
t.Run(s, func(t *testing.T) {
if got, err := r.Path(s); err == nil {
t.Errorf("got %q, want error", got)
}
})
}
}
func TestRunfiles_zero(t *testing.T) {
var r runfiles.Runfiles
if got, err := r.Path("a"); err == nil {
t.Errorf("Path: got %q, want error", got)
}
if got := r.Env(); got != nil {
t.Errorf("Env: got %v, want nil", got)
}
}
func TestRunfiles_empty(t *testing.T) {
dir := t.TempDir()
manifest := filepath.Join(dir, "manifest")
if err := os.WriteFile(manifest, []byte("__init__.py \n"), 0600); err != nil {
t.Fatal(err)
}
r, err := runfiles.New(runfiles.ManifestFile(manifest))
if err != nil {
t.Fatal(err)
}
_, got := r.Path("__init__.py")
want := runfiles.ErrEmpty
if !errors.Is(got, want) {
t.Errorf("Path for empty file: got error %q, want something that wraps %q", got, want)
}
}