forked from juju/testing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
195 lines (174 loc) · 5.72 KB
/
cmd.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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2013, 2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package testing
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
gc "gopkg.in/check.v1"
)
var HookChannelSize = 10
// HookCommandOutput intercepts CommandOutput to a function that passes the
// actual command and it's output back via a channel, and returns the error
// passed into this function. It also returns a cleanup function so you can
// restore the original function
func HookCommandOutput(
outputFunc *func(cmd *exec.Cmd) ([]byte, error), output []byte, err error) (<-chan *exec.Cmd, func()) {
cmdChan := make(chan *exec.Cmd, HookChannelSize)
origCommandOutput := *outputFunc
cleanup := func() {
close(cmdChan)
*outputFunc = origCommandOutput
}
*outputFunc = func(cmd *exec.Cmd) ([]byte, error) {
cmdChan <- cmd
return output, err
}
return cmdChan, cleanup
}
const (
// EchoQuotedArgs is a simple bash script that prints out the
// basename of the command followed by the args as quoted strings.
// If a ; separated list of exit codes is provided in $name.exitcodes
// then it will return them in turn over multiple calls. If
// $name.exitcodes does not exist, or the list runs out, return 0.
EchoQuotedArgsUnix = `#!/bin/bash --norc
name=` + "`basename $0`" + `
argfile="$name.out"
exitcodesfile="$name.exitcodes"
printf "%s" $name | tee -a $argfile
for arg in "$@"; do
printf " \"%s\"" "$arg" | tee -a $argfile
done
printf "\n" | tee -a $argfile
if [ -f $exitcodesfile ]
then
exitcodes=$(cat $exitcodesfile)
arr=(${exitcodes/;/ })
echo ${arr[1]} | tee $exitcodesfile
exit ${arr[0]}
fi
`
EchoQuotedArgsWindows = `@echo off
setlocal enabledelayedexpansion
set list=%0
set argCount=0
for %%x in (%*) do (
set /A argCount+=1
set "argVec[!argCount!]=%%~x"
)
for /L %%i in (1,1,%argCount%) do set list=!list! "!argVec[%%i]!"
IF exist %0.exitcodes (
FOR /F "tokens=1* delims=;" %%i IN (%0.exitcodes) DO (
set exitcode=%%i
IF NOT [%%j]==[] (
echo %%j > %0.exitcodes
) ELSE (
del %0.exitcodes
)
)
)
echo %list%>> %0.out
exit /B %exitcode%
`
)
// EnvironmentPatcher is an interface that requires just one method:
// PatchEnvironment.
type EnvironmentPatcher interface {
PatchEnvironment(name, value string)
}
// PatchExecutable creates an executable called 'execName' in a new test
// directory and that directory is added to the path.
func PatchExecutable(c *gc.C, patcher CleanupPatcher, execName, script string, exitCodes ...int) {
dir := c.MkDir()
patcher.PatchEnvironment("PATH", joinPathLists(dir, os.Getenv("PATH")))
var filename string
switch runtime.GOOS {
case "windows":
filename = filepath.Join(dir, execName+".bat")
default:
filename = filepath.Join(dir, execName)
}
os.Remove(filename + ".out")
err := ioutil.WriteFile(filename, []byte(script), 0755)
c.Assert(err, gc.IsNil)
if len(exitCodes) > 0 {
filename = execName + ".exitcodes"
codes := make([]string, len(exitCodes))
for i, code := range exitCodes {
codes[i] = strconv.Itoa(code)
}
s := strings.Join(codes, ";") + ";"
err = ioutil.WriteFile(filename, []byte(s), 0644)
c.Assert(err, gc.IsNil)
patcher.AddCleanup(func(*gc.C) {
os.Remove(filename)
})
}
}
type CleanupPatcher interface {
PatchEnvironment(name, value string)
AddCleanup(cleanup CleanupFunc)
}
// PatchExecutableThrowError is needed to test cases in which we expect exit
// codes from executables called from the system path
func PatchExecutableThrowError(c *gc.C, patcher CleanupPatcher, execName string, exitCode int) {
switch runtime.GOOS {
case "windows":
script := fmt.Sprintf(`@echo off
setlocal enabledelayedexpansion
echo failing
exit /b %d
REM see %ERRORLEVEL% for last exit code like $? on linux
`, exitCode)
PatchExecutable(c, patcher, execName, script)
default:
script := fmt.Sprintf(`#!/bin/bash --norc
echo failing
exit %d
`, exitCode)
PatchExecutable(c, patcher, execName, script)
}
patcher.AddCleanup(func(*gc.C) {
os.Remove(execName + ".out")
})
}
// PatchExecutableAsEchoArgs creates an executable called 'execName' in a new
// test directory and that directory is added to the path. The content of the
// script is 'EchoQuotedArgs', and the args file is removed using a cleanup
// function.
func PatchExecutableAsEchoArgs(c *gc.C, patcher CleanupPatcher, execName string, exitCodes ...int) {
switch runtime.GOOS {
case "windows":
PatchExecutable(c, patcher, execName, EchoQuotedArgsWindows, exitCodes...)
default:
PatchExecutable(c, patcher, execName, EchoQuotedArgsUnix, exitCodes...)
}
patcher.AddCleanup(func(*gc.C) {
os.Remove(execName + ".out")
os.Remove(execName + ".exitcodes")
})
}
// AssertEchoArgs is used to check the args from an execution of a command
// that has been patchec using PatchExecutable containing EchoQuotedArgs.
func AssertEchoArgs(c *gc.C, execName string, args ...string) {
// Read in entire argument log file
content, err := ioutil.ReadFile(execName + ".out")
c.Assert(err, gc.IsNil)
lines := strings.Split(string(content), "\n")
// Create expected output string
expected := execName
for _, arg := range args {
expected = fmt.Sprintf("%s %q", expected, arg)
}
// Check that the expected and the first line of actual output are the same
c.Assert(lines[0], gc.Equals, expected)
// Write out the remaining lines for the next check
content = []byte(strings.Join(lines[1:], "\n"))
err = ioutil.WriteFile(execName+".out", content, 0644) // or just call this filename somewhere, once.
}