| 1 | package shellrun |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "os/exec" |
| 7 | "runtime" |
| 8 | "testing" |
| 9 | |
| 10 | "reasonix/internal/proc" |
| 11 | "reasonix/internal/tool" |
| 12 | ) |
| 13 | |
| 14 | func TestRunForegroundExecutesRequestedCommandOnce(t *testing.T) { |
| 15 | calls := 0 |
| 16 | res := RunForeground(context.Background(), Request{ |
| 17 | Argv: []string{"real-command", "arg"}, |
| 18 | Run: func(_ context.Context, cmd *exec.Cmd, _ proc.RunOptions) (*proc.TrackedCommand, error) { |
| 19 | calls++ |
| 20 | if got := cmd.Args; len(got) != 2 || got[0] != "real-command" || got[1] != "arg" { |
| 21 | t.Fatalf("command = %v", got) |
| 22 | } |
| 23 | fmt.Fprint(cmd.Stdout, "ok") |
| 24 | return nil, nil |
| 25 | }, |
| 26 | }) |
| 27 | if calls != 1 || res.State != tool.ShellStateCompleted || res.Combined != "ok" { |
| 28 | t.Fatalf("calls=%d result=%+v", calls, res) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func TestOrdinaryExit126RemainsExecutionFailure(t *testing.T) { |
| 33 | res := RunForeground(context.Background(), Request{ |
| 34 | Argv: []string{"pwsh"}, |
| 35 | Run: func(_ context.Context, cmd *exec.Cmd, _ proc.RunOptions) (*proc.TrackedCommand, error) { |
| 36 | var child *exec.Cmd |
| 37 | if runtime.GOOS == "windows" { |
| 38 | child = exec.Command("cmd", "/c", "exit", "126") |
| 39 | } else { |
| 40 | child = exec.Command("sh", "-c", "exit 126") |
| 41 | } |
| 42 | err := child.Run() |
| 43 | cmd.Process = child.Process |
| 44 | cmd.ProcessState = child.ProcessState |
| 45 | return nil, err |
| 46 | }, |
| 47 | }) |
| 48 | if !res.Started || res.FailurePhase != tool.ShellPhaseExecution || res.ExitCode == nil || *res.ExitCode != 126 { |
| 49 | t.Fatalf("ordinary exit 126 misclassified: %+v", res) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func TestWindowsRuntimeDiagnosticsRequireEvidence(t *testing.T) { |
| 54 | for _, text := range []string{"exit status 256", "access denied", "CreateFileMapping failed", "Win32 error 5"} { |
| 55 | if WindowsRuntimeDiagnostic(text) != "" { |
| 56 | t.Fatalf("misclassified %q", text) |
| 57 | } |
| 58 | } |
| 59 | for _, text := range []string{ |
| 60 | "*** fatal error - CreateFileMapping S-1-5-21-1.1, Win32 error 5. Terminating.", |
| 61 | "cygheap_user::init: NtSetInformationToken (TokenDefaultDacl), 0xC0000022", |
| 62 | } { |
| 63 | if WindowsRuntimeDiagnostic(text) == "" { |
| 64 | t.Fatalf("missing diagnostic for %q", text) |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 |