|
| 1 | +// Copyright 2024 - 2025 Crunchy Data Solutions, Inc. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +package shell |
| 6 | + |
| 7 | +import ( |
| 8 | + "os" |
| 9 | + "os/exec" |
| 10 | + "path/filepath" |
| 11 | + "strings" |
| 12 | + "testing" |
| 13 | + |
| 14 | + "gotest.tools/v3/assert" |
| 15 | + "sigs.k8s.io/yaml" |
| 16 | + |
| 17 | + "github.com/crunchydata/postgres-operator/internal/testing/require" |
| 18 | +) |
| 19 | + |
| 20 | +func TestMakeDirectories(t *testing.T) { |
| 21 | + t.Parallel() |
| 22 | + |
| 23 | + t.Run("NoPaths", func(t *testing.T) { |
| 24 | + assert.Equal(t, |
| 25 | + MakeDirectories(0o755, "/asdf/jklm"), |
| 26 | + `test -d '/asdf/jklm'`) |
| 27 | + }) |
| 28 | + |
| 29 | + t.Run("Children", func(t *testing.T) { |
| 30 | + assert.DeepEqual(t, |
| 31 | + MakeDirectories(0o775, "/asdf", "/asdf/jklm", "/asdf/qwerty"), |
| 32 | + `mkdir -p '/asdf/jklm' '/asdf/qwerty' && chmod 0775 '/asdf/jklm' '/asdf/qwerty'`) |
| 33 | + }) |
| 34 | + |
| 35 | + t.Run("Grandchild", func(t *testing.T) { |
| 36 | + script := MakeDirectories(0o775, "/asdf", "/asdf/qwerty/boots") |
| 37 | + assert.DeepEqual(t, script, |
| 38 | + `mkdir -p '/asdf/qwerty/boots' && chmod 0775 '/asdf/qwerty/boots' '/asdf/qwerty'`) |
| 39 | + |
| 40 | + t.Run("ShellCheckPOSIX", func(t *testing.T) { |
| 41 | + shellcheck := require.ShellCheck(t) |
| 42 | + |
| 43 | + dir := t.TempDir() |
| 44 | + file := filepath.Join(dir, "script.sh") |
| 45 | + assert.NilError(t, os.WriteFile(file, []byte(script), 0o600)) |
| 46 | + |
| 47 | + // Expect ShellCheck for "sh" to be happy. |
| 48 | + // - https://www.shellcheck.net/wiki/SC2148 |
| 49 | + cmd := exec.Command(shellcheck, "--enable=all", "--shell=sh", file) |
| 50 | + output, err := cmd.CombinedOutput() |
| 51 | + assert.NilError(t, err, "%q\n%s", cmd.Args, output) |
| 52 | + }) |
| 53 | + }) |
| 54 | + |
| 55 | + t.Run("Long", func(t *testing.T) { |
| 56 | + script := MakeDirectories(0o700, "/", strings.Repeat("/asdf", 20)) |
| 57 | + |
| 58 | + t.Run("PrettyYAML", func(t *testing.T) { |
| 59 | + b, err := yaml.Marshal(script) |
| 60 | + s := string(b) |
| 61 | + assert.NilError(t, err) |
| 62 | + assert.Assert(t, !strings.HasPrefix(s, `"`) && !strings.HasPrefix(s, `'`), |
| 63 | + "expected plain unquoted scalar, got:\n%s", b) |
| 64 | + }) |
| 65 | + }) |
| 66 | +} |
0 commit comments