github.com/kunnos/engine@v1.13.1/cli/compose/template/template_test.go (about)

     1  package template
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  )
     8  
     9  var defaults = map[string]string{
    10  	"FOO": "first",
    11  	"BAR": "",
    12  }
    13  
    14  func defaultMapping(name string) (string, bool) {
    15  	val, ok := defaults[name]
    16  	return val, ok
    17  }
    18  
    19  func TestEscaped(t *testing.T) {
    20  	result, err := Substitute("$${foo}", defaultMapping)
    21  	assert.NoError(t, err)
    22  	assert.Equal(t, "${foo}", result)
    23  }
    24  
    25  func TestInvalid(t *testing.T) {
    26  	invalidTemplates := []string{
    27  		"${",
    28  		"$}",
    29  		"${}",
    30  		"${ }",
    31  		"${ foo}",
    32  		"${foo }",
    33  		"${foo!}",
    34  	}
    35  
    36  	for _, template := range invalidTemplates {
    37  		_, err := Substitute(template, defaultMapping)
    38  		assert.Error(t, err)
    39  		assert.IsType(t, &InvalidTemplateError{}, err)
    40  	}
    41  }
    42  
    43  func TestNoValueNoDefault(t *testing.T) {
    44  	for _, template := range []string{"This ${missing} var", "This ${BAR} var"} {
    45  		result, err := Substitute(template, defaultMapping)
    46  		assert.NoError(t, err)
    47  		assert.Equal(t, "This  var", result)
    48  	}
    49  }
    50  
    51  func TestValueNoDefault(t *testing.T) {
    52  	for _, template := range []string{"This $FOO var", "This ${FOO} var"} {
    53  		result, err := Substitute(template, defaultMapping)
    54  		assert.NoError(t, err)
    55  		assert.Equal(t, "This first var", result)
    56  	}
    57  }
    58  
    59  func TestNoValueWithDefault(t *testing.T) {
    60  	for _, template := range []string{"ok ${missing:-def}", "ok ${missing-def}"} {
    61  		result, err := Substitute(template, defaultMapping)
    62  		assert.NoError(t, err)
    63  		assert.Equal(t, "ok def", result)
    64  	}
    65  }
    66  
    67  func TestEmptyValueWithSoftDefault(t *testing.T) {
    68  	result, err := Substitute("ok ${BAR:-def}", defaultMapping)
    69  	assert.NoError(t, err)
    70  	assert.Equal(t, "ok def", result)
    71  }
    72  
    73  func TestEmptyValueWithHardDefault(t *testing.T) {
    74  	result, err := Substitute("ok ${BAR-def}", defaultMapping)
    75  	assert.NoError(t, err)
    76  	assert.Equal(t, "ok ", result)
    77  }
    78  
    79  func TestNonAlphanumericDefault(t *testing.T) {
    80  	result, err := Substitute("ok ${BAR:-/non:-alphanumeric}", defaultMapping)
    81  	assert.NoError(t, err)
    82  	assert.Equal(t, "ok /non:-alphanumeric", result)
    83  }