...

Source file src/code.rocket9labs.com/tslocum/etk/kibodo/keyboard_test.go

Documentation: code.rocket9labs.com/tslocum/etk/kibodo

     1  package kibodo
     2  
     3  import (
     4  	"log"
     5  	"runtime"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/hajimehoshi/ebiten/v2"
    10  	"github.com/hajimehoshi/ebiten/v2/examples/resources/fonts"
    11  	"golang.org/x/image/font/opentype"
    12  	"golang.org/x/image/font/sfnt"
    13  )
    14  
    15  // TODO test presses registered
    16  
    17  func TestKeyboard_Draw(t *testing.T) {
    18  	k := newTestKeyboard()
    19  
    20  	// Warm caches
    21  	k.drawBackground()
    22  }
    23  
    24  func BenchmarkKeyboard_Draw(b *testing.B) {
    25  	k := newTestKeyboard()
    26  
    27  	// Warm caches
    28  	k.drawBackground()
    29  
    30  	b.ReportAllocs()
    31  	b.ResetTimer()
    32  	for i := 0; i < b.N; i++ {
    33  		k.drawBackground()
    34  	}
    35  }
    36  
    37  func BenchmarkKeyboard_Press(b *testing.B) {
    38  	go func() {
    39  		time.Sleep(2 * time.Second)
    40  
    41  		k := newTestKeyboard()
    42  
    43  		// Warm caches
    44  		k.drawBackground()
    45  
    46  		b.ReportAllocs()
    47  		b.ResetTimer()
    48  		for i := 0; i < b.N; i++ {
    49  			k.drawBackground()
    50  			k.keys[0][0].pressed = true
    51  			k.drawBackground()
    52  			k.keys[0][0].pressed = false
    53  		}
    54  	}()
    55  
    56  	runtime.LockOSThread()
    57  
    58  	err := ebiten.RunGame(NewDummyGame())
    59  	if err != nil {
    60  		b.Error(err)
    61  	}
    62  }
    63  
    64  func newTestKeyboard() *Keyboard {
    65  	k := NewKeyboard(defaultFont())
    66  	k.SetRect(0, 0, 300, 100)
    67  
    68  	return k
    69  }
    70  
    71  type DummyGame struct {
    72  	ready bool
    73  }
    74  
    75  func (d *DummyGame) Update() error {
    76  	return nil
    77  }
    78  
    79  func (d *DummyGame) Draw(screen *ebiten.Image) {
    80  	d.ready = true
    81  }
    82  
    83  func (d *DummyGame) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
    84  	return outsideWidth, outsideHeight
    85  }
    86  
    87  func NewDummyGame() *DummyGame {
    88  	return &DummyGame{}
    89  }
    90  
    91  func defaultFont() *sfnt.Font {
    92  	f, err := opentype.Parse(fonts.MPlus1pRegular_ttf)
    93  	if err != nil {
    94  		log.Fatal(err)
    95  	}
    96  	return f
    97  }
    98  

View as plain text