Reputation:
This code is executing commands for binary and return std.out
and std.error
func exe(bin string, args string, path string) (string, error string) {
cmd := exec.Command(bin, strings.Split(args, " ")...)
cmd.Dir = path
stdoutBuf := &bytes.Buffer{}
cmd.Stdout = stdoutBuf
stdErrBuf := &bytes.Buffer{}
cmd.Stderr = stdErrBuf
cmd.Run()
return stdoutBuf.String(), stdErrBuf.String()
}
The problem that I don't know how to run a good test for it which will be supported in each system e.g. if I try to run "echo" command the test run on Darwin and Linux but not on windows. how I should do it?
func Test_execute(t *testing.T) {
type args struct {
bin string
args string
path string
}
tests := []struct {
name string
args args
wantString string
wantError string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotString, gotError := exe(tt.args.bin, tt.args.args, tt.args.path)
if gotString != tt.wantString {
t.Errorf("exe() gotString = %v, want %v", gotString, tt.wantString)
}
if gotError != tt.wantError {
t.Errorf("exe() gotError = %v, want %v", gotError, tt.wantError)
}
})
}
}
I've searched on it and found this, https://www.joeshaw.org/testing-with-os-exec-and-testmain/ But now sure how to combine the env with my test...
Upvotes: 1
Views: 64
Reputation: 166569
Use Go build tags or file names. For example, for Linux and Windows:
a_linux_test.go
(Linux file name):
package main
import "testing"
func TestLinuxA(t *testing.T) {
t.Log("Linux A")
}
l_test.go
(Linux build tag):
// +build linux
package main
import "testing"
func TestLinuxL(t *testing.T) {
t.Log("Linux L")
}
a_windows_test.go
(Windows file name):
package main
import "testing"
func TestWindowsA(t *testing.T) {
t.Log("Windows A")
}
w_test.go
(Windows build tag):
// +build windows
package main
import "testing"
func TestWindowsW(t *testing.T) {
t.Log("Windows W")
}
Output (on Linux):
$ go test -v
=== RUN TestLinuxA
--- PASS: TestLinuxA (0.00s)
a_linux_test.go:6: Linux A
=== RUN TestLinuxL
--- PASS: TestLinuxL (0.00s)
l_test.go:8: Linux L
PASS
$
Output (on Windows):
>go test -v
=== RUN TestWindowsA
--- PASS: TestWindowsA (0.00s)
a_windows_test.go:6: Windows A
=== RUN TestWindowsW
--- PASS: TestWindowsW (0.00s)
w_test.go:8: Windows W
PASS
>
References:
Upvotes: 2