github.com/oweisse/u-root@v0.0.0-20181109060735-d005ad25fef1/cmds/elvish/edit/listing_test.go (about)

     1  package edit
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"strconv"
     7  	"testing"
     8  
     9  	"github.com/u-root/u-root/cmds/elvish/edit/eddefs"
    10  	"github.com/u-root/u-root/cmds/elvish/edit/ui"
    11  )
    12  
    13  type provider struct {
    14  	elems    []string
    15  	accepted int
    16  }
    17  
    18  func (p provider) Len() int                       { return len(p.elems) }
    19  func (p provider) Filter(string) int              { return 0 }
    20  func (p provider) Accept(i int, ed eddefs.Editor) { p.accepted = i }
    21  func (p provider) ModeTitle(i int) string         { return fmt.Sprintf("test %d", i) }
    22  
    23  func (p provider) Show(i int) (string, ui.Styled) {
    24  	return strconv.Itoa(i), ui.Unstyled(p.elems[i])
    25  }
    26  
    27  var (
    28  	p  = provider{[]string{"foo", "bar", "foobar", "lorem", "ipsum"}, -1}
    29  	ls = newListing(emptyBindingMap, p)
    30  )
    31  
    32  func TestListing(t *testing.T) {
    33  	wantedModeLine := ui.NewModeLineRenderer("test 0", "")
    34  	if modeLine := ls.ModeLine(); modeLine != wantedModeLine {
    35  		t.Errorf("ls.ModeLine() = %v, want %v", modeLine, wantedModeLine)
    36  	}
    37  
    38  	// Selecting the first element and rendering with height=2. We expect to see
    39  	// the first 2 elements, with the first being shown as selected.
    40  	testListingList(t, 0, 2, listingWithScrollBarRenderer{
    41  		listingRenderer: listingRenderer{[]ui.Styled{
    42  			{"0 foo", styleForSelected},
    43  			{"1 bar", ui.Styles{}},
    44  		}},
    45  		n: 5, low: 0, high: 2, height: 2,
    46  	})
    47  	// Selecting the last element and rendering with height=2. We expect to see
    48  	// the last 2 elements, with the last being shown as selected.
    49  	testListingList(t, 4, 2, listingWithScrollBarRenderer{
    50  		listingRenderer: listingRenderer{[]ui.Styled{
    51  			{"3 lorem", ui.Styles{}},
    52  			{"4 ipsum", styleForSelected},
    53  		}},
    54  		n: 5, low: 3, high: 5, height: 2,
    55  	})
    56  	// Selecting the middle element and rendering with height=3. We expect to
    57  	// see the middle element and two elements around it, with the middle being
    58  	// shown as selected.
    59  	testListingList(t, 2, 3, listingWithScrollBarRenderer{
    60  		listingRenderer: listingRenderer{[]ui.Styled{
    61  			{"1 bar", ui.Styles{}},
    62  			{"2 foobar", styleForSelected},
    63  			{"3 lorem", ui.Styles{}},
    64  		}},
    65  		n: 5, low: 1, high: 4, height: 3,
    66  	})
    67  }
    68  
    69  func testListingList(t *testing.T, i, h int, want ui.Renderer) {
    70  	ls.selected = i
    71  	if r := ls.List(h); !reflect.DeepEqual(r, want) {
    72  		t.Errorf("selecting %d, ls.List(%d) = %v, want %v", i, h, r, want)
    73  	}
    74  }