@@ -34,6 +34,7 @@ type run struct {
34
34
command string
35
35
input []byte
36
36
output []byte
37
+ env []string
37
38
err error
38
39
}
39
40
@@ -117,6 +118,14 @@ func (c *FakeCmd) WithRunOutErr(command string, output string, err error) *FakeC
117
118
})
118
119
}
119
120
121
+ // WithRunEnv registers a command that requires the given env variables to be set.
122
+ func (c * FakeCmd ) WithRunEnv (command string , env []string ) * FakeCmd {
123
+ return c .addRun (run {
124
+ command : command ,
125
+ env : env ,
126
+ })
127
+ }
128
+
120
129
func (c * FakeCmd ) RunCmdOut (cmd * exec.Cmd ) ([]byte , error ) {
121
130
command := strings .Join (cmd .Args , " " )
122
131
@@ -129,6 +138,8 @@ func (c *FakeCmd) RunCmdOut(cmd *exec.Cmd) ([]byte, error) {
129
138
c .t .Errorf ("expected: %s. Got: %s" , r .command , command )
130
139
}
131
140
141
+ c .assertCmdEnv (r .env , cmd .Env )
142
+
132
143
if r .output == nil {
133
144
c .t .Errorf ("expected RunCmd(%s) to be called. Got RunCmdOut(%s)" , r .command , command )
134
145
}
@@ -152,6 +163,8 @@ func (c *FakeCmd) RunCmd(cmd *exec.Cmd) error {
152
163
c .t .Errorf ("expected RunCmdOut(%s) to be called. Got RunCmd(%s)" , r .command , command )
153
164
}
154
165
166
+ c .assertCmdEnv (r .env , cmd .Env )
167
+
155
168
if r .input != nil {
156
169
if cmd .Stdin == nil {
157
170
c .t .Error ("expected to run the command with a custom stdin" , command )
@@ -171,3 +184,22 @@ func (c *FakeCmd) RunCmd(cmd *exec.Cmd) error {
171
184
172
185
return r .err
173
186
}
187
+
188
+ // assertCmdEnv ensures that actualEnv contains all values from requiredEnv
189
+ func (c * FakeCmd ) assertCmdEnv (requiredEnv , actualEnv []string ) {
190
+ if requiredEnv == nil {
191
+ return
192
+ }
193
+ c .t .Helper ()
194
+
195
+ envs := make (map [string ]struct {}, len (actualEnv ))
196
+ for _ , e := range actualEnv {
197
+ envs [e ] = struct {}{}
198
+ }
199
+
200
+ for _ , e := range requiredEnv {
201
+ if _ , ok := envs [e ]; ! ok {
202
+ c .t .Errorf ("expected env variable with value %q" , e )
203
+ }
204
+ }
205
+ }
0 commit comments