package main import ( "bufio" "context" "fmt" "os" "os/exec" "syscall" "testing" "time" "go.maximumdirect.net/commandkit" ) func TestProcessSignalsCancelInvocation(t *testing.T) { if os.Getenv("NARRATIO_TEST_SIGNAL_CHILD") == "1" { os.Exit(runProcess(nil, commandkit.Streams{Out: os.Stdout, Err: os.Stderr}, func(ctx context.Context, _ []string, streams commandkit.Streams) commandkit.Outcome { fmt.Fprintln(streams.Out, "ready") <-ctx.Done() return commandkit.Failure("interrupted").WithCause(ctx.Err()) })) } for _, sig := range []os.Signal{os.Interrupt, syscall.SIGTERM} { t.Run(sig.String(), func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() child := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestProcessSignalsCancelInvocation$") child.Env = append(os.Environ(), "NARRATIO_TEST_SIGNAL_CHILD=1") out, err := child.StdoutPipe() if err != nil { t.Fatal(err) } child.Stderr = os.Stderr if err := child.Start(); err != nil { t.Fatal(err) } scanner := bufio.NewScanner(out) if !scanner.Scan() || scanner.Text() != "ready" { _ = child.Process.Kill() _ = child.Wait() t.Fatal("child failed to register its signal context") } if err := child.Process.Signal(sig); err != nil { _ = child.Process.Kill() _ = child.Wait() t.Fatal(err) } err = child.Wait() exit, ok := err.(*exec.ExitError) if !ok || exit.ExitCode() != 1 { t.Fatalf("child result=%v, want operational exit 1", err) } }) } }