summaryrefslogtreecommitdiff
path: root/internal/cmd/main_test.go
blob: 7f8bd6f75190efb0fe2e690f4b1c9d0e8f89fb51 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package cmd

import (
	"bytes"
	"context"
	"strings"
	"testing"

	"github.com/hairyhenderson/gomplate/v3/internal/config"
	"github.com/spf13/cobra"
	"github.com/stretchr/testify/assert"
)

func TestOptionalExecArgs(t *testing.T) {
	cmd := &cobra.Command{}
	cmd.SetArgs(nil)
	cmd.ParseFlags(nil)

	err := optionalExecArgs(cmd, nil)
	assert.NoError(t, err)

	cmd = &cobra.Command{}
	cmd.SetArgs(nil)
	cmd.ParseFlags(nil)

	err = optionalExecArgs(cmd, []string{"bogus"})
	assert.Error(t, err)

	cmd = &cobra.Command{}
	cmd.SetArgs(nil)
	cmd.ParseFlags([]string{"--", "foo"})

	err = optionalExecArgs(cmd, []string{})
	assert.NoError(t, err)

	cmd = &cobra.Command{}
	cmd.SetArgs(nil)
	cmd.ParseFlags([]string{"--"})

	err = optionalExecArgs(cmd, []string{"foo"})
	assert.NoError(t, err)
}

func TestRunMain(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	err := Main(ctx, []string{"-h"}, nil, nil, nil)
	assert.NoError(t, err)

	err = Main(ctx, []string{"--bogus"}, nil, nil, nil)
	assert.Error(t, err)

	stdin := &bytes.Buffer{}
	stdout := &bytes.Buffer{}
	stderr := &bytes.Buffer{}
	err = Main(ctx, []string{"-i", "hello"}, stdin, stdout, stderr)
	assert.NoError(t, err)
	assert.Equal(t, "hello", stdout.String())
}

func TestPostRunExec(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cfg := &config.Config{
		PostExecInput: strings.NewReader("hello world"),
		PostExec:      []string{"cat"},
	}
	out := &bytes.Buffer{}
	err := postRunExec(ctx, cfg, out, out)
	assert.NoError(t, err)
	assert.Equal(t, "hello world", out.String())
}