File: widget_test.go

package info (click to toggle)
elvish 0.21.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,372 kB
  • sloc: javascript: 236; sh: 130; python: 104; makefile: 88; xml: 9
file content (93 lines) | stat: -rw-r--r-- 2,087 bytes parent folder | download | duplicates (2)
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
package tk

import (
	"testing"

	"src.elv.sh/pkg/cli/term"
	"src.elv.sh/pkg/ui"
)

type testWidget struct {
	// Text to render.
	text ui.Text
	// Which events to accept.
	accepted []term.Event
	// A record of events that have been handled.
	handled []term.Event
}

func (w *testWidget) Render(width, height int) *term.Buffer {
	buf := term.NewBufferBuilder(width).WriteStyled(w.text).Buffer()
	buf.TrimToLines(0, height)
	return buf
}

func (w *testWidget) Handle(e term.Event) bool {
	for _, accept := range w.accepted {
		if e == accept {
			w.handled = append(w.handled, e)
			return true
		}
	}
	return false
}

func TestDummyBindings(t *testing.T) {
	w := Empty{}
	b := DummyBindings{}
	for _, event := range []term.Event{term.K('a'), term.PasteSetting(true)} {
		if b.Handle(w, event) {
			t.Errorf("should not handle")
		}
	}
}

func TestMapBindings(t *testing.T) {
	widgetCh := make(chan Widget, 1)
	w := Empty{}
	b := MapBindings{term.K('a'): func(w Widget) { widgetCh <- w }}
	handled := b.Handle(w, term.K('a'))
	if !handled {
		t.Errorf("should handle")
	}
	if gotWidget := <-widgetCh; gotWidget != w {
		t.Errorf("function called with widget %v, want %v", gotWidget, w)
	}
	handled = b.Handle(w, term.K('b'))
	if handled {
		t.Errorf("should not handle")
	}
}

func TestFuncBindings(t *testing.T) {
	widgetCh := make(chan Widget, 1)
	eventCh := make(chan term.Event, 1)

	h := FuncBindings(func(w Widget, event term.Event) bool {
		widgetCh <- w
		eventCh <- event
		return event == term.K('a')
	})

	w := Empty{}
	event := term.K('a')
	handled := h.Handle(w, event)
	if !handled {
		t.Errorf("should handle")
	}
	if gotWidget := <-widgetCh; gotWidget != w {
		t.Errorf("function called with widget %v, want %v", gotWidget, w)
	}
	if gotEvent := <-eventCh; gotEvent != event {
		t.Errorf("function called with event %v, want %v", gotEvent, event)
	}

	event = term.K('b')
	handled = h.Handle(w, event)
	if handled {
		t.Errorf("should not handle")
	}
	if gotEvent := <-eventCh; gotEvent != event {
		t.Errorf("function called with event %v, want %v", gotEvent, event)
	}
}