github.com/hairyhenderson/gomplate/v3@v3.11.7/plugins_test.go (about) 1 package gomplate 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "os" 8 "strings" 9 "testing" 10 "text/template" 11 "time" 12 13 "github.com/hairyhenderson/gomplate/v3/internal/config" 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func TestBindPlugins(t *testing.T) { 18 ctx := context.Background() 19 fm := template.FuncMap{} 20 cfg := &config.Config{ 21 Plugins: map[string]config.PluginConfig{}, 22 } 23 err := bindPlugins(ctx, cfg, fm) 24 assert.NoError(t, err) 25 assert.EqualValues(t, template.FuncMap{}, fm) 26 27 cfg.Plugins = map[string]config.PluginConfig{"foo": {Cmd: "bar"}} 28 err = bindPlugins(ctx, cfg, fm) 29 assert.NoError(t, err) 30 assert.Contains(t, fm, "foo") 31 32 err = bindPlugins(ctx, cfg, fm) 33 assert.ErrorContains(t, err, "already bound") 34 } 35 36 func TestBuildCommand(t *testing.T) { 37 ctx := context.Background() 38 data := []struct { 39 name, path string 40 args []string 41 expected []string 42 }{ 43 {"foo", "foo", nil, []string{"foo"}}, 44 {"foo", "foo", []string{"bar"}, []string{"foo", "bar"}}, 45 {"foo", "foo.bat", nil, []string{"cmd.exe", "/c", "foo.bat"}}, 46 {"foo", "foo.cmd", []string{"bar"}, []string{"cmd.exe", "/c", "foo.cmd", "bar"}}, 47 {"foo", "foo.ps1", []string{"bar", "baz"}, []string{"pwsh", "-File", "foo.ps1", "bar", "baz"}}, 48 } 49 for _, d := range data { 50 p := &plugin{ 51 ctx: ctx, 52 path: d.path, 53 } 54 name, args := p.buildCommand(d.args) 55 actual := append([]string{name}, args...) 56 assert.EqualValues(t, d.expected, actual) 57 } 58 } 59 60 func TestRun(t *testing.T) { 61 ctx, cancel := context.WithCancel(context.Background()) 62 defer cancel() 63 64 stderr := &bytes.Buffer{} 65 p := &plugin{ 66 ctx: ctx, 67 timeout: 500 * time.Millisecond, 68 stderr: stderr, 69 path: "echo", 70 } 71 out, err := p.run("foo") 72 assert.NoError(t, err) 73 assert.Equal(t, "", stderr.String()) 74 assert.Equal(t, "foo", strings.TrimSpace(out.(string))) 75 } 76 77 func ExamplePluginFunc() { 78 ctx := context.Background() 79 80 // PluginFunc creates a template function that runs an arbitrary command. 81 f := PluginFunc(ctx, "echo", PluginOpts{}) 82 83 // The function can be used in a template, but here we'll just run it 84 // directly. This is equivalent to running 'echo foo bar' 85 out, err := f("foo", "bar") 86 if err != nil { 87 panic(err) 88 } 89 fmt.Println(out) 90 91 // Output: 92 // foo bar 93 } 94 95 func ExamplePluginFunc_with_template() { 96 ctx := context.Background() 97 98 f := PluginFunc(ctx, "echo", PluginOpts{}) 99 100 // PluginFunc is intended for use with gomplate, but can be used in any 101 // text/template by adding it to the FuncMap. 102 tmpl := template.New("new").Funcs(template.FuncMap{"echo": f}) 103 104 tmpl, err := tmpl.Parse(`{{ echo "baz" "qux" }}`) 105 if err != nil { 106 panic(err) 107 } 108 109 err = tmpl.Execute(os.Stdout, nil) 110 if err != nil { 111 panic(err) 112 } 113 114 // Output: 115 // baz qux 116 }