Testing Widgets

A widget renders to a canvas and handles keys and mouse events through plain method calls, so a test needs no terminal. The urwid.testing module collects the helpers such tests keep rewriting. It is not imported by urwid, so the examples below start with:

from urwid.testing import (
    ScriptedScreen,
    VirtualClockEventLoop,
    attrs_for_text,
    check_sizing,
    press,
    render_runs,
    render_text,
)

Every check raises AssertionError with a message that names the call and the mismatch, and the module imports no test framework, so the helpers work with unittest, pytest or any other runner.

Rendering

render_text() renders a widget and returns its rows as text, and render_runs() returns each row as (attr, text) runs:

>>> from urwid import Text
>>> render_text(Text("ab cd"), (3,))
['ab ', 'cd ']
>>> render_runs(Text([("bold", "Hi"), "!"]), (3,))
[[('bold', 'Hi'), (None, '!')]]

attrs_for_text() returns the attributes of the runs that contain a text, to check how one label is drawn without spelling out the whole row:

>>> attrs_for_text(Text([("bold", "Hi"), "!"]), (3,), "Hi")
frozenset({'bold'})

resolve_attr() and resolve_runs() show the colors a screen with a given palette draws those attributes with.

Sizing checks

check_sizing() renders a widget at the degenerate and full sizes of each of its sizing modes, with focus off and on, and checks that the canvas has the size the widget promised and a cursor inside it:

>>> from urwid import Pile
>>> check_sizing(Pile([Text("x")]))

The checks empty the canvas cache before every case, so they belong in tests, not in a running application.

Input

press() sends keys and returns the ones the widget did not handle; click() sends one mouse event with named arguments:

>>> from urwid import Edit
>>> press(Edit("> "), (10,), "a", "b", "esc")
['esc']

Whole applications

ScriptedScreen stands in for the terminal of a MainLoop. It returns a fixed screen size, feeds scripted batches of input, stops the loop once they are used up, and records every distinct frame drawn:

>>> from urwid import Filler, MainLoop
>>> screen = ScriptedScreen(size=(6, 1), inputs=[["a", "b"], ["backspace"]])
>>> MainLoop(Filler(Edit("> ")), screen=screen).run()
>>> screen.last_text
['> a   ']

Alarms

VirtualClockEventLoop runs the alarms of a MainLoop on a clock of its own. advance() moves that clock ahead and fires every alarm that comes due on the way, so a widget that expires, blinks or polls is tested without waiting for it:

>>> from urwid import Notifications, SolidFill
>>> event_loop = VirtualClockEventLoop()
>>> loop = MainLoop(SolidFill(), screen=ScriptedScreen(), event_loop=event_loop)
>>> notifications = Notifications(loop=loop, timeout=5)
>>> _ = notifications.notify("saved")
>>> event_loop.advance(5)
>>> notifications.notifications
()

When a test needs the state after everything an application has scheduled, rather than at a chosen time, run_until_idle() fires the alarms until none is pending and returns with the clock at the last one. Its pause argument watches the files for that many seconds of real time before each jump of the clock, so a worker thread polled by an alarm can hand back its result through call_from_thread().

call_from_thread() needs a started loop, and a scripted screen ends a started loop once its input is used up. ScriptedScreen(inputs=None) is unscripted: it feeds no input and never ends the loop, so a loop started with start() keeps serving alarms, watched files and calls from other threads under run_until_idle(), while the screen records the frames drawn:

>>> import threading
>>> event_loop = VirtualClockEventLoop()
>>> text = Text("")
>>> screen = ScriptedScreen(size=(5, 1), inputs=None)
>>> loop = MainLoop(Filler(text), screen=screen, event_loop=event_loop)
>>> with loop.start():
...     worker = threading.Thread(target=loop.call_from_thread, args=(text.set_text, "done"))
...     worker.start()
...     worker.join()
...     _ = loop.set_alarm_in(1, lambda *_: text.set_text("later"))
...     event_loop.run_until_idle(pause=0.01)
>>> [frame.decoded_text for frame in screen.canvases]
[('done ',), ('later',)]

The clock is the loop’s own: a widget that reads time.monotonic() itself, such as Spinner choosing its frame, does not see it move.

To keep the frames as HTML for documentation instead, use urwid.display.html_fragment.HtmlGenerator.