kittest

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package kittest drives a giokit UI headlessly: real layout, real input routing, real GPU rendering (EGL surfaceless), no window or display.

Typical test:

h := kittest.NewT(t, 1100, 720, v.Frame) // skips if no GPU (KITTEST_REQUIRE_GPU=1 fails)
h.Theme = v.th                          // enables glyph checks
h.ClickID("save")                       // input → settle → stale check
h.ExpectTextIn("row:42", "Saved")
h.ExpectClean()                         // audit: ids, targets, occlusion, glyphs

Input methods (Click, Key, Type...) settle the UI and, in strict mode, re-render once more to catch a stale frame. Queries (Find, Texts, Role) read the last frame's semantic tree and pixels. The Expect methods report through the test and need a harness from NewT; on a standalone harness from New they panic. Package kittest/conform builds the per-control conformance suite on top of it.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Center

func Center(r image.Rectangle) image.Point

Center is the middle point of r.

func Near

func Near(a, b color.NRGBA, tol uint8) bool

Near reports whether two colors match within tol per channel (GPU rounding).

func NoGPU

func NoGPU(t TB, err error)

NoGPU skips t, or fails it when RequireGPU is set. Harness constructors call it when New returns an error.

func RequireGPU

func RequireGPU() bool

RequireGPU reports whether a missing headless GPU must fail tests instead of skipping them. Set KITTEST_REQUIRE_GPU=1 in CI, or a runner without EGL reports ok having run nothing.

func ShotName

func ShotName(test string) string

ShotName turns a test name into the file name NewTAt saves its final frame under: every byte other than an ASCII letter, digit, '-', '_' or '.' becomes '_', so a subtest name ("Gallery/dark theme") stays one flat, portable file name.

Types

type A11yNode

type A11yNode struct {
	ID, Label          string           // semantic id (description) and spoken label
	Class              semantic.ClassOp // Gio's semantic class
	Bounds             image.Rectangle  // window bounds in pixels
	Disabled, Selected bool             // Gio's enabled and selected state
	Children           []A11yNode       // nested nodes, in draw order
}

A11yNode is a stable, inspectable snapshot of one semantic node.

type FocusLeak

type FocusLeak struct {
	To     string // the focused id outside the trap
	Lost   bool   // nothing with an id holds focus
	Closed bool   // the trap itself is no longer on screen
}

FocusLeak says how focus left a focus trap. Exactly one field is set.

func (FocusLeak) String

func (l FocusLeak) String() string

String describes the leak for a test failure.

type Harness

type Harness struct {
	Size   image.Point // window size in pixels
	Metric unit.Metric // the window's scale: PxPerDp and PxPerSp
	Frames int         // total frames drawn
	// Now is the virtual clock handed to every frame (gtx.Now); it starts at
	// 2026-01-01 00:00 UTC. Settle advances it by FrameStep (default 1/60 s)
	// while the UI asks for immediate redraws (animations), so animations run
	// to completion deterministically. Wait advances it too.
	Now       time.Time
	FrameStep time.Duration // the clock step per settled frame

	// Strict re-renders after every input and fails if anything changed, i.e.
	// the settled frame was stale (draw-before-handle, late hover reads,
	// missing Notify). On by default.
	Strict bool
	// Theme enables the missing-glyph audit and ink recognition in the
	// contrast audit. Nil by default.
	Theme *kit.Theme
	// MinTarget is the smallest clickable size the audit accepts (default 16dp).
	MinTarget unit.Dp
	// MinContrast is the smallest text contrast ratio the audit accepts
	// (default WCAG AA: 4.5), MinContrastLarge the same for large text
	// (default 3). 0 turns the check off.
	MinContrast, MinContrastLarge float64
	// contains filtered or unexported fields
}

Harness runs one UI headlessly. Make it with New (standalone: problems are recorded for Problems and fatal failures panic) or NewT (attached to a test: problems fail the test and fatal failures stop it). Every input method settles the UI and, in strict mode, checks the settled frame. The harness, like the UI it drives, belongs to one goroutine.

func New

func New(wdp, hdp int, scale float32, draw func(gtx layout.Context)) (*Harness, error)

New creates a standalone harness of wdp×hdp dp at the given scale (pixels per dp) and settles the UI. Problems found while settling, and later, are recorded for Problems; a fatal failure panics. It fails only when no headless GPU is available. Call Release when done.

func NewT

func NewT(t TB, wdp, hdp int, draw func(gtx layout.Context)) *Harness

NewT is NewTAt at scale 1.

func NewTAt

