test(core): add bootloader emulator tests [no changelog]
What changed, and why it matters
This commit only adds new automated test code for the Trezor bootloader emulator. It introduces a test suite, supporting fixtures, documentation, and Makefile targets to run bootloader tests. There is no change to firmware, bootloader, or production code, and no security fix or vulnerability is present in the diff.
No security action required. Treat as a normal test-infrastructure addition; review for test correctness and CI integration only.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit adds a new tests/bootloader_tests/ suite with a conftest.py fixture (BootloaderRunner) that launches the bootloader emulator per test, drives it via debug link and wire messages, records UI frames, and inspects the resulting ExitRecord. It includes one initial test (test_host_wipe_empty_device) that exercises a host-initiated wipe of an empty device. Makefile targets (test_emu_bootloader, test_emu_bootloader_ui) and documentation are added. A small refactor in tests/ui_tests/__init__.py extracts record_result() so bootloader tests can reuse the UI result hashing logic. No runtime product code is modified.
Changed components
tests/bootloader_tests/conftest.pytests/bootloader_tests/test_wipe_device.pytests/ui_tests/__init__.pycore/Makefiledocs/tests/bootloader-tests.mddocs/tests/index.mddocs/SUMMARY.mdInspect captured patch +338 / −2
### core/Makefile
@@ -9,7 +9,7 @@
test_emu_persistence test_emu_persistence_ui test_emu_upgrade \
test_emu_ui test_emu_ui_multicore test_emu_ui_record test_emu_ui_record_multicore \
test_emu_clear_signing_ui test_emu_clear_signing_ui_record \
- test_emu_prodtest \
+ test_emu_prodtest test_emu_bootloader test_emu_bootloader_ui \
pylint mypy typecheck pyright clippy \
audit_rust vet_rust \
templates templates_check translations translations_check \
@@ -219,6 +219,13 @@ test_emu_clear_signing_ui_record: ## record the screens of all clear-signing reg
test_emu_prodtest: ## run prodtest device tests
$(PRODTEST_EMU) --headless -c $(PYTEST) $(TESTPATH)/prodtest_tests $(TESTOPTS)
+test_emu_bootloader: ## run bootloader emulator tests
+ TREZOR_PYTEST_LOGS_DIR=$(TESTPATH) $(PYTEST) $(TESTPATH)/bootloader_tests $(TESTOPTS)
+
+test_emu_bootloader_ui: ## run bootloader emulator tests with UI recording
+ TREZOR_PYTEST_LOGS_DIR=$(TESTPATH) $(PYTEST) $(TESTPATH)/bootloader_tests $(TESTOPTS) \
+ --ui=test --ui-check-missing --do-master-diff
+
pylint: ## run pylint on application sources and tests
pylint -E $(shell find src tests -name *.py)
### docs/SUMMARY.md
@@ -54,6 +54,7 @@
- [UI Tests](tests/ui-tests.md)
- [Click Tests](tests/click-tests.md)
- [Clear-signing Tests](tests/clear-signing-tests.md)
+ - [Bootloader Tests](tests/bootloader-tests.md)
- [Miscellaneous](misc/index.md)
- [Affected third-parties](misc/third-parties.md)
- [Changelog](misc/changelog.md)
### docs/tests/bootloader-tests.md
@@ -0,0 +1,54 @@
+# Bootloader tests
+
+Bootloader tests run the bootloader emulator, one or more runs per test, and
+drive it the way the click tests drive firmware: input over the debug link, host
+messages over the wire port, screenshots hashed against
+`tests/ui_tests/fixtures.json`.
+
+Unlike the firmware emulator, a bootloader run is expected to end on its own. A
+test starts the emulator with explicit startup parameters (a firmware image to
+preload, a boot command, a record directory), interacts with it, and then reads
+how the run ended: the process exit code tells the kind of exit, the file
+`trezor.bootargs` in the profile directory tells which boot command the
+bootloader left for the next boot, and the flash file tells whether storage
+survived. See `trezorlib._internal.bootloader_emulator` for the wrapper and
+`trezorlib._internal.bootargs` for the decoders.
+
+## Running
+
+Build a debuglink bootloader emulator with the development keys, then run the
+suite:
+
+```sh
+make -C core build_bootloader_emu PYOPT=0 BOOTLOADER_DEVEL=1 TREZOR_MODEL=T3T1
+make -C core test_emu_bootloader # plain
+make -C core test_emu_bootloader_ui # with UI fixtures
+```
+
+The binary is taken from `core/build/artifacts/latest/bootloader-emu`, or from
+the path in `TREZOR_BOOTLOADER_EMU`.
+
+To record fixtures for a model, run with `--ui=record`:
+
+```sh
+cd tests
+TREZOR_BOOTLOADER_EMU=../core/build/artifacts/T3T1/bootloader-emu pytest bootloader_tests --ui=record
+```
+
+With `--ui` the screens are recorded from the first frame of every run, so the
+boot screens are part of the fixtures.
+
+## Writing a test
+
+Use the `bootloader` fixture. `bootloader.start(BootloaderStartup(...))` starts a
+run and returns the emulator; its `ctx` carries the debug link (`debug`) and
+the wire channel (`wire`). A wire call that needs an on-screen confirmation is
+made with `wire.call_in_background()` while the test clicks through the screen.
+Finish with `bootloader.wait_exit()` for a run that ends by itself, or
+`bootloader.abort()` for a screen that waits for the user to reconnect the
+device. Both return an `ExitRecord` with `kind`, `bootargs` and
+`storage_erased`.
+
+The bootloader emulator prints its flash layout with `-p` and takes a boot
+command from a file with `-B`; `BootArgs.wipe(...)`, `BootArgs.show_rsod(...)`
+and friends build such files.
### docs/tests/index.md
@@ -45,6 +45,12 @@ See the [upgrade-tests.md](upgrade-tests.md) for instructions how to run it.
These tests test the Persistence mode, which is currently used in the device recovery. These tests launch the emulator themselves and they are capable of restarting or stopping it simulating user's plugging in or plugging out the device.
+## Bootloader tests
+
+These tests run the bootloader emulator, one or more runs per test, with explicit startup parameters, and check both the screens and how the run ended. They are located in `bootloader_tests/` and have their own `conftest.py`.
+
+See [bootloader-tests.md](bootloader-tests.md) for instructions how to run it.
+
## Prodtest tests
These tests test the production test firmware (prodtest) CLI against the prodtest emulator. The tests are located in `prodtest_tests/` and have their own `conftest.py`, isolated from the device-test suite.
### tests/bootloader_tests/__init__.py
[binary or diff unavailable]
### tests/bootloader_tests/conftest.py
@@ -0,0 +1,180 @@
+# This file is part of the Trezor project.
+#
+# Copyright (C) 2012-2026 SatoshiLabs and contributors
+#
+# This library is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# as published by the Free Software Foundation.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the License along with this library.
+# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
+
+"""Bootloader emulator tests.
+
+Every test owns its emulator runs: it starts the bootloader with explicit
+startup parameters, drives it, and reads how the run ended. The emulator
+binary comes from ``TREZOR_BOOTLOADER_EMU`` or the latest ``xtask`` build.
+
+With ``--ui`` the screens are recorded from the first frame of every run
+(``-r``) and hashed with the usual UI-test machinery; a test that runs the
+emulator more than once gets all its runs in one recording.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import shutil
+import tempfile
+import typing as t
+from pathlib import Path
+
+import pytest
+import xdist
+
+from trezorlib._internal.bootloader_emulator import (
+ BootloaderEmulator,
+ BootloaderStartup,
+ ExitRecord,
+ find_bootloader_emulator,
+)
+
+from .. import ui_tests
+from ..emulators import _get_port, delete_profile, get_logfile
+from ..ui_tests.common import TestCase
+
+LOG = logging.getLogger(__name__)
+
+
+def _get_worker_id(request: pytest.FixtureRequest) -> int:
+ worker_id = xdist.get_xdist_worker_id(request)
+ if worker_id == "master":
+ return 0
+ assert worker_id.startswith("gw")
+ return 1 + int(worker_id[2:])
+
+
+def _executable() -> Path:
+ path = os.environ.get("TREZOR_BOOTLOADER_EMU")
+ if path:
+ return Path(path)
+ return find_bootloader_emulator()
+
+
+class BootloaderRunner:
+ """Starts bootloader emulator runs for one test and collects their exits."""
+
+ def __init__(
+ self,
+ request: pytest.FixtureRequest,
+ executable: Path,
+ port: int,
+ profile_dir: Path,
+ logfile: Path | None,
+ ) -> None:
+ self.request = request
+ self.executable = executable
+ self.port = port
+ self.profile_dir = profile_dir
+ self.logfile = logfile
+ self.emulator: BootloaderEmulator | None = None
+ self.exits: list[ExitRecord] = []
+ self._runs = 0
+ self._testcase: TestCase | None = None
+ self._record_dir: Path | None = None
+
+ @property
+ def recording(self) -> bool:
+ return bool(self.request.config.getoption("ui"))
+
+ def _prepare_recording(self, emu: BootloaderEmulator) -> Path:
+ # TestCase needs the model and language, which only a running
+ # emulator reports; take them from a throwaway properties query.
+ model = emu.properties()["model"]
+ name, group = ui_tests.common._get_test_name_and_group(self.request.node.nodeid)
+ self._testcase = TestCase(model=model, group=group, name=name, language="en")
+ self._testcase.dir.mkdir(exist_ok=True, parents=True)
+ shutil.rmtree(self._testcase.actual_dir, ignore_errors=True)
+ self._testcase.actual_dir.mkdir()
+ return self._testcase.actual_dir
+
+ def start(self, startup: BootloaderStartup | None = None) -> BootloaderEmulator:
+ """Start a run; a previous run of this test must have ended first."""
+ if self.emulator is not None and self.emulator.process is not None:
+ raise RuntimeError(
+ "the previous run is still running; wait_exit() or stop() it"
+ )
+ startup = startup or BootloaderStartup()
+ emu = BootloaderEmulator(
+ self.executable,
+ self.profile_dir,
+ startup=startup,
+ port=self.port,
+ logfile=self.logfile,
+ )
+ if self.recording:
+ if self._record_dir is None:
+ self._record_dir = self._prepare_recording(emu)
+ startup.record_dir = self._record_dir
+ emu.start()
+ self.emulator = emu
+ return emu
+
+ def wait_exit(self, timeout: float | None = 60) -> ExitRecord:
+ """Wait for the current run to end and record how."""
+ assert self.emulator is not None, "no run started"
+ record = self.emulator.wait_exit(timeout)
+ self.exits.append(record)
+ self._finish_run()
+ return record
+
+ def abort(self) -> ExitRecord:
+ """Stop a run that will not end on its own and record its state."""
+ assert self.emulator is not None, "no run started"
+ record = self.emulator.abort()
+ self.exits.append(record)
+ self._finish_run()
+ return record
+
+ def _finish_run(self) -> None:
+ # Every run records its frames with the prefix of a first refresh;
+ # move them to the run's own index before the next run reuses the
+ # prefix, so the frames survive and sort in run order.
+ self._runs += 1
+ if self._record_dir is not None:
+ for png in self._record_dir.glob("refresh00-*.png"):
+ png.rename(
+ png.with_name(
+ f"refresh{self._runs:02d}-" + png.name[len("refresh00-") :]
+ )
+ )
+
+ def close(self) -> None:
+ if self.emulator is not None and self.emulator.process is not None:
+ self.emulator.stop()
+ self._finish_run()
+ self.emulator = None
+ if self._testcase is not None:
+ ui_tests.record_result(self._testcase, self.request)
+
+
+@pytest.fixture
+def bootloader(request: pytest.FixtureRequest) -> t.Iterator[BootloaderRunner]:
+ worker_id = _get_worker_id(request)
+ executable = _executable()
+ logfile = get_logfile(f"trezor-bootloader-{worker_id}.log")
+ with tempfile.TemporaryDirectory(
+ prefix="trezor-bootloader-", delete=delete_profile()
+ ) as profile_dir:
+ runner = BootloaderRunner(
+ request, executable, _get_port(worker_id), Path(profile_dir), logfile
+ )
+ try:
+ yield runner
+ finally:
+ runner.close()
### tests/bootloader_tests/test_wipe_device.py
@@ -0,0 +1,83 @@
+# This file is part of the Trezor project.
+#
+# Copyright (C) 2012-2026 SatoshiLabs and contributors
+#
+# This library is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# as published by the Free Software Foundation.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the License along with this library.
+# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
+
+from __future__ import annotations
+
+import subprocess
+import typing as t
+
+from trezorlib import messages
+from trezorlib._internal.bootargs import BootCommand
+from trezorlib._internal.bootloader_emulator import BootloaderStartup, ExitKind
+from trezorlib.debuglink import LayoutType
+from trezorlib.messages import DebugWaitType
+
+if t.TYPE_CHECKING:
+ from .conftest import BootloaderRunner
+
+
+def confirm_wipe(ctx) -> None:
+ """Press the confirming button of the wipe-confirmation screen."""
+ layout = ctx.layout_type
+ if layout in (LayoutType.Bolt, LayoutType.Delizia):
+ ctx.debug.click((180, 212))
+ elif layout is LayoutType.Eckhart:
+ ctx.debug.click((285, 475))
+ elif layout is LayoutType.Caesar:
+ ctx.debug.press_right()
+ else:
+ raise NotImplementedError(layout)
+
+
+def test_host_wipe_empty_device(bootloader: "BootloaderRunner") -> None:
+ """An empty device wipes its storage on the host's request."""
+ emu = bootloader.start(BootloaderStartup())
+ ctx = emu.ctx
+ assert ctx.features.bootloader_mode
+ assert not ctx.features.firmware_present
+
+ # the welcome screen listens on the wire port; the reply comes after the
+ # confirmation on screen
+ with ctx.debug.wait_for_layout_change():
+ reply = ctx.wire.call_in_background(messages.WipeDevice(), timeout=60)
+ confirm_wipe(ctx)
+ assert isinstance(reply.result(timeout=60), messages.Success)
+
+ # Success is sent 100 ms before the success screen is drawn; without
+ # layout tokens the test cannot wait for that screen by name
+ ctx.debug.state(DebugWaitType.IMMEDIATE)
+
+ if ctx.layout_type is LayoutType.Eckhart:
+ # the success screen offers a restart button; a tap that lands on
+ # the progress screen before it is ignored, so tap until the run ends
+ record = None
+ for _ in range(10):
+ ctx.debug.click((190, 475))
+ try:
+ record = bootloader.wait_exit(timeout=2)
+ break
+ except subprocess.TimeoutExpired:
+ continue
+ assert record is not None, "the restart button did not end the run"
+ assert record.kind is ExitKind.REBOOT
+ assert record.bootargs is not None
+ assert record.bootargs.command == BootCommand.REBOOT
+ else:
+ # the success screen asks the user to reconnect the device, which
+ # nothing on the emulator can do
+ record = bootloader.abort()
+ assert record.kind is ExitKind.QUIT
+ assert record.storage_erased is True
### tests/ui_tests/__init__.py
@@ -89,8 +89,13 @@ def screen_recording(
client.sync_responses()
client.debug.stop_recording()
+ record_result(testcase, request)
+
+
+def record_result(testcase: TestCase, request: pytest.FixtureRequest) -> None:
+ """Hash the screens recorded for `testcase` and file the result."""
result = testcase.build_result(request)
- if test_ui == "record":
+ if request.config.getoption("ui") == "record":
_process_recorded(result)
else:
_process_tested(result, request.node)Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.