github.com/cybriq/giocore@v0.0.7-0.20210703034601-cfb9cb5f3900/gesture/gesture_test.go (about)

     1  package gesture
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/cybriq/giocore/io/event"
     8  	"github.com/cybriq/giocore/io/pointer"
     9  	"github.com/cybriq/giocore/io/router"
    10  	"github.com/cybriq/giocore/op"
    11  )
    12  
    13  func TestMouseClicks(t *testing.T) {
    14  	for _, tc := range []struct {
    15  		label  string
    16  		events []event.Event
    17  		clicks []int // number of combined clicks per click (single, double...)
    18  	}{
    19  		{
    20  			label:  "single click",
    21  			events: mouseClickEvents(200 * time.Millisecond),
    22  			clicks: []int{1},
    23  		},
    24  		{
    25  			label: "double click",
    26  			events: mouseClickEvents(
    27  				100*time.Millisecond,
    28  				100*time.Millisecond+doubleClickDuration-1),
    29  			clicks: []int{1, 2},
    30  		},
    31  		{
    32  			label: "two single clicks",
    33  			events: mouseClickEvents(
    34  				100*time.Millisecond,
    35  				100*time.Millisecond+doubleClickDuration+1),
    36  			clicks: []int{1, 1},
    37  		},
    38  	} {
    39  		t.Run(tc.label, func(t *testing.T) {
    40  			var click Click
    41  			var ops op.Ops
    42  			click.Add(&ops)
    43  
    44  			var r router.Router
    45  			r.Frame(&ops)
    46  			r.Queue(tc.events...)
    47  
    48  			events := click.Events(&r)
    49  			clicks := filterMouseClicks(events)
    50  			if got, want := len(clicks), len(tc.clicks); got != want {
    51  				t.Fatalf("got %d mouse clicks, expected %d", got, want)
    52  			}
    53  
    54  			for i, click := range clicks {
    55  				if got, want := click.NumClicks, tc.clicks[i]; got != want {
    56  					t.Errorf("got %d combined mouse clicks, expected %d", got, want)
    57  				}
    58  			}
    59  		})
    60  	}
    61  }
    62  
    63  func mouseClickEvents(times ...time.Duration) []event.Event {
    64  	press := pointer.Event{
    65  		Type:    pointer.Press,
    66  		Source:  pointer.Mouse,
    67  		Buttons: pointer.ButtonPrimary,
    68  	}
    69  	events := make([]event.Event, 0, 2*len(times))
    70  	for _, t := range times {
    71  		release := press
    72  		release.Type = pointer.Release
    73  		release.Time = t
    74  		events = append(events, press, release)
    75  	}
    76  	return events
    77  }
    78  
    79  func filterMouseClicks(events []ClickEvent) []ClickEvent {
    80  	var clicks []ClickEvent
    81  	for _, ev := range events {
    82  		if ev.Type == TypeClick {
    83  			clicks = append(clicks, ev)
    84  		}
    85  	}
    86  	return clicks
    87  }