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

     1  package cli
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	"github.com/elves/elvish/pkg/cli/term"
     8  )
     9  
    10  // RenderTest is a test case to be used in TestRenderer.
    11  type RenderTest struct {
    12  	Name   string
    13  	Given  Renderer
    14  	Width  int
    15  	Height int
    16  	Want   interface{ Buffer() *term.Buffer }
    17  }
    18  
    19  // TestRender runs the given Renderer tests.
    20  func TestRender(t *testing.T, tests []RenderTest) {
    21  	t.Helper()
    22  	for _, test := range tests {
    23  		t.Run(test.Name, func(t *testing.T) {
    24  			t.Helper()
    25  			buf := test.Given.Render(test.Width, test.Height)
    26  			wantBuf := test.Want.Buffer()
    27  			if !reflect.DeepEqual(buf, wantBuf) {
    28  				t.Errorf("Buffer mismatch")
    29  				t.Logf("Got: %s", buf.TTYString())
    30  				t.Logf("Want: %s", wantBuf.TTYString())
    31  			}
    32  		})
    33  	}
    34  }
    35  
    36  // HandleTest is a test case to be used in TestHandle.
    37  type HandleTest struct {
    38  	Name   string
    39  	Given  Handler
    40  	Event  term.Event
    41  	Events []term.Event
    42  
    43  	WantNewState  interface{}
    44  	WantUnhandled bool
    45  }
    46  
    47  // TestHandle runs the given Handler tests.
    48  func TestHandle(t *testing.T, tests []HandleTest) {
    49  	t.Helper()
    50  
    51  	for _, test := range tests {
    52  		t.Run(test.Name, func(t *testing.T) {
    53  			t.Helper()
    54  			var handled bool
    55  			switch {
    56  			case test.Event != nil && test.Events != nil:
    57  				t.Fatal("Malformed test case: both Event and Events non-nil:",
    58  					test.Event, test.Events)
    59  			case test.Event == nil && test.Events == nil:
    60  				t.Fatal("Malformed test case: both Event and Events nil")
    61  			case test.Event != nil:
    62  				handled = test.Given.Handle(test.Event)
    63  			default: // test.Events != nil
    64  				for _, event := range test.Events {
    65  					handled = test.Given.Handle(event)
    66  				}
    67  			}
    68  			if handled != !test.WantUnhandled {
    69  				t.Errorf("Got handled %v, want %v", handled, !test.WantUnhandled)
    70  			}
    71  			if test.WantNewState != nil {
    72  				state := getState(test.Given)
    73  				if !reflect.DeepEqual(state, test.WantNewState) {
    74  					t.Errorf("Got state %v, want %v", state, test.WantNewState)
    75  				}
    76  			}
    77  		})
    78  	}
    79  }
    80  
    81  func getState(v interface{}) interface{} {
    82  	rv := reflect.ValueOf(v)
    83  	if rv.Kind() == reflect.Ptr {
    84  		rv = reflect.Indirect(rv)
    85  	}
    86  	return rv.FieldByName("State").Interface()
    87  }