testenv

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 25 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 testenv provides an ergonomic testing environment for Kite components. It includes a headless mock backend, event dispatchers, and fluent assertion helpers to verify DOM state, layout fragments, and rendered output.

Use New(t, width, height) to create an environment, and then use the provided helpers like Mount, Flush, and various assertion types to test UI components in isolation.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ByID

func ByID[T dom.Node](tb testing.TB, env *Environment, id string) T

ByID looks up the element with the given ID in env and returns it typed as T. It calls tb.Fatalf with a diagnostic message if env is nil, no node matches id, or the matched node does not satisfy T.

func Eventually

func Eventually(t *testing.T, predicate func() bool, timeout time.Duration, pollInterval ...time.Duration)

Eventually polls the given predicate function until it returns true or the timeout is reached. If the timeout is reached, the test fails with a description.

Types

type CellAssertion

type CellAssertion struct {
	// contains filtered or unexported fields
}

CellAssertion scopes assertions to a specific cell coordinate.

func (*CellAssertion) ToHaveAttribute

func (c *CellAssertion) ToHaveAttribute(attr backend.CellStyle) *ScreenAssertion

ToHaveAttribute asserts that the cell has the given attribute.

func (*CellAssertion) ToHaveContent

func (c *CellAssertion) ToHaveContent(expected string) *ScreenAssertion

ToHaveContent checks the text/rune inside the cell and returns to the ScreenAssertion for chaining.

func (*CellAssertion) ToNotHaveAttribute

func (c *CellAssertion) ToNotHaveAttribute(attr backend.CellStyle) *ScreenAssertion

ToNotHaveAttribute asserts that the cell does NOT have the given attribute.

type ColumnAssertion

type ColumnAssertion struct {
	// contains filtered or unexported fields
}

ColumnAssertion provides fluent assertions for a single table column.

func (*ColumnAssertion) ToHaveEqualWidth

func (c *ColumnAssertion) ToHaveEqualWidth(msgs ...any) *ColumnAssertion

ToHaveEqualWidth asserts that all collected cell widths are equal.

type ElementAssertion

type ElementAssertion struct {
	// contains filtered or unexported fields
}

ElementAssertion wraps a node and the testing context for fluent assertions.

func Expect

func Expect(t *testing.T, node dom.Node) *ElementAssertion

Expect is a convenience alias for NewElementAssertion to provide a BDD-style entry point for test assertions.

func NewElementAssertion

func NewElementAssertion(t *testing.T, node dom.Node) *ElementAssertion

NewElementAssertion creates a new assertion helper for the given node.

func (*ElementAssertion) CellsInColumn

func (a *ElementAssertion) CellsInColumn(col int) *ColumnAssertion

CellsInColumn collects the physical widths of cells in the given column index across all rows in the table's fragment and returns a ColumnAssertion for further checks (e.g. ToHaveEqualWidth).

func (*ElementAssertion) ExpectHardwareCursorVisible

func (a *ElementAssertion) ExpectHardwareCursorVisible(env *Environment, msgs ...any) *ElementAssertion

ExpectHardwareCursorVisible asserts that the backend's hardware cursor is visible.

func (*ElementAssertion) ExpectHardwareCursorY

func (a *ElementAssertion) ExpectHardwareCursorY(env *Environment, want int, msgs ...any) *ElementAssertion

ExpectHardwareCursorY asserts the Y position of the backend cursor.

func (*ElementAssertion) ToBeChecked

func (a *ElementAssertion) ToBeChecked(expected bool, msgs ...any) *ElementAssertion

ToBeChecked asserts that the node (or its underlying unwrapped node) is a Checkbox or Radio element and matches the expected checked state.

func (*ElementAssertion) ToBeDisabled

func (a *ElementAssertion) ToBeDisabled(expected bool, msgs ...any) *ElementAssertion

ToBeDisabled asserts that the node (or its underlying unwrapped node) is a form control or interactive element and matches the expected disabled state.

func (*ElementAssertion) ToHaveCellContentInFrame

func (a *ElementAssertion) ToHaveCellContentInFrame(env *Environment, expected string, msgs ...any) *ElementAssertion

