1package commands_test
 2
 3import (
 4	"bytes"
 5	"context"
 6	"flag"
 7	"io/ioutil"
 8	"os"
 9	"path/filepath"
10	"strings"
11	"testing"
12
13	"github.com/MichaelMure/git-bug/commands"
14	"github.com/MichaelMure/git-bug/repository"
15	"github.com/spf13/cobra"
16	"github.com/stretchr/testify/require"
17)
18
19var update = flag.Bool("update", false, "pass -update to the test runner to update golden files")
20
21type testEnv struct {
22	cwd  string
23	repo *repository.GoGitRepo
24	cmd  *cobra.Command
25	out  *bytes.Buffer
26}
27
28func newTestEnv(t *testing.T) *testEnv {
29	t.Helper()
30
31	cwd, err := ioutil.TempDir("", "")
32	require.NoError(t, err)
33	t.Cleanup(func() {
34		require.NoError(t, os.RemoveAll(cwd))
35	})
36
37	repo, err := repository.InitGoGitRepo(cwd, commands.GitBugNamespace)
38	require.NoError(t, err)
39	t.Cleanup(func() {
40		require.NoError(t, repo.Close())
41	})
42
43	out := new(bytes.Buffer)
44	cmd := commands.NewRootCommand()
45	cmd.SetArgs([]string{})
46	cmd.SetErr(out)
47	cmd.SetOut(out)
48
49	return &testEnv{
50		cwd:  cwd,
51		repo: repo,
52		cmd:  cmd,
53		out:  out,
54	}
55}
56
57func (e *testEnv) Execute(t *testing.T) {
58	t.Helper()
59
60	ctx := context.WithValue(context.Background(), "cwd", e.cwd)
61	require.NoError(t, e.cmd.ExecuteContext(ctx))
62}
63
64func requireGoldenFileEqual(t *testing.T, path string, act []byte) {
65	t.Helper()
66
67	// Replace Windows line terminators
68	act = []byte(strings.ReplaceAll(string(act), "\r\n", "\n"))
69
70	path = filepath.Join("testdata", path)
71
72	if *update {
73		require.NoError(t, ioutil.WriteFile(path, act, 0644))
74	}
75
76	exp, err := ioutil.ReadFile(path)
77	require.NoError(t, err)
78	require.Equal(t, string(exp), string(act))
79}
80
81func TestNewRootCommand(t *testing.T) {
82	testEnv := newTestEnv(t)
83	testEnv.Execute(t)
84
85	requireGoldenFileEqual(t, "root_out_golden.txt", testEnv.out.Bytes())
86}