go / expert
Snippet
Hermetic Executable Helper Testing via Environment Flag Subprocess Forking
Testing OS subprocess command execution without mocking external system binaries is accomplished by re-executing the compiled test executable binary itself (`os.Args[0]`) guarded by an environment variable flag.
snippet.go
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
package mainimport ("os""os/exec""testing")func HelperProcess(t *testing.T) {if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {return}os.Stdout.WriteString("simulated subprocess output")os.Exit(0)}func TestSubprocessExecution(t *testing.T) {cmd := exec.Command(os.Args[0], "-test.run=HelperProcess")cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")out, err := cmd.Output()if err != nil || string(out) != "simulated subprocess output" {t.Fatalf("Subprocess testing failed, output: %s", string(out))}}
Breakdown
1
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
Guards the target test process from running helper logic during standard test runs.
2
cmd := exec.Command(os.Args[0], "-test.run=HelperProcess")
Forks the current compiled test binary to execute a sub-routine in an isolated OS process environment.
3
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
Injects process environment flags to activate sub-routine behavior inside the re-invoked binary.