aboutsummaryrefslogtreecommitdiffstats
path: root/commands/execenv/env_testing.go
blob: 15d7b646fda8d9b72e3784509cfaf7b73f6f6c65 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package execenv

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/MichaelMure/git-bug/cache"
	"github.com/MichaelMure/git-bug/repository"
)

var _ In = &TestIn{}

type TestIn struct {
	*bytes.Buffer
	forceIsTerminal bool
}

func (t *TestIn) IsTerminal() bool {
	return t.forceIsTerminal
}

func (t *TestIn) ForceIsTerminal(value bool) {
	t.forceIsTerminal = value
}

var _ Out = &TestOut{}

type TestOut struct {
	*bytes.Buffer
	forceIsTerminal bool
}

func (te *TestOut) Printf(format string, a ...interface{}) {
	_, _ = fmt.Fprintf(te.Buffer, format, a...)
}

func (te *TestOut) Print(a ...interface{}) {
	_, _ = fmt.Fprint(te.Buffer, a...)
}

func (te *TestOut) Println(a ...interface{}) {
	_, _ = fmt.Fprintln(te.Buffer, a...)
}

func (te *TestOut) PrintJSON(v interface{}) error {
	raw, err := json.MarshalIndent(v, "", "    ")
	if err != nil {
		return err
	}
	te.Println(string(raw))
	return nil
}

func (te *TestOut) IsTerminal() bool {
	return te.forceIsTerminal
}

func (te *TestOut) Width() int {
	return 80
}

func (te *TestOut) Raw() io.Writer {
	return te.Buffer
}

func (te *TestOut) ForceIsTerminal(value bool) {
	te.forceIsTerminal = value
}

func NewTestEnv(t *testing.T) *Env {
	t.Helper()
	return newTestEnv(t, false)
}

func NewTestEnvTerminal(t *testing.T) *Env {
	t.Helper()
	return newTestEnv(t, true)
}

func newTestEnv(t *testing.T, isTerminal bool) *Env {
	repo := repository.CreateGoGitTestRepo(t, false)

	backend, err := cache.NewRepoCacheNoEvents(repo)
	require.NoError(t, err)

	t.Cleanup(func() {
		backend.Close()
	})

	return &Env{
		Repo:    repo,
		Backend: backend,
		In:      &TestIn{Buffer: &bytes.Buffer{}, forceIsTerminal: isTerminal},
		Out:     &TestOut{Buffer: &bytes.Buffer{}, forceIsTerminal: isTerminal},
		Err:     &TestOut{Buffer: &bytes.Buffer{}, forceIsTerminal: isTerminal},
	}
}