func NewTAt(t TB, wdp, hdp int, scale float32, draw func(gtx layout.Context)) *Harness

NewTAt creates a harness attached to t at the given scale (pixels per dp) and settles the UI. Every problem, from the first frame on, fails t. It skips t without a GPU (fails it under KITTEST_REQUIRE_GPU). On cleanup it saves the final frame to $KITTEST_SHOTS/<ShotName(test)>.png when that variable is set, then releases the harness. Scales 1.5 and 2 catch hairlines, rings and targets that only break on HiDPI screens.

func (*Harness) A11yTree

func (h *Harness) A11yTree() []A11yNode

A11yTree returns the semantic tree of the current frame. IDs are the stable automation addresses; labels are the text presented to users.

func (*Harness) App

func (h *Harness) App() *kit.App

App is an App for the code under test: pass it to kit.Spawn and Post so work runs off the UI goroutine as in a real window, and its callbacks run before the harness's next frame. RunTasks waits for the work to finish.

func (*Harness) Audit

func (h *Harness) Audit() []Problem

Audit inspects the current frame for structural problems:

  • unlabeled-clickable: clickable without a semantic id (untestable, mute to screen readers)
  • tiny-target: clickable smaller than MinTarget (often a collapsed Stack child)
  • occluded: another interactive area sits on top of a clickable's center
  • duplicate-id: two widgets share an id
  • missing-glyph: a label uses runes the theme's fonts can't draw (tofu)
  • low-contrast: an enabled label's text is under MinContrast against its background, measured from pixels (off while MinContrast is 0)

func (*Harness) BgColor

func (h *Harness) BgColor(id string) color.NRGBA

BgColor samples a widget's background 3px inside its left edge at mid height, where content rarely is. Use it to check hover/selection fills.

func (*Harness) ByRole

func (h *Harness) ByRole(role kit.Role, label string) string

ByRole returns the id of the one control with role and spoken label (as a screen reader announces it: "the Save button", "the Editor tab"), and fails when there is none or several. Querying this way checks the accessibility on the way: an unlabelled control cannot be found.

func (*Harness) Chord

func (h *Harness) Chord(chord string)

Chord presses a chord written like a kit.Keymap binding ("Ctrl+1", "Shortcut+K", "Escape").

func (*Harness) Click

func (h *Harness) Click(p image.Point)

Click moves to p, then presses and releases the primary button.

func (*Harness) ClickID

func (h *Harness) ClickID(id string)

ClickID clicks the center of the visible part of the widget tagged id. A widget clipped out of view (laid out past the end of a scrolled list) fails the test rather than clicking whatever covers that point.

func (*Harness) ClickIDMods

func (h *Harness) ClickIDMods(id string, mods key.Modifiers)

ClickIDMods clicks the widget tagged id holding modifiers.

func (*Harness) ClickMods

func (h *Harness) ClickMods(p image.Point, mods key.Modifiers)

ClickMods clicks at p holding modifiers (Shift-click to extend, Ctrl-click to toggle).

func (*Harness) ClickRole

func (h *Harness) ClickRole(role kit.Role, label string)

ClickRole clicks the control with role and spoken label (ByRole).

func (*Harness) Contrasts

func (h *Harness) Contrasts() []TextContrast

Contrasts measures every enabled, visible label from the rendered pixels: the background is the most common color in the label's box, the text color the pixel that contrasts with it most (a glyph's solid core). Disabled labels (Theme.Disable) are exempt, as in WCAG.

func (*Harness) Cursor

func (h *Harness) Cursor() pointer.Cursor

Cursor is the pointer cursor the UI requests at the current pointer position.

func (*Harness) Disabled

func (h *Harness) Disabled(id string) bool

