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, commands.GitBugNamespace)
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 // Replace Windows line terminators
67 // act = []byte(strings.ReplaceAll(string(act), "\r\n", "\n"))
68
69 path = filepath.Join("testdata", path)
70
71 if *update {
72 require.NoError(t, ioutil.WriteFile(path, act, 0644))
73 }
74
75 exp, err := ioutil.ReadFile(path)
76 require.NoError(t, err)
77 require.Equal(t, string(exp), string(act))
78}
79
80func TestNewRootCommand(t *testing.T) {
81 testEnv := newTestEnv(t)
82 testEnv.Execute(t)
83
84 requireGoldenFileEqual(t, "root_out_golden.txt", testEnv.out.Bytes())
85}