github.com/hairyhenderson/templater@v3.5.0+incompatible/tmpl/tmpl_test.go (about)

     1  package tmpl
     2  
     3  import (
     4  	"testing"
     5  	"text/template"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestInline(t *testing.T) {
    11  	testdata := []string{
    12  		"{{ print `hello world`}}",
    13  		"{{ tpl \"{{ print `hello world`}}\"}}",
    14  		"{{ tpl \"{{ tpl \\\"{{ print `hello world`}}\\\"}}\"}}",
    15  	}
    16  	tmpl := &Template{
    17  		defaultCtx: map[string]string{},
    18  		root:       template.New("root"),
    19  	}
    20  	tmpl.root.Funcs(template.FuncMap{
    21  		"tpl": tmpl.Inline,
    22  	})
    23  	for _, d := range testdata {
    24  		out, err := tmpl.Inline(d)
    25  		assert.NoError(t, err, d)
    26  		assert.Equal(t, "hello world", out)
    27  	}
    28  }
    29  
    30  func TestParseArgs(t *testing.T) {
    31  	defaultCtx := map[string]string{"hello": "world"}
    32  	tmpl := New(nil, defaultCtx)
    33  	name, in, ctx, err := tmpl.parseArgs("foo")
    34  	assert.NoError(t, err)
    35  	assert.Equal(t, "<inline>", name)
    36  	assert.Equal(t, "foo", in)
    37  	assert.Equal(t, defaultCtx, ctx)
    38  
    39  	_, _, _, err = tmpl.parseArgs(42)
    40  	assert.Error(t, err)
    41  
    42  	_, _, _, err = tmpl.parseArgs()
    43  	assert.Error(t, err)
    44  
    45  	_, _, _, err = tmpl.parseArgs("", "", 42, "")
    46  	assert.Error(t, err)
    47  
    48  	_, _, _, err = tmpl.parseArgs("", 42, 42)
    49  	assert.Error(t, err)
    50  
    51  	name, in, ctx, err = tmpl.parseArgs("foo", "bar")
    52  	assert.NoError(t, err)
    53  	assert.Equal(t, "foo", name)
    54  	assert.Equal(t, "bar", in)
    55  	assert.Equal(t, defaultCtx, ctx)
    56  
    57  	c := map[string]string{"one": "two"}
    58  	name, in, ctx, err = tmpl.parseArgs("foo", c)
    59  	assert.NoError(t, err)
    60  	assert.Equal(t, "<inline>", name)
    61  	assert.Equal(t, "foo", in)
    62  	assert.Equal(t, c, ctx)
    63  
    64  	name, in, ctx, err = tmpl.parseArgs("foo", "bar", c)
    65  	assert.NoError(t, err)
    66  	assert.Equal(t, "foo", name)
    67  	assert.Equal(t, "bar", in)
    68  	assert.Equal(t, c, ctx)
    69  }
    70  
    71  func TestExec(t *testing.T) {
    72  	root := template.New("root")
    73  	t1 := root.New("T1")
    74  	t1.Parse("hello, {{ . }}")
    75  	tmpl := &Template{
    76  		defaultCtx: map[string]string{"foo": "bar"},
    77  		root:       root,
    78  	}
    79  
    80  	out, err := tmpl.Exec("T1")
    81  	assert.NoError(t, err)
    82  	assert.Equal(t, "hello, map[foo:bar]", out)
    83  
    84  	out, err = tmpl.Exec("T1", "world")
    85  	assert.NoError(t, err)
    86  	assert.Equal(t, "hello, world", out)
    87  
    88  	_, err = tmpl.Exec("bogus")
    89  	assert.Error(t, err)
    90  }