aboutsummaryrefslogtreecommitdiffstats
path: root/commands/root_test.go
blob: 5e780ec7329b1adea4addefef82157f9cf678405 (plain) (blame)
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
75
76
77
78
79
80
81
82
package commands_test

import (
	"bytes"
	"context"
	"flag"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	"github.com/MichaelMure/git-bug/commands"
	"github.com/MichaelMure/git-bug/repository"
	"github.com/spf13/cobra"
	"github.com/stretchr/testify/require"
)

var update = flag.Bool("update", false, "pass -update to the test runner to update golden files")

type testEnv struct {
	cwd  string
	repo *repository.GoGitRepo
	cmd  *cobra.Command
	out  *bytes.Buffer
}

func newTestEnv(t *testing.T) *testEnv {
	t.Helper()

	cwd, err := ioutil.TempDir("", "")
	require.NoError(t, err)
	t.Cleanup(func() {
		require.NoError(t, os.RemoveAll(cwd))
	})

	repo, err := repository.InitGoGitRepo(cwd)
	require.NoError(t, err)
	t.Cleanup(func() {
		require.NoError(t, repo.Close())
	})

	out := new(bytes.Buffer)
	cmd := commands.NewRootCommand()
	cmd.SetArgs([]string{})
	cmd.SetErr(out)
	cmd.SetOut(out)

	return &testEnv{
		cwd:  cwd,
		repo: repo,
		cmd:  cmd,
		out:  out,
	}
}

func (e *testEnv) Execute(t *testing.T) {
	t.Helper()

	ctx := context.WithValue(context.Background(), "cwd", e.cwd)
	require.NoError(t, e.cmd.ExecuteContext(ctx))
}

func requireGoldenFileEqual(t *testing.T, path string, act []byte) {
	t.Helper()

	path = filepath.Join("testdata", path)

	if *update {
		require.NoError(t, ioutil.WriteFile(path, act, 0644))
	}

	exp, err := ioutil.ReadFile(path)
	require.NoError(t, err)
	require.Equal(t, exp, act)
}

func TestNewRootCommand(t *testing.T) {
	testEnv := newTestEnv(t)
	testEnv.Execute(t)

	requireGoldenFileEqual(t, "root_out_golden.txt", testEnv.out.Bytes())
}