github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/utils/command_test.go (about) 1 /* 2 Copyright 2018 Mirantis 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 17 package utils 18 19 import ( 20 "strings" 21 "testing" 22 ) 23 24 func TestCommand(t *testing.T) { 25 for _, tc := range []struct { 26 cmd []string 27 stdin []byte 28 expectedOutput string 29 expectedError string 30 }{ 31 { 32 cmd: []string{"echo", "-n", "foobar"}, 33 stdin: nil, 34 expectedOutput: "foobar", 35 }, 36 { 37 cmd: []string{"/bin/bash", "-c", "echo -n >&2 'stderr here'; echo -n 'stdout here'; exit 1"}, 38 stdin: nil, 39 expectedOutput: "stdout here", 40 expectedError: "stderr here", 41 }, 42 { 43 cmd: []string{"sed", "s/foo/bar/g"}, 44 stdin: []byte("here is foo; foo."), 45 expectedOutput: "here is bar; bar.", 46 }, 47 } { 48 t.Run(strings.Join(tc.cmd, " "), func(t *testing.T) { 49 c := DefaultCommander.Command(tc.cmd[0], tc.cmd[1:]...) 50 switch out, err := c.Run(tc.stdin); { 51 case tc.expectedError == "" && err != nil: 52 t.Errorf("Command error: %v", err) 53 case tc.expectedError != "" && err == nil: 54 t.Errorf("Didn't get the expected error") 55 case tc.expectedError != "" && !strings.Contains(err.Error(), tc.expectedError): 56 t.Errorf("Bad error message %q (no substring %q)", err.Error(), tc.expectedError) 57 case tc.expectedError != "" && !strings.Contains(err.Error(), tc.cmd[0]): 58 t.Errorf("Bad error message %q (no substring %q)", err.Error(), tc.cmd[0]) 59 case string(out) != tc.expectedOutput: 60 t.Errorf("Command output mismatch: %q instead of %q", out, tc.expectedOutput) 61 } 62 }) 63 } 64 }