ToHaveCellContentInFrame scans the last painted framebuffer for a cell whose content equals the expected string. Useful for asserting border junctions and other painted characters.

func (*ElementAssertion) ToHaveChildCount

func (a *ElementAssertion) ToHaveChildCount(expected int, msgs ...any) *ElementAssertion

ToHaveChildCount asserts that the node has exactly expected direct children.

func (*ElementAssertion) ToHaveChildrenText

func (a *ElementAssertion) ToHaveChildrenText(expected []string, msgs ...any) *ElementAssertion

ToHaveChildrenText asserts that the node's direct children have the given text contents in document order.

func (*ElementAssertion) ToHaveClass

func (a *ElementAssertion) ToHaveClass(expected string, msgs ...any) *ElementAssertion

ToHaveClass asserts that the node is a dom.Element (or its underlying unwrapped node) and has the expected Class.

func (*ElementAssertion) ToHaveCursorAt

func (a *ElementAssertion) ToHaveCursorAt(x, y int, msgs ...any) *ElementAssertion

ToHaveCursorAt specifically tests components that implement a cursor state.

func (*ElementAssertion) ToHaveFocus

func (a *ElementAssertion) ToHaveFocus(env *Environment, msgs ...any) *ElementAssertion

ToHaveFocus asserts that this node is the currently focused node in env.

func (*ElementAssertion) ToHaveFragmentHeight

func (a *ElementAssertion) ToHaveFragmentHeight(expected int, msgs ...any) *ElementAssertion

ToHaveFragmentHeight asserts that the node's render fragment has the expected height in layout units (cells/rows). Useful for verifying that elements respect their configured height and do not overflow.

func (*ElementAssertion) ToHaveID

func (a *ElementAssertion) ToHaveID(expected string, msgs ...any) *ElementAssertion

ToHaveID asserts that the node is a dom.Element (or its underlying unwrapped node) and has the expected ID.

func (*ElementAssertion) ToHaveScroll

func (a *ElementAssertion) ToHaveScroll(x, y int, msgs ...any) *ElementAssertion

ToHaveScroll asserts that the element reports the given scroll offsets.

func (*ElementAssertion) ToHaveTableStructure

func (a *ElementAssertion) ToHaveTableStructure(expected []string, msgs ...any) *ElementAssertion

ToHaveTableStructure verifies that the table's section fragments appear in the specified order (e.g. "thead", "tbody", "tfoot"). It returns the same ElementAssertion to allow chaining further table-related checks.

func (*ElementAssertion) ToHaveTextContent

func (a *ElementAssertion) ToHaveTextContent(expected string, msgs ...any) *ElementAssertion

ToHaveTextContent asserts that the node's TextContent() equals the expected string.

func (*ElementAssertion) ToHaveValue

func (a *ElementAssertion) ToHaveValue(expected any, msgs ...any) *ElementAssertion

ToHaveValue asserts that the node is a FormControl (or its underlying unwrapped node) and its Value() equals the expected value.

func (*ElementAssertion) ToNotHaveFocus

func (a *ElementAssertion) ToNotHaveFocus(env *Environment, msgs ...any) *ElementAssertion

ToNotHaveFocus asserts that this node is not the currently focused node.

type Environment

type Environment struct {
	Engine  *engine.Engine
	Backend *mock.Backend
	// contains filtered or unexported fields
}

Environment provides ergonomic tools for testing Kite components headless.

func New

func New(t testing.TB, width, height int, opts ...Option) *Environment

New creates a new test environment bound to testing.TB. It initializes a mock backend and engine of the given dimensions, and automatically registers teardown via t.Cleanup when t is non-nil.

Example
package main

import (
	"fmt"

	"github.com/masterkeysrd/kite/element"
	"github.com/masterkeysrd/kite/testenv"
)

func main() {
	env := testenv.New(nil, 24, 3)
	defer env.Close()

	checkbox := element.Checkbox(false)
	env.Mount(element.Box(checkbox, "Notify me"))
	env.Flush()

	env.ClickElement(checkbox)
	env.Flush()
	fmt.Println("notifications enabled:", checkbox.Checked())
}
Output:
notifications enabled: true

func (*Environment) Cleanup

