Repository navigation
Expand file tree
/
Copy pathtest_context.go
More file actions
104 lines (90 loc) · 2.49 KB
/
Copy pathtest_context.go
File metadata and controls
104 lines (90 loc) · 2.49 KB
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
103
104
package test
import (
"github.com/charmbracelet/bubbles/key"
"github.com/idursun/jjui/internal/config"
"github.com/idursun/jjui/internal/ui/context"
"testing"
tea "github.com/charmbracelet/bubbletea"
"github.com/idursun/jjui/internal/ui/common"
"github.com/stretchr/testify/assert"
)
type ExpectedCommand struct {
args []string
output []byte
called bool
}
func (e *ExpectedCommand) SetOutput(output []byte) *ExpectedCommand {
e.output = output
return e
}
type TestContext struct {
*testing.T
selectedItem context.SelectedItem
expectations map[string][]*ExpectedCommand
}
func (t *TestContext) KeyMap() config.KeyMappings[key.Binding] {
return config.Convert(config.DefaultKeyMappings)
}
func (t *TestContext) SelectedItem() context.SelectedItem {
return t.selectedItem
}
func (t *TestContext) SetSelectedItem(item context.SelectedItem) tea.Cmd {
t.selectedItem = item
return nil
}
func (t *TestContext) RunCommandImmediate(args []string) ([]byte, error) {
subCommand := args[0]
if _, ok := t.expectations[subCommand]; !ok {
assert.Fail(t, "unexpected command", subCommand)
}
expectations := t.expectations[subCommand]
if len(expectations) == 0 {
assert.Fail(t, "unexpected command", subCommand)
}
for _, e := range expectations {
if assert.Equal(t.T, e.args, args) {
e.called = true
return e.output, nil
}
}
assert.Fail(t, "unexpected command", subCommand)
return nil, nil
}
func (t *TestContext) RunCommand(args []string, continuations ...tea.Cmd) tea.Cmd {
cmds := make([]tea.Cmd, 0)
cmds = append(cmds, func() tea.Msg {
_, _ = t.RunCommandImmediate(args)
return common.CommandCompletedMsg{}
})
cmds = append(cmds, continuations...)
return tea.Batch(cmds...)
}
func (t *TestContext) RunInteractiveCommand(args []string, continuation tea.Cmd) tea.Cmd {
return t.RunCommand(args, continuation)
}
func (t *TestContext) Expect(args []string) *ExpectedCommand {
subCommand := args[0]
if _, ok := t.expectations[subCommand]; !ok {
t.expectations[subCommand] = make([]*ExpectedCommand, 0)
}
e := &ExpectedCommand{
args: args,
}
t.expectations[subCommand] = append(t.expectations[subCommand], e)
return e
}
func (t *TestContext) Verify() {
for subCommand, expectations := range t.expectations {
for _, e := range expectations {
if !e.called {
assert.Fail(t, "expected command not called", subCommand)
}
}
}
}
func NewTestContext(t *testing.T) *TestContext {
return &TestContext{
T: t,
expectations: make(map[string][]*ExpectedCommand),
}
}