Simulating input
Make the UI reachable from a test
A test needs to get at the widgets it taps and reads. The simplest way is to
build the UI in a function that returns them, and call that function from both
main and the test:
// counter holds the widgets a test needs to reach.
type counter struct {
name *widget.Entry
add *widget.Button
output *widget.Label
count int
}
func newCounter() *counter {
c := &counter{
name: widget.NewEntry(),
output: widget.NewLabel("Nobody has clicked yet"),
}
c.add = widget.NewButton("Click", func() {
c.count++
c.output.SetText(c.name.Text + " clicked " + strconv.Itoa(c.count) + " times")
})
return c
}
func (c *counter) content() core.CanvasObject {
return container.NewVBox(c.name, c.add, c.output)
}
func main() {
a := app.New()
w := a.NewWindow("Counter")
w.SetContent(newCounter().content())
bellui.ShowAndRun(w)
}Tap, type, check
Put the test next to the code, in a _test.go file of the same package:
func TestCounter_TypeAndTap(t *testing.T) {
test.NewTempApp(t) // an in-memory app, torn down when the test ends
c := newCounter()
w := test.NewTempWindow(t, c.content())
w.Resize(w.Content().MinSize())
test.Type(c.name, "Ada")
test.Tap(c.add)
test.Tap(c.add)
if got, want := c.output.Text, "Ada clicked 2 times"; got != want {
t.Errorf("label = %q, want %q", got, want)
}
}Run it with go test ./.... No window opens.
test.Typefocuses the widget and then sends the text one character at a time, as typing would.test.Taptaps the widget. It runs the widget’s tap handling, including moving focus, so the button’sOnTappedfunction runs.- After that, read the widgets’ fields, such as
Label.Text, and compare them with what you expect.
Resizing the window to its content’s minimum size, as above, gives every widget a real size and position. Do this when the test depends on layout, or when it taps a position on the canvas rather than a widget.
Other input
| Function | Simulates |
|---|---|
Tap, TapAt(obj, pos) | A primary click or tap on a widget, optionally at a position inside it. |
DoubleTap | A double click. |
TapSecondary, TapSecondaryAt | A right click. |
LongPress, LongPressAt | A long press on a touch screen. |
TapCanvas(c, pos) | A tap at an absolute position on a canvas, delivered to whatever is there. |
Type(obj, text) | Typing into a focusable widget. |
TypeOnCanvas(c, text) | Typing to the canvas’s own key handler. |
Drag(c, pos, dx, dy) | A drag that starts at pos and moves by dx, dy. DragSteps does it in several steps. |
Scroll(c, pos, dx, dy) | A scroll wheel or trackpad scroll at a position. |
MoveMouse(c, pos) | Moving the pointer, so hover effects run. |
FocusNext(c), FocusPrevious(c) | Moving focus to the next or previous widget, as Tab and Shift-Tab do. |
Compose, ComposeCommit, ComposeCancel | Text entry through an input method, as used for Chinese, Japanese and Korean. |
All of these are in the test
package. The canvas c is usually w.Canvas() of your test window.
Testing an idle timer
bellui.LastUserActivity
returns when the user last tapped, dragged, scrolled or typed, for timers that
act after a while untouched. The helpers in the table above that simulate
input move it forward, as the real drivers do, whether or not a widget is
there to receive the input. MoveMouse does not, since moving the mouse with
no button held is not counted on a real device either. Nor does calling a
widget’s method or callback directly. test.NewApp, and so NewTempApp,
starts it back at the zero time, so one test’s input does not leak into the
next.
Write the idle rule so that it takes the current time, and the test does not have to wait:
const idleAfter = 2 * time.Minute // untouched this long, the app goes home
// isIdle reports whether the user has given no input for idleAfter.
// LastUserActivity is the zero time until the first input, so a fresh
// app counts as idle.
func isIdle(now time.Time) bool {
return now.Sub(bellui.LastUserActivity()) >= idleAfter
}func TestIdle(t *testing.T) {
test.NewTempApp(t) // starts LastUserActivity at the zero time
tapped := false
b := widget.NewButton("Open", func() { tapped = true })
w := test.NewTempWindow(t, b)
w.Resize(b.MinSize())
if !isIdle(time.Now()) {
t.Fatal("a fresh app should be idle")
}
// A simulated tap counts as user input, as a real one does.
test.Tap(b)
if !tapped || isIdle(time.Now()) {
t.Fatal("the app should not be idle right after a tap")
}
// Ask about a moment past the idle time instead of waiting for it.
if !isIdle(time.Now().Add(idleAfter)) {
t.Error("the app should be idle two minutes after the tap")
}
}The whole app, which goes back to its home screen after two minutes:
// An app that goes back to its home screen when nobody has touched it for a
// while, built so that a test can check the idle rule.
package main
import (
"time"
"github.com/belluikit/bellui"
"github.com/belluikit/bellui/app"
"github.com/belluikit/bellui/container"
"github.com/belluikit/bellui/widget"
)
const idleAfter = 2 * time.Minute // untouched this long, the app goes home
// isIdle reports whether the user has given no input for idleAfter.
// LastUserActivity is the zero time until the first input, so a fresh
// app counts as idle.
func isIdle(now time.Time) bool {
return now.Sub(bellui.LastUserActivity()) >= idleAfter
}
func main() {
a := app.New()
w := a.NewWindow("Kiosk")
home := widget.NewLabel("Welcome")
details := widget.NewLabel("Details")
stack := container.NewStack(home, details)
details.Hide()
open := widget.NewButton("Open details", func() {
home.Hide()
details.Show()
})
// Check once a second, and go home when idle.
go func() {
for range time.Tick(time.Second) {
bellui.Do(func() {
if isIdle(time.Now()) && details.Visible() {
details.Hide()
home.Show()
}
})
}
}()
w.SetContent(container.NewVBox(stack, open))
bellui.ShowAndRun(w)
}Assertion helpers
The package has a few assertions for common checks. They report a failure
through t, and most also return false, so you can stop the test early if
you need to.
func TestCounter_Layout(t *testing.T) {
test.NewTempApp(t)
c := newCounter()
w := test.NewTempWindow(t, c.content())
w.Resize(w.Content().MinSize())
test.AssertVisible(t, c.add)
test.AssertEnabled(t, c.add)
test.AssertMinSizeAtLeast(t, c.add, 40, 20)
c.add.Disable()
test.AssertDisabled(t, c.add)
}| Function | Checks |
|---|---|
AssertVisible, AssertHidden | The object’s Visible() state. |
AssertEnabled, AssertDisabled | A widget that can be disabled. |
AssertWidgetSize(t, obj, w, h) | The current size, to within 1.5 units. |
AssertWidgetPosition(t, obj, x, y) | The current position, to within 1.5 units. |
AssertMinSizeAtLeast(t, obj, w, h) | The minimum size is at least this big. |
AssertFitsWithin(t, obj, w, h) | The current size is no bigger than this. |
AssertCanvasTappableAt(t, c, pos) | Something tappable is at this position. |
AssertNotificationSent(t, n, f) | Running f sends the notification n. |
Themes in tests
The test app starts with a test theme whose colours are deliberately plain.
test.Theme and
test.NewTheme
define every size the theme has, so widgets lay out as they would with a
real theme. For example, tab containers leave a content margin of 12 under
test.Theme and 18 under test.NewTheme.
To check how your UI looks with another theme,
test.ApplyTheme(t, th)
switches the theme and switches it back when the test ends.
Releasing renderers in benchmarks
A widget’s renderer is cached the first time it is needed, and outside a
running app nothing releases it. A benchmark or test that builds widgets in a
loop therefore keeps every one of them in memory.
test.DestroyRenderers(tb, obj)
destroys the cached renderers of obj and everything under it, the way
closing a window does:
func BenchmarkCard(b *testing.B) {
test.NewTempApp(b)
for b.Loop() {
card := widget.NewCard("Title", "", container.NewVBox(
widget.NewLabel("Body"), widget.NewButton("Open", nil)))
test.WidgetRenderer(card).Layout(card.MinSize()) // builds the renderers
test.DestroyRenderers(b, card) // or they stay cached
}
}It runs when you call it, not when the test ends. To release a tree at the
end of a test, call it from t.Cleanup. It does not reach pop-ups and
overlays, which are not under obj, nor the unused items a list or other
collection keeps for reuse. A widget used again afterwards gets a new
renderer.
The complete test
package main
import (
"testing"
"github.com/belluikit/bellui/test"
)
func TestCounter_TypeAndTap(t *testing.T) {
test.NewTempApp(t) // an in-memory app, torn down when the test ends
c := newCounter()
w := test.NewTempWindow(t, c.content())
w.Resize(w.Content().MinSize())
test.Type(c.name, "Ada")
test.Tap(c.add)
test.Tap(c.add)
if got, want := c.output.Text, "Ada clicked 2 times"; got != want {
t.Errorf("label = %q, want %q", got, want)
}
}
func TestCounter_Layout(t *testing.T) {
test.NewTempApp(t)
c := newCounter()
w := test.NewTempWindow(t, c.content())
w.Resize(w.Content().MinSize())
test.AssertVisible(t, c.add)
test.AssertEnabled(t, c.add)
test.AssertMinSizeAtLeast(t, c.add, 40, 20)
c.add.Disable()
test.AssertDisabled(t, c.add)
}