Parent directory

hook_test.go

1668 bytes
 1package hook
 2
 3import (
 4	"context"
 5	"errors"
 6	"io"
 7	"os"
 8	"os/exec"
 9	"path/filepath"
10	"testing"
11)
12
13func TestRunCustomHookPropagatesExitError(t *testing.T) {
14	executable, err := os.Executable()
15	if err != nil {
16		t.Fatal(err)
17	}
18	info, err := os.Stat(executable)
19	if err != nil {
20		t.Fatal(err)
21	}
22	if info.Mode()&0o111 == 0 {
23		t.Skip("test binary is not executable on this platform")
24	}
25
26	t.Setenv("SOFT_SERVE_TEST_HELPER", "1")
27	t.Setenv("SOFT_SERVE_TEST_HELPER_EXIT", "1")
28	err = runCustomHook(
29		context.Background(),
30		executable,
31		io.Reader(nil),
32		io.Discard,
33		io.Discard,
34		"-test.run=TestCustomHookHelperProcess",
35	)
36	if err == nil {
37		t.Fatal("runCustomHook returned nil for a failing custom hook")
38	}
39
40	var exitErr *exec.ExitError
41	if !errors.As(err, &exitErr) {
42		t.Fatalf("runCustomHook error = %T %v, want exec.ExitError", err, err)
43	}
44}
45
46func TestRunCustomHookIgnoresMissingOrNonExecutableHook(t *testing.T) {
47	missing := filepath.Join(t.TempDir(), "missing-hook")
48	if err := runCustomHook(context.Background(), missing, nil, io.Discard, io.Discard); err != nil {
49		t.Fatalf("runCustomHook(missing) error = %v", err)
50	}
51
52	nonExecutable := filepath.Join(t.TempDir(), "non-executable-hook")
53	if err := os.WriteFile(nonExecutable, []byte("exit 1\n"), 0o600); err != nil {
54		t.Fatal(err)
55	}
56	if err := runCustomHook(context.Background(), nonExecutable, nil, io.Discard, io.Discard); err != nil {
57		t.Fatalf("runCustomHook(non-executable) error = %v", err)
58	}
59}
60
61func TestCustomHookHelperProcess(t *testing.T) {
62	if os.Getenv("SOFT_SERVE_TEST_HELPER") != "1" {
63		return
64	}
65	if os.Getenv("SOFT_SERVE_TEST_HELPER_EXIT") == "1" {
66		os.Exit(1)
67	}
68	os.Exit(0)
69}