| 1 |
package sprig |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"testing" |
| 7 |
"text/template" |
| 8 |
|
| 9 |
"github.com/stretchr/testify/assert" |
| 10 |
) |
| 11 |
|
| 12 |
func TestBase(t *testing.T) { |
| 13 |
assert.NoError(t, runt(`{{ base "foo/bar" }}`, "bar")) |
| 14 |
} |
| 15 |
|
| 16 |
func TestDir(t *testing.T) { |
| 17 |
assert.NoError(t, runt(`{{ dir "foo/bar/baz" }}`, "foo/bar")) |
| 18 |
} |
| 19 |
|
| 20 |
func TestIsAbs(t *testing.T) { |
| 21 |
assert.NoError(t, runt(`{{ isAbs "/foo" }}`, "true")) |
| 22 |
assert.NoError(t, runt(`{{ isAbs "foo" }}`, "false")) |
| 23 |
} |
| 24 |
|
| 25 |
func TestClean(t *testing.T) { |
| 26 |
assert.NoError(t, runt(`{{ clean "/foo/../foo/../bar" }}`, "/bar")) |
| 27 |
} |
| 28 |
|
| 29 |
func TestExt(t *testing.T) { |
| 30 |
assert.NoError(t, runt(`{{ ext "/foo/bar/baz.txt" }}`, ".txt")) |
| 31 |
} |
| 32 |
|
| 33 |
func TestRegex(t *testing.T) { |
| 34 |
assert.NoError(t, runt(`{{ regexQuoteMeta "1.2.3" }}`, "1\\.2\\.3")) |
| 35 |
assert.NoError(t, runt(`{{ regexQuoteMeta "pretzel" }}`, "pretzel")) |
| 36 |
} |
| 37 |
|
| 38 |
// runt runs a template and checks that the output exactly matches the expected string. |
| 39 |
func runt(tpl, expect string) error { |
| 40 |
return runtv(tpl, expect, map[string]string{}) |
| 41 |
} |
| 42 |
|
| 43 |
// runtv takes a template, and expected return, and values for substitution. |
| 44 |
// |
| 45 |
// It runs the template and verifies that the output is an exact match. |
| 46 |
func runtv(tpl, expect string, vars any) error { |
| 47 |
fmap := TxtFuncMap() |
| 48 |
t := template.Must(template.New("test").Funcs(fmap).Parse(tpl)) |
| 49 |
var b bytes.Buffer |
| 50 |
err := t.Execute(&b, vars) |
| 51 |
if err != nil { |
| 52 |
return err |
| 53 |
} |
| 54 |
if expect != b.String() { |
| 55 |
return fmt.Errorf("expected '%s', got '%s'", expect, b.String()) |
| 56 |
} |
| 57 |
return nil |
| 58 |
} |
| 59 |
|
| 60 |
// runRaw runs a template with the given variables and returns the result. |
| 61 |
func runRaw(tpl string, vars any) (string, error) { |
| 62 |
fmap := TxtFuncMap() |
| 63 |
t := template.Must(template.New("test").Funcs(fmap).Parse(tpl)) |
| 64 |
var b bytes.Buffer |
| 65 |
err := t.Execute(&b, vars) |
| 66 |
if err != nil { |
| 67 |
return "", err |
| 68 |
} |
| 69 |
return b.String(), nil |
| 70 |
} |