functions_test.go 1.8 KB

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