| 1 | package host |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "strings" |
| 8 | "syscall" |
| 9 | "testing" |
| 10 | |
| 11 | "golang.org/x/sys/windows" |
| 12 | ) |
| 13 | |
| 14 | func TestHideCommandWindowPreservesProcessAttributes(t *testing.T) { |
| 15 | attributes := &syscall.SysProcAttr{CreationFlags: windows.CREATE_NEW_PROCESS_GROUP} |
| 16 | cmd := &exec.Cmd{SysProcAttr: attributes} |
| 17 | HideCommandWindow(cmd) |
| 18 | if cmd.SysProcAttr != attributes || !attributes.HideWindow || attributes.CreationFlags != windows.CREATE_NEW_PROCESS_GROUP|windows.CREATE_NO_WINDOW { |
| 19 | t.Fatalf("background command attributes changed: %+v", cmd.SysProcAttr) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | func TestHiddenCommandHasNoConsoleAndCapturesOutput(t *testing.T) { |
| 24 | executable, err := os.Executable() |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | cmd := exec.Command(executable, "-test.run=^TestHiddenCommandChild$") |
| 29 | cmd.Env = append(os.Environ(), "CAGE_HIDDEN_COMMAND_TEST=1") |
| 30 | HideCommandWindow(cmd) |
| 31 | output, err := cmd.CombinedOutput() |
| 32 | if err != nil || !strings.Contains(string(output), "console=0") || !strings.Contains(string(output), "stderr-captured") { |
| 33 | t.Fatalf("hidden child: %s, %v", output, err) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func TestHiddenCommandChild(t *testing.T) { |
| 38 | if os.Getenv("CAGE_HIDDEN_COMMAND_TEST") != "1" { |
| 39 | return |
| 40 | } |
| 41 | window, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("GetConsoleWindow").Call() |
| 42 | fmt.Printf("console=%d\n", window) |
| 43 | fmt.Fprintln(os.Stderr, "stderr-captured") |
| 44 | } |