github.com/elves/elvish@v0.15.0/pkg/cli/widget_test.go (about)

     1  package cli
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/elves/elvish/pkg/cli/term"
     7  	"github.com/elves/elvish/pkg/ui"
     8  )
     9  
    10  type testWidget struct {
    11  	// Text to render.
    12  	text ui.Text
    13  	// Which events to accept.
    14  	accepted []term.Event
    15  	// A record of events that have been handled.
    16  	handled []term.Event
    17  }
    18  
    19  func (w *testWidget) Render(width, height int) *term.Buffer {
    20  	buf := term.NewBufferBuilder(width).WriteStyled(w.text).Buffer()
    21  	buf.TrimToLines(0, height)
    22  	return buf
    23  }
    24  
    25  func (w *testWidget) Handle(e term.Event) bool {
    26  	for _, accept := range w.accepted {
    27  		if e == accept {
    28  			w.handled = append(w.handled, e)
    29  			return true
    30  		}
    31  	}
    32  	return false
    33  }
    34  
    35  func TestDummyHandler(t *testing.T) {
    36  	h := DummyHandler{}
    37  	for _, event := range []term.Event{term.K('a'), term.PasteSetting(true)} {
    38  		if h.Handle(event) {
    39  			t.Errorf("should not handle")
    40  		}
    41  	}
    42  }
    43  
    44  func TestMapHandler(t *testing.T) {
    45  	var aCalled bool
    46  	h := MapHandler{term.K('a'): func() { aCalled = true }}
    47  	handled := h.Handle(term.K('a'))
    48  	if !handled {
    49  		t.Errorf("should handle")
    50  	}
    51  	if !aCalled {
    52  		t.Errorf("should call callback")
    53  	}
    54  	handled = h.Handle(term.K('b'))
    55  	if handled {
    56  		t.Errorf("should not handle")
    57  	}
    58  }
    59  
    60  func TestFuncHandler(t *testing.T) {
    61  	eventCh := make(chan term.Event, 1)
    62  	h := FuncHandler(func(event term.Event) bool {
    63  		eventCh <- event
    64  		return event == term.K('a')
    65  	})
    66  
    67  	handled := h.Handle(term.K('a'))
    68  	if !handled {
    69  		t.Errorf("should handle")
    70  	}
    71  	if <-eventCh != term.K('a') {
    72  		t.Errorf("should call func")
    73  	}
    74  
    75  	handled = h.Handle(term.K('b'))
    76  	if handled {
    77  		t.Errorf("should not handle")
    78  	}
    79  	if <-eventCh != term.K('b') {
    80  		t.Errorf("should call func")
    81  	}
    82  }