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