func (e *Environment) Cleanup(fn func())

Cleanup registers a function to be executed when the environment is torn down.

func (*Environment) Click

func (e *Environment) Click(x, y int)

Click simulates a mouse click at (x, y).

func (*Environment) ClickByID

func (e *Environment) ClickByID(tb testing.TB, id string)

ClickByID resolves the element with id and clicks it via ClickElement, failing the test if no element with id exists.

func (*Environment) ClickByText

func (e *Environment) ClickByText(tb testing.TB, text string)

ClickByText resolves the element matching text via GetByText and clicks it via ClickElement.

func (*Environment) ClickElement

func (e *Environment) ClickElement(el dom.Element)

ClickElement computes the center coordinates of el's bounding rect, sends a left mouse click there, and flushes a frame.

func (*Environment) Close

func (e *Environment) Close()

Close is an alias for Teardown.

func (*Environment) CurrentFocus

func (e *Environment) CurrentFocus() dom.Node

CurrentFocus returns the logical node that currently holds focus, or nil if no node is focused.

func (*Environment) DispatchKey

func (e *Environment) DispatchKey(target event.EventTarget, k key.Key)

DispatchKey sends a key down event to the target EventTarget by building the ancestor path (root -> target) and dispatching through the event system. Useful for tests to simulate keyboard input against nodes.

func (*Environment) Document

func (e *Environment) Document() dom.Document

Document returns the logical document root.

func (*Environment) DoubleClick

func (e *Environment) DoubleClick(x, y int)

DoubleClick simulates a double mouse click at (x, y).

func (*Environment) DragAndDrop

func (e *Environment) DragAndDrop(startX, startY, endX, endY int)

DragAndDrop simulates dragging from (startX, startY) to (endX, endY).

func (*Environment) DumpANSI

func (e *Environment) DumpANSI() string

DumpANSI translates the current FrameBuffer into a raw string of ANSI escape codes.

func (*Environment) DumpHTML

func (e *Environment) DumpHTML() string

DumpHTML translates the current FrameBuffer into a standalone HTML file.

func (*Environment) DumpText

func (e *Environment) DumpText() string

DumpText translates the current FrameBuffer into a plain text representation.

func (*Environment) FindByText

func (e *Environment) FindByText(ctx context.Context, text string) (dom.Element, error)

FindByText flushes and checks QueryByText immediately, then polls every 5ms (flushing before each check) until a matching element is found or ctx is done.

func (*Environment) Flush

func (e *Environment) Flush()

Flush blocks until the engine completes a frame and drains any follow-up pending tasks (such as passive effects queued during reconciliation), bounded by maxFlushPasses to prevent infinite loops.

func (*Environment) GetAllByText

func (e *Environment) GetAllByText(tb testing.TB, text string) []dom.Element

GetAllByText returns all deepest elements matching text, failing the test with a diagnostic screen dump if none matches.

func (*Environment) GetByText

func (e *Environment) GetByText(tb testing.TB, text string) dom.Element

GetByText returns the first element matching text, failing the test with a diagnostic screen dump if no element matches.

func (*Environment) GetByTextMatch

func (e *Environment) GetByTextMatch(tb testing.TB, re *regexp.Regexp) dom.Element

GetByTextMatch returns the first deepest element whose TextContent matches re, failing the test with a diagnostic screen dump if none matches.

func (*Environment) GetNodeByID

func (e *Environment) GetNodeByID(id string) dom.Element

GetNodeByID returns the element with the given ID from the logical DOM.

func (*Environment) HasFocus

func (e *Environment) HasFocus(n dom.Node) bool

HasFocus reports whether the given logical node currently has focus.

func (*Environment) HideOverlay

func (e *Environment) HideOverlay(el dom.Element)

HideOverlay removes el from the top layer.

func (*Environment) KeyPress

func (e *Environment) KeyPress(keyOrChar string, mods ...key.Mod)

KeyPress simulates a key press by string name (e.g. "left", "a") with optional modifiers.

func (*Environment) MatchGolden

func (e *Environment) MatchGolden(t *testing.T, filename string)

MatchGolden compares the current framebuffer against a stored snapshot.

func (*Environment) Mount

