Testing
wybthon.testing¶
testing
¶
Render components in plain CPython and query them like a user would.
wybthon.testing mounts views into an in-memory DOM through the real
reconciler, kernel protocol, scheduler, and event delegation. Nothing is
mocked: the commands a test applies are exactly the commands the browser
kernel applies.
from wybthon.testing import cleanup, fire, render
def test_counter():
screen = render(Counter(label="Clicks"))
fire.click(screen.get_by_role("button", name="+"))
assert screen.get_by_text("Clicks: 1")
cleanup()
Queries come in three forms, as in Testing Library:
get_by_*returns the single match and raises when there are none or several;query_by_*returns the match orNone;get_all_by_*returns every match (raising when there are none).
They search by visible text, ARIA role (with an optional accessible
name), label text, and data-testid. fire
dispatches events through Wybthon's delegated handlers and flushes the
resulting updates, so assertions see the settled DOM.
Use render as a context manager to unmount automatically, or call
cleanup at the end of each test (an
autouse pytest fixture is a convenient place).
Full-stack code tests the same way:
connect_servermakes the components a test renders call their server functions the way the browser does, through the wire protocol and the server's argument validation, in-process.Clientsends HTTP requests to an ASGI app (wybthon.asgi.create_app) without a network, for pages, form posts, and HTTP handlers.
Classes:
| Name | Description |
|---|---|
TestNode |
An in-memory DOM node: an element, a text node, or a comment. |
TestDocument |
An in-memory |
Screen |
A rendered view and the queries that find nodes in it. |
ClientResponse |
A response a |
Client |
Send requests to an ASGI app in-process; cookies persist between requests. |
Functions:
| Name | Description |
|---|---|
raise_unhandled |
Raise the errors rendered views logged that no |
render |
Mount |
cleanup |
Unmount every view rendered with |
reactive_scope |
Own test computations and dispose them deterministically at scope exit. |
tick |
Drain ready asyncio continuations and flush reactive work. |
wait_for |
Wait for an observable condition, raising TimeoutError on failure. |
connect_server |
Make server function calls inside the block cross the wire, as they would in the browser. |
Attributes:
| Name | Type | Description |
|---|---|---|
fire |
Dispatch events: |
fire
module-attribute
¶
Dispatch events: fire.click(node), fire.input(node, "text"), fire(node, "dblclick").
TestNode
¶
An in-memory DOM node: an element, a text node, or a comment.
It implements the subset of the DOM the kernel protocol uses, plus
the properties tests read (text_content, attributes, value,
checked).
Methods:
| Name | Description |
|---|---|
focus |
Make this node the document's active element (no events are dispatched). |
blur |
Clear the active element if it's this node. |
click |
Dispatch a click through Wybthon's delegated handlers (like |
Attributes:
| Name | Type | Description |
|---|---|---|
is_element |
bool
|
Whether this node is an element (not text or a comment). |
text_content |
str
|
The concatenated text of this node and its descendants (comments excluded). |
Screen
¶
A rendered view and the queries that find nodes in it.
Attributes:
| Name | Type | Description |
|---|---|---|
container |
The |
|
root |
The |
Methods:
| Name | Description |
|---|---|
unmount |
Dispose the view and release its container. |
html |
The container's inner HTML, without Wybthon's comment markers. |
text |
The container's text content, with whitespace collapsed. |
debug |
Print the rendered markup, for a look at what a failing query searched. |
get_by_text |
Return the one element whose text matches. |
query_by_text |
Return the element whose text matches, or |
get_all_by_text |
Return every element whose text matches. |
get_by_role |
Return the one element with this ARIA role (and accessible name). |
query_by_role |
Return the element with this role (and name), or |
get_all_by_role |
Return every element with this role (and name). |
get_by_label_text |
Return the one form control labelled by |
query_by_label_text |
Return the form control labelled by |
get_by_test_id |
Return the one element with |
query_by_test_id |
Return the element with this |
get_all_by_test_id |
Return every element with this |
unmount
¶
unmount(*, check: bool = True) -> None
Dispose the view and release its container.
Raises an error a rendered view logged that no Errored
boundary handled, unless check is false.
get_by_text
¶
Return the one element whose text matches.
query_by_text
¶
Return the element whose text matches, or None.
get_all_by_text
¶
Return every element whose text matches.
get_by_role
¶
Return the one element with this ARIA role (and accessible name).
query_by_role
¶
Return the element with this role (and name), or None.
get_all_by_role
¶
Return every element with this role (and name).
get_by_label_text
¶
Return the one form control labelled by text.
query_by_label_text
¶
Return the form control labelled by text, or None.
get_by_test_id
¶
Return the one element with data-testid equal to test_id.
query_by_test_id
¶
Return the element with this data-testid, or None.
ClientResponse
¶
A response a Client received.
Attributes:
| Name | Type | Description |
|---|---|---|
status |
The status code. |
|
headers |
Header values by lowercase name (repeated headers joined
with |
|
cookies |
Every |
|
body |
The body. |
Methods:
| Name | Description |
|---|---|
json |
The body parsed as JSON. |
Client
¶
Send requests to an ASGI app in-process; cookies persist between requests.
from wybthon.asgi import create_app
from wybthon.testing import Client
def test_home_page():
client = Client(create_app("tests/fixture_app"))
page = client.get("/")
assert page.status == 200 and "Todos" in page.text
Methods:
| Name | Description |
|---|---|
request_async |
Send a request from a running event loop. |
request |
Send a request and wait for the whole response. |
get |
|
post_form |
Post a form the way a browser without JavaScript does. |
request_async
async
¶
request_async(method: str, path: str, *, body: bytes = b'', headers: dict[str, str] | None = None) -> ClientResponse
Send a request from a running event loop.
request
¶
request(method: str, path: str, *, body: bytes = b'', headers: dict[str, str] | None = None) -> ClientResponse
Send a request and wait for the whole response.
raise_unhandled
¶
Raise the errors rendered views logged that no Errored boundary handled.
render, every fire call, and leaving a render block call this, so
a test fails on an error a component, binding, or effect raised instead
of passing against whatever the view managed to show. Several errors
are raised together as an ExceptionGroup.
render
¶
Mount view into a fresh in-memory container and flush it.
An error a component, binding, or effect raises that no
Errored boundary handles fails the test: it's
raised from render, from the fire call that caused it, or when the
with block ends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
view
|
Any
|
Anything |
required |
strict
|
bool
|
Pass |
True
|
Returns:
| Type | Description |
|---|---|
Screen
|
A |
cleanup
¶
cleanup(*, check: bool = False) -> None
Unmount every view rendered with render that's still mounted.
With check, then raise the errors the views logged that no boundary
handled, as the pytest plugin does after every test; otherwise they're
dropped.
reactive_scope
¶
Own test computations and dispose them deterministically at scope exit.
tick
async
¶
tick(rounds: int = 2) -> None
Drain ready asyncio continuations and flush reactive work.
wait_for
async
¶
Wait for an observable condition, raising TimeoutError on failure.
connect_server
¶
Make server function calls inside the block cross the wire, as they would in the browser.
With no app, each call is handled in-process by the server-side
handler: arguments are encoded, validated against the function's
annotations, and the result decoded, exactly as over HTTP. With an
ASGI app (such as wybthon.asgi.create_app(...)), each call is a
request to it.
What's in this module¶
wybthon.testing renders components in plain CPython, through the real
reconciler, kernel protocol, scheduler, and event delegation, into an
in-memory DOM. Nothing is mocked, so a passing test exercises the same
commands the browser kernel applies. The queries follow Testing
Library's conventions.
| Name | Description |
|---|---|
render |
render(view) -> Screen: mount a view (a VNode or a zero-arg callable) into a fresh in-memory document. |
Screen |
Queries plus html(), text(), and unmount(); also a context manager that unmounts on exit. |
fire |
Dispatch events through delegated handlers and flush: fire.click(node), fire.input(node, value), fire.change(node, value=None, checked=None), fire.submit(form), fire.key_down(node, key), fire.focus(node), fire.blur(node), or fire(node, "dblclick", **payload). |
cleanup |
Unmount everything render mounted; call it after each test, or from an autouse fixture. |
TestNode, TestDocument |
The in-memory DOM the screen renders into. |
reactive_scope, tick, wait_for |
Helpers for testing reactive code and async updates outside a component. |
| Query | Finds | Variants |
|---|---|---|
get_by_text(text, *, exact=True) |
Elements by visible text, or a compiled regex | query_by_text, get_all_by_text |
get_by_role(role, *, name=None) |
Elements by ARIA role and accessible name | query_by_role, get_all_by_role |
get_by_label_text(text) |
Form controls by their label | query_by_label_text |
get_by_test_id(test_id) |
Elements by data-testid |
query_by_test_id, get_all_by_test_id |
get_by_* raises unless exactly one element matches, query_by_*
returns the match or None, and get_all_by_* returns every match.
import pytest
from wybthon import component, create_signal, html
from wybthon.testing import cleanup, fire, render
@component
def Counter(label: str = "Count"):
count, set_count = create_signal(0)
def increment():
set_count(lambda n: n + 1)
return html(t"<div><p>{label}: {count()}</p><button onclick={increment}>+</button></div>")
@pytest.fixture(autouse=True)
def _cleanup():
yield
cleanup()
def test_counter():
screen = render(Counter(label="Clicks"))
fire.click(screen.get_by_role("button", name="+"))
assert screen.get_by_text("Clicks: 1")
assert screen.html() == "<div><p>Clicks: 1</p><button>+</button></div>"
Templates in test modules are compiled by Wybthon's pytest plugin, so
they behave exactly as they do in the application; see
Guides: Testing. For a script outside pytest,
use wyb run script.py.
See also¶
- Guides: Testing
- Kernel: the
PythonBackendthe screen renders through - Events: the delegated handlers
firedispatches to