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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
// +build !windows
package browserenv
import (
"os"
"reflect"
"strings"
"testing"
)
func unsetEnvBrowser(t *testing.T) {
t.Helper()
err := os.Unsetenv("BROWSER")
if err != nil {
t.Fatal(err)
}
}
func TestBrowserCommand(t *testing.T) {
tests := []struct {
name string
envValue string
url string
wantCmd string
}{
{
"without URL directive",
"open -a Firefox",
"https://duckduckgo.com",
"open -a Firefox 'https://duckduckgo.com'",
},
{
"with URL directive at end",
"open -a Firefox %s",
"https://duckduckgo.com",
"open -a Firefox https://duckduckgo.com",
},
{
"with URL directive in middle",
"open -a Firefox %s --other-arg",
"https://duckduckgo.com",
"open -a Firefox https://duckduckgo.com --other-arg",
},
{
"escapes single quotes in URL",
"open -a Firefox",
"https://duckduckgo.com/?q='s-Hertogenbosch",
"open -a Firefox 'https://duckduckgo.com/?q=%27s-Hertogenbosch'",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
cmd := browserCommand(test.envValue, test.url)
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
}
wantArgs := []string{shell, "-c", test.wantCmd}
if !reflect.DeepEqual(cmd.Args, wantArgs) {
t.Errorf("got args '%#v' want '%#v'", cmd.Args, wantArgs)
}
})
}
}
func TestOpenURLStdout(t *testing.T) {
var stdout strings.Builder
Stdout = &stdout
err := os.Setenv("BROWSER", "printf")
if err != nil {
t.Fatal(err)
}
url := "http://localhost:8000"
OpenURL(url)
got := stdout.String()
if got != url {
t.Errorf("got stdout value %q want %q", got, url)
}
unsetEnvBrowser(t)
}
func TestOpenURLStderr(t *testing.T) {
var stderr strings.Builder
Stderr = &stderr
err := os.Setenv("BROWSER", "printf >&2")
if err != nil {
t.Fatal(err)
}
url := "http://localhost:8000"
OpenURL(url)
got := stderr.String()
if got != url {
t.Errorf("got stdout value %q want %q", got, url)
}
unsetEnvBrowser(t)
}
func TestOpenURLMultipleBrowserCommands(t *testing.T) {
// The `test -z URL` command must fail, causing `printf URL` to run.
err := os.Setenv("BROWSER", "test -z:printf")
if err != nil {
t.Fatal(err)
}
var stdout strings.Builder
Stdout = &stdout
url := "http://localhost:8000"
OpenURL(url)
got := stdout.String()
if got != url {
t.Errorf("got stdout value %q want %q", got, url)
}
unsetEnvBrowser(t)
}
|