func (e *Environment) Mount(n dom.Node)

Mount appends n as the body of the document.

func (*Environment) MouseDown

func (e *Environment) MouseDown(x, y int, button event.MouseButton)

MouseDown simulates a mouse button press at (x, y).

func (*Environment) MouseMove

func (e *Environment) MouseMove(x, y int)

MouseMove simulates a mouse move to (x, y).

func (*Environment) MouseUp

func (e *Environment) MouseUp(x, y int, button event.MouseButton)

MouseUp simulates a mouse button release at (x, y).

func (*Environment) Overlays

func (e *Environment) Overlays() iter.Seq[dom.Element]

Overlays returns an iterator over all active overlays.

func (*Environment) Play

func (e *Environment) Play(actions ...string)

Play simulates a sequence of keyboard actions. Actions enclosed in brackets (e.g., "<Down>", "<Enter>", "<Ctrl+a>", "<Shift+Left>") are simulated as special keypresses with optional modifiers. All other actions are typed literally.

func (*Environment) QueryAllByText

func (e *Environment) QueryAllByText(text string) []dom.Element

QueryAllByText walks the logical DOM and active overlays in depth-first order, returning the deepest matching dom.Element nodes whose TextContent contains text (or equals "" when text == ""). Exact trimmed matches are ordered before substring matches.

func (*Environment) QueryAllByTextMatch

func (e *Environment) QueryAllByTextMatch(re *regexp.Regexp) []dom.Element

QueryAllByTextMatch walks the logical DOM and active overlays in depth-first order, returning the deepest matching dom.Element nodes whose TextContent matches re.

func (*Environment) QueryByText

func (e *Environment) QueryByText(text string) dom.Element

QueryByText returns the first element matching text, or nil if none matches.

func (*Environment) QueryByTextMatch

func (e *Environment) QueryByTextMatch(re *regexp.Regexp) dom.Element

QueryByTextMatch returns the first deepest element whose TextContent matches re, or nil if none matches.

func (*Environment) QueryOverlay

func (e *Environment) QueryOverlay(selector string) dom.Element

QueryOverlay returns the first element matching the selector in any active overlay.

func (*Environment) QuerySelector

func (e *Environment) QuerySelector(selector string) dom.Element

QuerySelector returns the first element matching the selector. Supports simple tag name ("div"), ID ("#id"), and class (".class") matching.

func (*Environment) RenderFrame

func (e *Environment) RenderFrame()

RenderFrame is an alias for Flush.

func (*Environment) RenderObject

func (e *Environment) RenderObject(n dom.Node) render.Object

RenderObject returns the render object for the given logical node.

func (*Environment) Resize

func (e *Environment) Resize(width, height int)

func (*Environment) ScrollTo

func (e *Environment) ScrollTo(el dom.Element, x, y int)

ScrollTo sets the scroll offset of an element.

func (*Environment) SendKey

func (e *Environment) SendKey(k key.Key)

SendKey simulates a key event.

func (*Environment) SetColorScheme

func (e *Environment) SetColorScheme(scheme style.ColorScheme)

func (*Environment) ShowOverlay

func (e *Environment) ShowOverlay(el dom.Element, zIndex int)

ShowOverlay adds el to the top layer at the specified z-index.

func (*Environment) Teardown

func (e *Environment) Teardown()

Teardown gracefully stops the engine and runs all registered cleanups.

func (*Environment) Type

func (e *Environment) Type(text string)

Type simulates typing the given text.

func (*Environment) Wheel

func (e *Environment) Wheel(x, y, dx, dy int)

Wheel simulates a mouse wheel event at (x, y).

type EventAssertion

type EventAssertion struct {
	// contains filtered or unexported fields
}

EventAssertion provides helpers for asserting that events fire on targets.

func ExpectEvent

func ExpectEvent(t *testing.T, target event.EventTarget, eventType event.EventType) *EventAssertion

ExpectEvent creates an assertion for event listeners.

func (*EventAssertion) ToFireWhen

func (ea *EventAssertion) ToFireWhen(action func())

ToFireWhen executes the action and asserts the event was received.

type EventSpy

type EventSpy struct {
	// contains filtered or unexported fields
}