Disabled reports whether the widget tagged id is disabled (kit's Theme.Disable), itself or through an ancestor. It fails the test if the id isn't on screen.

func (*Harness) DoubleClick

func (h *Harness) DoubleClick(p image.Point)

DoubleClick clicks twice at p in quick succession (gesture.Click reports NumClicks 2 for the second).

func (*Harness) DoubleClickID

func (h *Harness) DoubleClickID(id string)

DoubleClickID double-clicks the widget tagged id.

func (*Harness) Drag

func (h *Harness) Drag(from, to image.Point)

Drag presses at from, moves to to in a few steps, and releases there.

func (*Harness) DragID

func (h *Harness) DragID(id string, dx, dy int)

DragID drags the widget tagged id by (dx, dy) pixels from the center of its visible part.

func (*Harness) Dump

func (h *Harness) Dump(w io.Writer)

Dump prints the semantic tree (ids, labels, bounds): the first thing to look at when a Find fails or an audit finding is unclear. Nodes with neither an id nor a label are skipped, and their children shown one level up.

func (*Harness) ExpectBg

func (h *Harness) ExpectBg(id string, want color.NRGBA)

ExpectBg checks BgColor(id) within ±2 per channel.

func (*Harness) ExpectClean

func (h *Harness) ExpectClean()

ExpectClean fails the test for every Audit finding.

func (*Harness) ExpectEscapeCloses

func (h *Harness) ExpectEscapeCloses(id string)

ExpectEscapeCloses presses Escape and fails unless the widget tagged id (a popup, menu or dialog) is gone.

func (*Harness) ExpectFocusTrapped

func (h *Harness) ExpectFocusTrapped(id string, n int)

ExpectFocusTrapped fails if Tab or Shift+Tab (n presses each) moves focus out of the widget tagged id.

func (*Harness) ExpectGolden

func (h *Harness) ExpectGolden(name string)

ExpectGolden compares the frame to testdata/golden/<name>.png. Set KITTEST_UPDATE=1 to (re)write goldens. Tolerates GPU rounding: fails only if more than 0.1% of pixels differ by more than 8 in some colour channel. On a mismatch the actual frame is saved to a new temporary file named in the failure. Goldens are machine/driver specific; keep them for layout-heavy screens, not every test.

func (*Harness) ExpectID

func (h *Harness) ExpectID(id string) image.Rectangle

ExpectID returns the bounds of the widget tagged id, stopping the test if it is not on screen.

func (*Harness) ExpectNoID

func (h *Harness) ExpectNoID(id string)

ExpectNoID fails the test if a widget tagged id is on screen.

func (*Harness) ExpectPathBuilds

func (h *Harness) ExpectPathBuilds(max float64, act func())

ExpectPathBuilds runs act and fails the test if the frames it drew built more than max shapes each, on average. Use it on frames that move things rather than change them (scrolling, dragging, a sliding or fading panel, hover): those should replay recordings, so pass a small max (a few shapes for what really changes: a moving scrollbar thumb, the hovered control). Warm up first (one frame of the same kind), so the first recording of each cache isn't counted.

func (*Harness) ExpectShadersDrawn

func (h *Harness) ExpectShadersDrawn(act func())

ExpectShadersDrawn runs act and fails the test if any shader paint in the frames it drew fell back to its Fallback colour, reporting why. Use it to prove an effect drew rather than its fallback: on backends that cannot draw shaders (Direct3D and Metal until their variants are generated) it fails too, so gate it on the platforms that should.

func (*Harness) ExpectTabReachable

func (h *Harness) ExpectTabReachable()

ExpectTabReachable reports every enabled control that Tab skipped.

func (*Harness) ExpectText

func (h *Harness) ExpectText(s string)

ExpectText fails the test unless some label on screen is exactly s.

func (*Harness) ExpectTextIn

func (h *Harness) ExpectTextIn(id, s string)

ExpectTextIn fails the test unless the widget tagged id shows the label s (see TextsIn).

func (*Harness) Find

func (h *Harness) Find(id string) (image.Rectangle, bool)

Find returns the pixel bounds of the widget tagged with semantic id.

func (*Harness) FindText

func (h *Harness) FindText(s string) (image.Rectangle, bool)

FindText returns the bounds of the first text label exactly equal to s.

func (*Harness) FocusEscape

func (h *Harness) FocusEscape(id string, n int) (leak FocusLeak, ok bool)

FocusEscape presses Tab n times, then Shift+Tab n times, and reports how focus first left the widget tagged id, or ok false if it stayed inside: the focus trap a modal layer must have.

func (*Harness) FocusedID

func (h *Harness) FocusedID() string

FocusedID is the id of the focused widget. When focus is on a focus group (a list, tree, table or menu), it is the group's active item if that item is laid out, as a screen reader would announce it; otherwise the group.

func (*Harness) GPUStats

func (h *Harness) GPUStats() gpu.Stats

GPUStats returns the running totals of the harness's GPU (gpu.Stats).

func (*Harness) GroupMembers

func (h *Harness) GroupMembers() map[string][]string

GroupMembers maps each focus group laid out in the last frame to the ids of its members. A group is one Tab stop; arrows move inside it. The map is borrowed from the harness: valid until the next frame, not to be modified.

func (*Harness) Hover

func (h *Harness) Hover(id string)

Hover moves to the center of the visible part of the widget tagged id.

func (*Harness) IDs

func (h *Harness) IDs() []string

IDs returns every semantic id on screen, in draw order.

func (*Harness) Image

func (h *Harness) Image() *image.RGBA

Image returns the current frame.

func (*Harness) Key

func (h *Harness) Key(name key.Name, mods key.Modifiers)

Key presses and releases a key. Tab and Shift+Tab move focus unless the UI handled them. As in app.Window, a key counts as handled when delivering it requested a redraw: a handler that consumes Tab without calling Notify (or otherwise invalidating) lets focus move as well.

func (*Harness) KeyCode

func (h *Harness) KeyCode(code key.Code, name key.Name, mods key.Modifiers)

KeyCode presses and releases the physical key code, which the simulated keyboard layout types as name: KeyCode("KeyQ", "A", 0) is the top-left letter on AZERTY. It tests bindings by place (see key.Code) on other layouts; Key sends no code, so such bindings see the US layout.

func (*Harness) KeyDown

func (h *Harness) KeyDown(name key.Name, mods key.Modifiers)

KeyDown presses a key and holds it: a held modifier ("Ctrl" while testing a hint that shows during the hold). Release it with KeyUp.

func (*Harness) KeyUp

func (h *Harness) KeyUp(name key.Name, mods key.Modifiers)

KeyUp releases a key KeyDown pressed.

func (*Harness) Keys

func (h *Harness) Keys(names ...key.Name)

Keys presses and releases each key in turn, delivering them all to the same frame, as a real window does when keys arrive faster than frames (key repeat, a fast typist, a busy UI goroutine). Key settles between keys; Keys tests a handler against a batch. Tab and Shift+Tab are delivered to the UI but do not move focus.

func (*Harness) Move

func (h *Harness) Move(p image.Point)

Move sends a pointer move to p (pixels).

func (*Harness) PathBuilds

func (h *Harness) PathBuilds() int

PathBuilds is how many filled shapes the harness's GPU has flattened and uploaded so far, over every frame drawn.

func (*Harness) PathBuildsDuring

func (h *Harness) PathBuildsDuring(act func()) (builds, frames int)

PathBuildsDuring runs act and returns the shapes built and frames drawn while it ran (including Settle's and strict mode's frames).

func (*Harness) Pixel

func (h *Harness) Pixel(p image.Point) color.NRGBA

Pixel samples the current frame at p.

func (*Harness) Problems

func (h *Harness) Problems() []Problem

Problems returns a copy of the findings recorded while no test is attached (a harness from New). A harness from NewT reports them to the test instead, so this is empty.

func (*Harness) Release

func (h *Harness) Release()

Release frees the harness's GPU resources. The harness is unusable after.

func (*Harness) RightClick

func (h *Harness) RightClick(p image.Point)

RightClick moves to p, then presses and releases the secondary button.

func (*Harness) RightClickID

func (h *Harness) RightClickID(id string)

RightClickID right-clicks the widget tagged id (context menus).

func (*Harness) Role

func (h *Harness) Role(id string) kit.Role

Role is the role (semantic class) of the widget tagged id, or 0 (semantic.Unknown) when it has none or is not on screen.

func (*Harness) RunTasks

func (h *Harness) RunTasks()

RunTasks waits for every kit.Spawn started on h.App() to finish and its done callback to run and draw, including work those callbacks start in turn: it alternates waiting for running work with settling (which runs the callbacks) until no work is running, all under one 10s deadline; work still running or queued at the deadline (a callback that keeps re-posting itself, say) is a fatal failure. A cancelled task's done never runs, but RunTasks still waits for its work function to return. Callbacks queued with App.Post, from the test or from other callbacks, run in the settle (see Settle); RunTasks returns once no work is running and nothing is queued. It cannot see a goroutine of the app's own that has not posted yet. Before RunTasks, a test sees the UI as the user does while work is in flight.

func (*Harness) Save

func (h *Harness) Save(path string) error

Save writes the current frame as a PNG.

func (*Harness) SaveSheet

func (h *Harness) SaveSheet(path string, cols, downscale int) error

SaveSheet writes every Snap into one labeled grid PNG, cols frames wide, each frame downscaled by an integer factor (2 halves it). It creates the file's directory and writes nothing when there are no snaps. One image read instead of many: the cheap way for an agent to review several UI states.

func (*Harness) Scroll

func (h *Harness) Scroll(p image.Point, dy float32)

Scroll scrolls by dy pixels (positive = down) with the pointer at p.

func (*Harness) ScrollID

func (h *Harness) ScrollID(id string, dy float32)

ScrollID scrolls the region tagged id by dy pixels.

func (*Harness) Settle

func (h *Harness) Settle() int

Settle draws one frame, then keeps drawing while the UI requests an immediate redraw or h.App() has queued callbacks (App.Post triggers a frame), exactly like a real window, advancing the virtual clock one FrameStep per extra frame. It never invents input, so "one click and the screen is right" is a real assertion. Redraws scheduled for later (caret blink, continuous animations via kit.Loop, delays) are not chased; use Wait. It returns the number of frames drawn and reports no-settle after maxSettle frames.

func (*Harness) ShaderErr

func (h *Harness) ShaderErr() error

ShaderErr returns the latest shader paint or layer effect fallback reason, or nil if there has been none.

func (*Harness) Snap

func (h *Harness) Snap(label string)

Snap records the current frame under a label for SaveSheet. Every snap is a full-size copy held until the harness is dropped, so snap the states worth reviewing, not every frame.

func (*Harness) Stale

func (h *Harness) Stale() string

Stale draws one extra frame with no input and reports what changed, or "". A settled UI must be a fixed point: if another frame changes anything, the previous frame showed stale state and a real window would sit on it until the user moved the mouse. Compared are the semantic tree (ids, labels, classes (roles), selection, disabled state, gestures and bounds), focus groups and focused id, and every pixel.

func (*Harness) Tab

func (h *Harness) Tab(back bool)

Tab moves focus forward (or backward with back=true).

func (*Harness) TabUnreachable

func (h *Harness) TabUnreachable() []string

TabUnreachable visits the enabled, named controls in the current frame and returns those Tab cannot reach. A control is one by its role. Call it on a stable screen with no popup opening during traversal. It leaves focus at the final Tab stop.

func (*Harness) Texts

func (h *Harness) Texts() []string

Texts returns every label on screen, in draw order.

func (*Harness) TextsIn

func (h *Harness) TextsIn(id string) []string

TextsIn returns the labels whose origin lies inside the widget tagged id. A label's semantic bounds are the constraints it was laid out in, often larger than its glyphs and its container, so containment would miss them.

func (*Harness) Type

func (h *Harness) Type(s string)

Type inserts text into the focused editor, replacing its selection.

func (*Harness) Wait

func (h *Harness) Wait(d time.Duration)

Wait advances the virtual clock by d and settles: use it for hover delays (tooltips) or to step a continuous animation.

type Problem

type Problem struct {
	Kind   ProblemKind     // what kind of finding this is
	ID     string          // the widget's id, when it has one
	Bounds image.Rectangle // the widget's bounds in pixels, when known
	Msg    string          // what is wrong, for a human
}

Problem is one audit or strict-mode finding.

func (Problem) String

func (p Problem) String() string

String formats p as "kind id at bounds: msg", leaving out what is unknown.

type ProblemKind

type ProblemKind string

ProblemKind names the rule a Problem breaks. Its value is the short name used in failure messages.

const (
	// ProblemStaleFrame means a frame drawn with no new input differs from
	// the settled one, so the settled frame showed stale state.
	ProblemStaleFrame ProblemKind = "stale-frame"
	// ProblemNoSettle means the UI kept requesting immediate redraws.
	ProblemNoSettle ProblemKind = "no-settle"
)

Strict-mode kinds, found while the harness settles after input.

const (
	ProblemUnlabeledClickable ProblemKind = "unlabeled-clickable"
	ProblemTinyTarget         ProblemKind = "tiny-target"
	ProblemOccluded           ProblemKind = "occluded"
	ProblemDuplicateID        ProblemKind = "duplicate-id"
	ProblemMissingGlyph       ProblemKind = "missing-glyph"
	ProblemLowContrast        ProblemKind = "low-contrast"
)

Audit kinds, found by Audit in the current frame; Audit describes each.

type TB

type TB interface {
	Helper()
	Name() string
	Error(args ...any)
	Errorf(format string, args ...any)
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Skip(args ...any)
	Cleanup(func())
}

TB is the subset of testing.TB the harness uses. Declaring it here keeps package testing out of binaries that use New for screenshots (-shot), and lets tests pass their own implementation.

type TextContrast

type TextContrast struct {
	Text    string          // the label's text
	Bounds  image.Rectangle // the label's bounds in pixels
	Fg, Bg  color.NRGBA     // the measured text and background colours
	Ratio   float64         // WCAG contrast ratio, 1..21
	LargePx int             // visible label-box height in px, for the large-text threshold
}

TextContrast is one label's measured contrast.

Directories

Path Synopsis
Package conform is the conformance suite every interactive giokit control must pass.
Package conform is the conformance suite every interactive giokit control must pass.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL