...

Source file src/github.com/go-task/slim-sprig/v3/functions_test.go

Documentation: github.com/go-task/slim-sprig/v3

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

View as plain text