EventSpy records occurrences of a specific event type on a target.

func SpyEvents

func SpyEvents(t *testing.T, target event.EventTarget, eventType event.EventType) *EventSpy

SpyEvents attaches a listener to target for the given eventType and returns an EventSpy.

func (*EventSpy) AssertFired

func (s *EventSpy) AssertFired(msgs ...any) *EventSpy

AssertFired asserts that the event was fired at least once.

func (*EventSpy) AssertFiredCount

func (s *EventSpy) AssertFiredCount(expected int, msgs ...any) *EventSpy

AssertFiredCount asserts that the event was fired exactly expected times.

func (*EventSpy) Count

func (s *EventSpy) Count() int

Count returns the number of events captured.

func (*EventSpy) Events

func (s *EventSpy) Events() []event.Event

Events returns the captured events.

type Option

type Option func(*envOptions)

Option configures an Environment created with New.

func WithBackend

func WithBackend(b *mock.Backend) Option

WithBackend specifies a custom mock backend.

func WithCaps

func WithCaps(caps backend.Caps) Option

WithCaps specifies simulated terminal capabilities for the mock backend.

func WithEngine

func WithEngine(eng *engine.Engine) Option

WithEngine specifies a custom pre-configured engine.

type RegionAssertion

type RegionAssertion struct {
	// contains filtered or unexported fields
}

RegionAssertion scopes assertions to a rectangular region on the framebuffer.

func (*RegionAssertion) ToHaveBackground

func (r *RegionAssertion) ToHaveBackground(expected color.Color) *ScreenAssertion

ToHaveBackground asserts that EVERY cell in the region has the specified background.

func (*RegionAssertion) ToHaveBackgroundCountGreaterThan

func (r *RegionAssertion) ToHaveBackgroundCountGreaterThan(expected color.Color, min int) *ScreenAssertion

ToHaveBackgroundCountGreaterThan asserts that the number of cells in the region carrying the specified background color is strictly greater than `min`.

func (*RegionAssertion) ToNotHaveBackground

func (r *RegionAssertion) ToNotHaveBackground(unexpected color.Color) *ScreenAssertion

ToNotHaveBackground asserts that NO cell in the region has the specified background.

type ScreenAssertion

type ScreenAssertion struct {
	// contains filtered or unexported fields
}

ScreenAssertion provides fluent assertions over a rendered framebuffer.

func ExpectScreen

func ExpectScreen(t *testing.T, env *Environment) *ScreenAssertion

ExpectScreen starts an assertion chain for the rendered framebuffer.

func (*ScreenAssertion) CellAt

func (s *ScreenAssertion) CellAt(x, y int) *CellAssertion

CellAt scopes the next assertions to a specific X,Y coordinate.

func (*ScreenAssertion) Lines

func (s *ScreenAssertion) Lines() []string

Lines returns the lines of the rendered framebuffer with trailing spaces trimmed on each line.

func (*ScreenAssertion) Region

func (s *ScreenAssertion) Region(x, y, w, h int) *RegionAssertion

Region is a convenience that accepts raw coordinates and size.

func (*ScreenAssertion) RegionRect

func (s *ScreenAssertion) RegionRect(r geom.Rect) *RegionAssertion

RegionRect scopes assertions to a geom.Rect region.

func (*ScreenAssertion) Text

func (s *ScreenAssertion) Text() string

Text returns the rendered framebuffer as newline-separated lines with trailing spaces trimmed on each line.

func (*ScreenAssertion) ToContainText

func (s *ScreenAssertion) ToContainText(expected string, msgs ...any) *ScreenAssertion

ToContainText asserts that the rendered screen text contains expected.

func (*ScreenAssertion) ToHaveLine

func (s *ScreenAssertion) ToHaveLine(row int, expected string, msgs ...any) *ScreenAssertion

ToHaveLine asserts that row exists in the rendered framebuffer and equals expected (ignoring trailing spaces).

func (*ScreenAssertion) ToNotContainText

func (s *ScreenAssertion) ToNotContainText(unexpected string, msgs ...any) *ScreenAssertion

ToNotContainText asserts that the rendered screen text does not contain unexpected.

Jump to

Keyboard shortcuts

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