### Install Documentation Dependencies Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/CONTRIBUTING Installs the necessary Python packages for building the project's documentation, including Sphinx and the espressif theme. ```bash #!/bin/bash pip install -r docs/requirements.txt ``` -------------------------------- ### Install Project Dependencies Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/CONTRIBUTING Installs project dependencies using pip and installs local subpackages in editable mode via a custom script. ```bash #!/bin/bash pip install -r requirements.txt bash foreach.sh install-editable ``` -------------------------------- ### Assigning Service-Specific Arguments in Multi-DUT Shell Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/concepts/key-concepts Illustrates how to provide vacant values for configuration options that are only applicable to specific DUTs in a multi-DUT setup. The example shows assigning `--qemu-cli-args` to the first DUT (using the `qemu` service) and `--port` to the second DUT (using the `serial` service) by using a vacant value (`|`) for the other DUT. ```shell pytest \ --embedded-services qemu|serial \ --count 2 \ --app-path | \ --qemu-cli-args "|" \ --port "|" ``` -------------------------------- ### Build Project Documentation Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/CONTRIBUTING Navigates to the docs directory and builds the HTML documentation using the 'make html' command. Assumes Sphinx and related dependencies are installed. ```bash #!/bin/bash cd docs make html ``` -------------------------------- ### Install Pre-commit Hooks Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/CONTRIBUTING Installs pre-commit and commit-msg hooks for code formatting and linter checks. Ensures code quality before commits. ```bash #!/bin/bash pre-commit install -t pre-commit -t commit-msg ``` -------------------------------- ### Wokwi Button Test Example (Python) Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/concepts/services A Python pytest example demonstrating how to interact with the Wokwi simulation environment. It uses the `dut` fixture for device communication and the `wokwi` fixture to control virtual components like buttons. The test simulates pressing a button and verifies the device's response. ```python import logging from pytest_embedded_wokwi import Wokwi from pytest_embedded import Dut def test_gpio(dut: Dut, wokwi: Wokwi): LOGGER = logging.getLogger(__name__) LOGGER.info("Waiting for Button test begin...") dut.expect_exact("Butston test") for i in range(3): LOGGER.info(f"Setting button pressed for {i + 1} seconds") wokwi.client.set_control("btn1", "pressed", 1) dut.expect_exact(f"Button pressed {i + 1} times") wokwi.client.set_control("btn1", "pressed", 0) ``` -------------------------------- ### Parametrizing Tests with Embedded Services and App Paths in Python Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/concepts/key-concepts.rst Illustrates how to use pytest's parametrize marker to run a single test function with multiple configurations of embedded services and application paths. This allows for efficient testing across different environments without duplicating test logic. The example shows how to set up different app_path values and asserts the target of the DUT. ```python @pytest.mark.parametrize( "embedded_services, app_path", [ ("idf", app_path_1), ("idf", app_path_2), ], indirect=True, ) def test_serial_tcp(dut): assert dut.app.target == "esp32" dut.expect("Restart now") ``` -------------------------------- ### pytest Markers and idf_parametrize Examples Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/usages/markers.rst Demonstrates the usage of pytest markers and the idf_parametrize decorator for complex test case generation and configuration, including combining environment markers and parameterizing targets and configurations. ```APIDOC ## Pytest Markers and idf_parametrize ### Description This section illustrates how to use `pytest.mark` and `idf_parametrize` to define and control test execution environments and parameters. ### Combining Markers Markers can be combined and must be placed in the last position. If some test cases do not have markers, you can skip their definition. **Example:** Tests can run on various runners using environment markers like `generic`, `sdcard`, and `usb_device`. ```python @pytest.mark.generic @idf_parametrize('target', soc_filtered_targets('SOC_ULP_SUPPORTED != 1'), indirect=['target']) @idf_parametrize('config', [ 'defaults' ], indirect=['config']) @idf_parametrize('target, markers', [ ('esp32', (pytest.mark.usb_device,)), ('esp32c3' ), ('esp32', (pytest.mark.sdcard,)) ], indirect=['target']) def test_console(dut: Dut, test_on: str) -> None: pass ``` **Resulting Parameters Matrix:** | Target | Markers | | ------- | --------------- | | esp32 | generic, usb_device | | esp32c3 | generic | | esp32 | generic, sdcard | ### Target with Config Parameterization **Example:** Parameterize tests with different targets and configurations. ```python @idf_parametrize('target, config', [ ('esp32', 'release'), ('esp32c3', 'default'), ('supported_target', 'psram') ], indirect=True) def test_st(dut: Dut) -> None: ... ``` **Resulting Parameters Matrix:** | Target | Config | | ------- | ------- | | esp32 | release | | esp32c3 | default | | esp32 | psram | | esp32c3 | psram | | esp32s3 | psram | ### Supported Target on Runners **Example:** Parameterize tests to run on specific runners with supported targets. ```python @idf_parametrize('target, markers', [ ('esp32', (pytest.mark.generic, )), ('esp32c3', (pytest.mark.sdcard, )), ('supported_target', (pytest.mark.usb_device, )) ], indirect=True) def test_st(dut: Dut) -> None: ... ``` **Resulting Parameters Matrix:** | Target | Markers | | ------- | --------- | | esp32 | generic | | esp32c3 | sdcard | | esp32 | usb_device | | esp32c3 | usb_device | | esp32s3 | usb_device | ### Runner for All Tests **Example:** Applying a global marker (`@pytest.mark.generic`) to all tests while parameterizing targets and configurations. ```python @pytest.mark.generic @idf_parametrize('target, config', [ ('esp32', 'release'), ('esp32c3', 'default'), ('supported_target', 'psram') ], indirect=True) def test_st(dut: Dut) -> None: ... ``` **Resulting Parameters Matrix:** | Target | Config | Markers | | ------- | ------- | ------- | | esp32 | release | generic | | esp32c3 | default | generic | | esp32 | psram | generic | | esp32c3 | psram | generic | | esp32s3 | psram | generic | ``` -------------------------------- ### Configuring Multi-DUTs with Mixed Service and Vacant Values in Shell Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/concepts/key-concepts.rst Demonstrates advanced multi-DUT configuration in pytest using shell commands. This example enables different services (qemu and serial) for two DUTs and shows how to provide specific arguments or values for each DUT individually, including using vacant values ('|') for configurations that don't apply to a particular DUT. ```shell pytest \ --embedded-services qemu|serial \ --count 2 \ --app-path | \ --qemu-cli-args "|" \ --port "|" ``` -------------------------------- ### Install pytest-embedded using pip Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/index Installs or upgrades the pytest-embedded package to the latest 2.x version using pip. It recommends using `~=2.0` to ensure compatibility with non-breaking changes and access to the latest features. ```bash pip install -U pytest-embedded~=2.0 ``` -------------------------------- ### Testing Multiple DUTs with Different Configurations in Python Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/concepts/key-concepts.rst Provides a Python test function demonstrating how to interact with multiple DUTs when they are enabled. The DUT fixtures become tuples, allowing access to individual DUT instances (e.g., dut[0] for the master, dut[1] for the slave). The example shows basic interaction by expecting specific output from each DUT. ```python def test(dut): master = dut[0] slave = dut[1] master.expect("sent") slave.expect("received") ``` -------------------------------- ### Enabling Multi-DUT Testing with Serial Service in Shell Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/concepts/key-concepts.rst Shows how to enable a multi-DUT testing environment using the pytest command line. This example configures two DUTs, each using the 'serial' service, and specifies different binary paths for the master and slave DUTs. It highlights the use of --count to define the number of DUTs and how app paths are separated by '|'. ```shell pytest \ --embedded-services serial|serial \ --count 2 \ --app-path | ``` -------------------------------- ### Example Prometheus Text Format Output Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/usages/help_functions.rst This is an example of the output format for logged metrics in the specified file. Each line represents a metric with its name, labels (key-value pairs in curly braces), and its numerical value. ```text boot_time{target="esp32",sdk="v5.1"} 123.45 ``` -------------------------------- ### QemuTarget Class for QEMU Target Configuration Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-qemu The QemuTarget class holds configuration specific to a QEMU target. It stores the default efuse data (`default_efuse`) and the strap mode configuration (`strap_mode`) for the target, allowing for customized QEMU environment setup. ```python class QemuTarget: def __init__(self, strap_mode: str, default_efuse: bytes): self._strap_mode = strap_mode self.default_efuse = default_efuse @property def strap_mode(self) -> str: # Get the strap mode configuration for the QEMU target. return self._strap_mode ``` -------------------------------- ### SerialDut Class Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-serial The SerialDut class provides an interface for interacting with DUTs connected via serial ports. It includes attributes for serial, openocd, gdb, and telnet instances, along with methods for setup and writing data. ```APIDOC ## Class: SerialDut ### Description Dut class for serial ports. ### Attributes - **serial** (Serial) - Serial instance. - **openocd** (OpenOcd) - OpenOcd instance, applied only when jtag service is activated. - **gdb** (Gdb) - Gdb instance, applied only when jtag service is activated. - **telnet** (Telnet) - Telnet instance, applied only when jtag service is activated. ### Methods - **setup_jtag()** - Sets up the JTAG interface. - **write(data: AnyStr)** - Writes data to the MessageQueue instance. ``` -------------------------------- ### Preview Documentation Locally Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/CONTRIBUTING Opens the generated HTML documentation in a web browser. Requires the browser executable (e.g., firefox) to be in the system's PATH. ```bash #!/bin/bash firefox _build/html/index.html ``` -------------------------------- ### pytest_embedded.plugin.qemu Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded Launches a QEMU subprocess for emulating embedded devices. ```APIDOC ## GET pytest_embedded.plugin.qemu ### Description A qemu subprocess that could read/redirect/write. ### Method GET ### Endpoint /pytest_embedded.plugin.qemu ### Parameters #### Path Parameters - **__fixture_classes_and_options** (ClassCliOptions_) - Required - Fixture classes and options for QEMU. - **_app_** (string) - Required - The application to run in QEMU. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **Qemu** (object | None) - The QEMU process object or None if QEMU is not available. #### Response Example ```json { "example": "qemu_process_object or null" } ``` ``` -------------------------------- ### Get All DUTs - Python Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded Retrieves a list of all Device Under Test (DUT) objects that have been created by the DutFactory. This method is useful for iterating through and managing multiple DUT instances within a test session. ```python def _get_all_duts() -> list[Dut]: """ Get all DUTs created by DutFactory. """ pass ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/CONTRIBUTING Creates a Python virtual environment named '.venv' and activates it. This isolates project dependencies. ```bash #!/bin/bash python -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Get Current UTC Time as String Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded The `utcnow_str` function returns the current Coordinated Universal Time (UTC) as a formatted string. This is useful for timestamping logs, events, or any data where a consistent, timezone-independent time representation is required. ```python def pytest_embedded.utils.utcnow_str() → str: """Returns the current UTC time as a string. """ pass ``` -------------------------------- ### pytest_embedded.plugin.wokwi Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded Launches a Wokwi subprocess for simulation. ```APIDOC ## GET pytest_embedded.plugin.wokwi ### Description A wokwi subprocess that could read/redirect/write. ### Method GET ### Endpoint /pytest_embedded.plugin.wokwi ### Parameters #### Path Parameters - **__fixture_classes_and_options** (ClassCliOptions_) - Required - Fixture classes and options for Wokwi. - **_app_** (string) - Required - The application to run in Wokwi. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **Wokwi** (object | None) - The Wokwi process object or None if Wokwi is not available. #### Response Example ```json { "example": "wokwi_process_object or null" } ``` ``` -------------------------------- ### Pytest Parametrization for Embedded Services and App Paths Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/concepts/key-concepts Illustrates how to use pytest's `@pytest.mark.parametrize` decorator to run the same test function with different configurations of `embedded_services` and `app_path`. This is equivalent to running separate pytest commands for each parameter set, enabling efficient testing across multiple build targets or configurations. ```python @pytest.mark.parametrize( "embedded_services, app_path", [ ("idf", app_path_1), ("idf", app_path_2), ], indirect=True, ) def test_serial_tcp(dut): assert dut.app.target == "esp32" dut.expect("Restart now") ``` -------------------------------- ### Qemu Class for QEMU Instance Management Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-qemu The Qemu class, inheriting from DuplicateStdoutPopen, manages QEMU instances. It defines various constants for default arguments, machine types, QMP formatting, serial TCP formatting, and strap mode. It provides methods for executing efuse commands (`execute_efuse_command`), interacting with QMP (`qmp_execute_cmd`), and taking screenshots (`take_screenshot`). ```python class Qemu(DuplicateStdoutPopen): QEMU_DEFAULT_ARGS = '-nographic -machine esp32' QEMU_DEFAULT_FMT = '-nographic -machine {}' QEMU_DEFAULT_QMP_FMT = '-qmp tcp:127.0.0.1:{},server,wait=off' QEMU_PROG_PATH = 'qemu-system-xtensa' QEMU_SERIAL_TCP_FMT = '-serial tcp::{},server,nowait' QEMU_STRAP_MODE_FMT = 'driver={}.gpio,property=strap_mode,value={}' SOURCE = 'QEMU' def execute_efuse_command(self, command: str): # Executes an efuse command on the QEMU instance. pass @property def qemu_default_args(self) -> str: # Returns the default command-line arguments for QEMU. return "-nographic -machine esp32" @property def qemu_prog_name(self) -> str: # Returns the name of the QEMU executable. return "qemu-system-xtensa" def qmp_execute_cmd(self, execute, arguments=None): # Executes a QEMU Machine Protocol (QMP) command. pass def take_screenshot(self, image_path): # Takes a screenshot of the QEMU instance. pass ``` -------------------------------- ### ArduinoApp Class Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-arduino The ArduinoApp class represents an Arduino application. It holds configuration details such as the sketch name, Fully Qualified Board Name (FQBN), target chip, and files to be flashed. ```APIDOC ## ArduinoApp Class ### Description Represents an Arduino application with configuration for flashing. ### Class `_pytest_embedded_arduino.app.ArduinoApp` ### Attributes - **sketch** (str) - The name of the Arduino sketch. - **fqbn** (str) - The Fully Qualified Board Name (e.g., `arduino:esp32:esp32`). - **target** (str) - The target ESPxx chip (e.g., `esp32`, `esp32s3`). - **flash_files** (List[Tuple[int, str, str]]) - A list of tuples, where each tuple contains the offset, file path, and encryption status for files to be flashed. - **binary_offsets** (ClassVar[dict[str, list[int]]]) - A dictionary mapping target chips to their respective binary offset lists. - **flash_settings** (ClassVar[dict[str, dict[str, str]]]) - A dictionary mapping target chips to their flash settings (e.g., flash frequency, mode, size). ``` -------------------------------- ### QemuApp Class for QEMU Application Management Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-qemu The QemuApp class extends IdfApp to manage QEMU applications. It defines properties like `image_path` for the QEMU flashable binary path and provides methods to create the QEMU image (`create_image`) and retrieve the QEMU version (`qemu_version`). It also defines constants for QEMU program formatting and version regex. ```python class QemuApp(IdfApp): QEMU_PROG_FMT = 'qemu-system-{}' QEMU_VERSION_REGEX = re.compile('QEMU emulator version (\d+\.\d+\.\d+)') @property def image_path(self) -> str: # QEMU flash-able bin path pass def create_image(self) -> None: # Create the image, if it doesn’t exist. pass @property def qemu_version(self) -> Version: # Get QEMU version return Version('8.0.0') ``` -------------------------------- ### IdfFlashImageMaker Class and Constants Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-qemu The IdfFlashImageMaker class is used to create a single flash image for QEMU. It includes class variables for defining flashable binary sizes for RISC-V and Xtensa architectures. The `make_bin` method generates the image, and `qemu_flash_size` property retrieves the QEMU flash size, with a warning for older QEMU versions regarding Xtensa flash size support. ```python class IdfFlashImageMaker: RISCV_FLASH_BIN_SIZES: ClassVar[list[tuple[int, str]]] = [(2097152, '2MB'), (4194304, '4MB'), (8388608, '8MB'), (16777216, '16MB')] XTENSA_FLASH_BIN_SIZES: ClassVar[list[tuple[int, str]]] = [(2097152, '2MB'), (4194304, '4MB'), (8388608, '8MB'), (16777216, '16MB')] def make_bin(self) -> None: # Create a single image file for qemu. pass @property def qemu_flash_size(self) -> str: # Get QEMU flash size. # If flash_size is set to keep or detect, the size will be automatically detected. # Otherwise, the size will be taken from flash_size settings. # Warning: QEMU < 8.0.0 only support 4MB flash image size for xtensa. return "" ``` -------------------------------- ### Enable pytest-embedded services Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/projects/pytest-embedded Command to enable specific services for pytest-embedded tests. Services like 'serial', 'esp', 'idf', 'jtag', 'qemu', 'arduino', 'wokwi', and 'nuttx' provide extended functionalities. ```shell pytest --embedded-services service[,service] ``` -------------------------------- ### Parameterize Tests with Target and Config Combinations (Python) Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/usages/markers.rst Illustrates using `idf_parametrize` to create test cases with combinations of hardware targets and build configurations (e.g., 'release', 'default', 'psram'). This enables testing across different target/config pairings. ```python @idf_parametrize('target, config', [ ('esp32', 'release'), ('esp32c3', 'default'), ('supported_target', 'psram') ], indirect=True) def test_st(dut: Dut) -> None: ... ``` -------------------------------- ### Run Pytest with Wokwi Service (CLI) Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/concepts/services Command to execute pytest tests while enabling both the 'idf' and 'wokwi' embedded services. This command configures pytest to utilize the functionalities provided by these services during test execution. ```bash pytest --embedded-services idf,wokwi ``` -------------------------------- ### Basic pytest-embedded test case Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/index A simple pytest test case using the `Dut` fixture from `pytest-embedded`. It demonstrates capturing redirected output and using `expect` and `expect_exact` to verify specific strings in the device's output. ```python from pytest_embedded import Dut def test_basic_expect(redirect, dut: Dut): with redirect(): print('this would be redirected') dut.expect('this') dut.expect_exact('would') dut.expect('[be]{2}') dut.expect_exact('redirected') ``` -------------------------------- ### Pytest-Embedded-IDF DUT Module Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/apis/pytest-embedded-idf.rst Documentation for the dut (Device Under Test) module in pytest-embedded-idf, enabling interaction with the target hardware. ```APIDOC ## Pytest-Embedded-IDF DUT Module ### Description This module allows for the control and monitoring of the Device Under Test (DUT) within the pytest-embedded-idf environment. ### Method N/A (This is a module documentation, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Python: expect() with expect_all and return_what_before_match Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/usages/expecting Demonstrates advanced usage of expect() with `expect_all=True` to match all specified patterns and `return_what_before_match=True` to retrieve the output preceding the match. This is useful for detailed analysis of the DUT's output stream. ```python import pexpect def test_expect_before_match(dut): dut.write('this would be redirected') res = dut.expect('would', return_what_before_match=True) assert res == b'this ' res = dut.expect_exact('be ', return_what_before_match=True) assert res == b' ' res = dut.expect('ected', return_what_before_match=True) assert res == b'redir' ``` -------------------------------- ### NuttxApp Class - pytest-embedded Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-nuttx The NuttxApp class in pytest-embedded-nuttx is designed to evaluate binary files for NuttX RTOS on Espressif devices. It handles firmware and bootloader files, extracting necessary information for flashing. The `file_extension` attribute specifies the expected extension for app binary files. ```python class NuttxApp(_file_extension ='.bin'_, _** kwargs_) : """NuttX App class for Espressif devices. Evaluates binary files (firmware and bootloader) and extract information required for flashing.""" file_extension : str """app binary file extension.""" ``` -------------------------------- ### Parameterize Tests with Supported Targets and Markers (Python) Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/usages/markers.rst Shows how to parameterize tests using `idf_parametrize` with explicitly defined supported targets and specific runner markers ('generic', 'sdcard', 'usb_device'). This ensures tests are executed on appropriate hardware and environments. ```python @idf_parametrize('target, markers', [ ('esp32', (pytest.mark.generic, )), ('esp32c3', (pytest.mark.sdcard, )), ('supported_target', (pytest.mark.usb_device, )) ], indirect=True) def test_st(dut: Dut) -> None: ... ``` -------------------------------- ### Enabling Multi-DUT Testing with Serial Service in Shell Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/concepts/key-concepts Shows how to enable multi-DUT mode for testing, specifically using the `serial` service for two independent devices. The `--count 2` option activates two DUT instances, and `--app-path |` assigns different application binaries to each. This configuration results in `app` and `dut` fixtures becoming tuples of instances. ```shell pytest \ --embedded-services serial|serial \ --count 2 \ --app-path | ``` -------------------------------- ### Parameterize Tests with Multiple Targets and Markers (Python) Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/usages/markers.rst Demonstrates how to use `idf_parametrize` to combine target and marker configurations for tests. This allows tests to be run with specific hardware targets and associated environment markers like 'generic', 'sdcard', or 'usb_device'. ```python @pytest.mark.generic @idf_parametrize('config', [ 'defaults' ], indirect=['config']) @idf_parametrize('target, markers', [ ('esp32', (pytest.mark.usb_device,)), ('esp32c3') ('esp32', (pytest.mark.sdcard,)) ], indirect=['target']) def test_console(dut: Dut, test_on: str) -> None: ... ``` -------------------------------- ### Pytest-Embedded-IDF Linux Module Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/apis/pytest-embedded-idf.rst Documentation for the linux module in pytest-embedded-idf, offering features for Linux-based test environments. ```APIDOC ## Pytest-Embedded-IDF Linux Module ### Description This module provides specific functionalities and utilities for running pytest-embedded-idf tests on Linux operating systems. ### Method N/A (This is a module documentation, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Python: expect() with a list of patterns Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/usages/expecting Shows how the expect() function can accept a list of patterns, attempting to match any one of them. This provides flexibility when the exact output might vary between several possibilities. ```python import re def test_expect_from_list(dut): dut.write("this would be redirected") pattern_list = [ "this", b"would", "[be]+", re.compile(b"redirected"), ] for _ in range(4): dut.expect(pattern_list) ``` -------------------------------- ### Class: FlashFile Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-idf Represents a file to be flashed, including its offset, file path, and encryption status. ```APIDOC ## Class: FlashFile ### Description Represents a file to be flashed, including its offset, file path, and encryption status. ### Fields - **offset** (int) - The starting offset for the file in flash. - **file_path** (str) - The path to the file to be flashed. - **encrypted** (bool) - Indicates whether the file is encrypted. ``` -------------------------------- ### QEMU Fixture - Python Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded A pytest fixture that provides a Qemu object or None. It takes ClassCliOptions and an App object to configure the QEMU emulator instance, allowing for software emulation of hardware. ```python def qemu_gn(__fixture_classes_and_options : ClassCliOptions_, _app_) -> Qemu | None: pass ``` -------------------------------- ### Run Project Tests Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/CONTRIBUTING Executes all tests within the project. An optional environment variable can be set to include JTAG-related tests if a connection is available. ```bash #!/bin/bash # export DONT_SKIP_JTAG_TESTS=1 (when you have a jtag connection) pytest ``` -------------------------------- ### Pytest-Embedded-IDF App Module Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/apis/pytest-embedded-idf.rst Documentation for the app module within pytest-embedded-idf, providing functionalities related to application management. ```APIDOC ## Pytest-Embedded-IDF App Module ### Description This module provides functionalities for managing and interacting with applications within the pytest-embedded-idf framework. ### Method N/A (This is a module documentation, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### CaseTester API Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-idf Provides methods for running various types of test cases on ESP-IDF devices, including options for resetting, timeouts, and retries. ```APIDOC ## CaseTester Methods ### `run_all_cases(_reset: bool = False, _timeout: int = 90, _start_retry: int = 3_) -> None` **Description**: Runs all test cases. Allows configuration of hardware reset, timeout, and retry attempts for starting cases. **Parameters**: - `reset` (bool) - Optional - Whether to perform a hardware reset before running a case. - `timeout` (int) - Optional - Timeout in seconds. - `start_retry` (int) - Optional - Number of retries for a single case when it is failed to start. ### `run_all_multi_dev_cases(_reset: bool = False, _timeout: float = 90, _start_retry: int = 3_) -> None` **Description**: Runs only multi-device test cases. Supports configuration for reset, timeout, and retries. **Parameters**: - `reset` (bool) - Optional - Whether to perform a hardware reset before running a case. - `timeout` (float) - Optional - Timeout in seconds. - `start_retry` (int) - Optional - Number of retries for a single case when it is failed to start. ### `run_all_multi_stage_cases(_reset: bool = False, _timeout: int = 90) -> None` **Description**: Runs all multi-stage test cases. Includes options for hardware reset and timeout. **Parameters**: - `reset` (bool) - Optional - Whether to perform a hardware reset before running the case. - `timeout` (int) - Optional - Timeout in seconds. ### `run_all_normal_cases(_reset: bool = False, _timeout: int = 90) -> None` **Description**: Runs all normal test cases. Configurable with reset and timeout parameters. **Parameters**: - `reset` (bool) - Optional - Whether to perform a hardware reset before running the case. - `timeout` (int) - Optional - Timeout in seconds. ### `run_case(_case: UnittestMenuCase, _reset: bool = False, _timeout: int = 90, _start_retry: int = 3_) -> None` **Description**: Runs a specific test case. Allows specifying the case, reset behavior, timeout, and start retry attempts. **Parameters**: - `case` (UnittestMenuCase) - Required - The specific case to run. - `reset` (bool) - Optional - Whether to perform a hardware reset before running a case. - `timeout` (int) - Optional - Timeout in seconds, setup time excluded. - `start_retry` (int) - Optional - Number of retries for a single case when it is failed to start. ### `run_multi_dev_case(_case: UnittestMenuCase, _reset: bool = False, _timeout: float = 90, _start_retry: int = 3_) -> None` **Description**: Runs a specific multi-device test case. Skips with a warning if the case type is not multi-device. Configurable with reset, timeout, and start retry. **Parameters**: - `case` (UnittestMenuCase) - Required - The specific case to run. - `reset` (bool) - Optional - Whether to perform a hardware reset before running a case. - `timeout` (float) - Optional - Timeout in seconds. - `start_retry` (int) - Optional - Number of retries for a single case when it is failed to start. ### `run_multi_stage_case(_case: UnittestMenuCase, _reset: bool = False, _timeout: int = 90) -> None` **Description**: Runs a specific multi-stage test case. Skips if the case type is not multi-stage. Supports reset and timeout configuration. **Parameters**: - `case` (UnittestMenuCase) - Required - The specific case to run. - `reset` (bool) - Optional - Whether to perform a hardware reset before running the case. - `timeout` (int) - Optional - Timeout in seconds. ### `run_normal_case(_case: UnittestMenuCase, _reset: bool = False, _timeout: int = 90) -> None` **Description**: Runs a specific normal test case. Skips if the case type is not normal. Supports reset and timeout configuration. **Parameters**: - `case` (UnittestMenuCase) - Required - The specific case to run. - `reset` (bool) - Optional - Whether to perform a hardware reset before running the case. - `timeout` (int) - Optional - Timeout in seconds. ``` -------------------------------- ### Pytest-Embedded-IDF Unity Tester Module Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/_sources/apis/pytest-embedded-idf.rst Documentation for the unity_tester module in pytest-embedded-idf, integrating with the Unity testing framework. ```APIDOC ## Pytest-Embedded-IDF Unity Tester Module ### Description This module provides integration with the Unity testing framework, allowing for the execution and reporting of Unity tests within pytest-embedded-idf. ### Method N/A (This is a module documentation, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Class: IdfApp Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-idf Manages an ESP-IDF application, including its build artifacts, flash settings, and target information. ```APIDOC ## Class: IdfApp ### Description Manages an ESP-IDF application, including its build artifacts, flash settings, and target information. ### Attributes - **elf_file** (str) - Path to the application's ELF file. - **flash_args** (dict[str, Any]) - Dictionary of flasher arguments loaded from `flasher_args.json`. - **flash_files** (list[FlashFile]) - List of files to be flashed, each represented by a `FlashFile` object. - **flash_settings** (dict[str, Any]) - Dictionary containing flash settings. - **RISCV32_TARGETS** (ClassVar[list[str]]) - List of RISC-V 32-bit target chip types. - **XTENSA_TARGETS** (ClassVar[list[str]]) - List of Xtensa target chip types. ### Methods - **get_sha256**(filepath: str) -> str | None - Get the SHA256 hash of a given file. ### Properties - **is_riscv32** (bool) - True if the target is RISC-V 32-bit. - **is_xtensa** (bool) - True if the target is Xtensa. - **_partition_table** (dict[str, Any]) - The partition table dictionary generated by the partition tool. - **_parttool_path** (str) - The path to the partition tool. - **_sdkconfig** (dict[str, Any]) - A dictionary containing key-value pairs from the `sdkconfig` file. - **_target** (str) - The target chip type. - **_write_flash_args** (list) - List of arguments used for writing to flash. ``` -------------------------------- ### QemuDut Class for QEMU Device Under Test Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-qemu The QemuDut class inherits from Dut and provides specific functionalities for controlling a QEMU device under test. It includes methods for performing a hard reset (`hard_reset`) and writing data to the device (`write`), typically interacting with its communication interface. ```python class QemuDut(Dut): def hard_reset(self) -> None: # Perform a hard reset on the QEMU DUT. pass def write(self, s: AnyStr) -> None: # Write data to the QEMU DUT's communication channel. pass ``` -------------------------------- ### pytest_embedded.plugin.redirect Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded A context manager to redirect stdout to a message queue. ```APIDOC ## GET pytest_embedded.plugin.redirect ### Description A context manager that could help duplicate all the sys.stdout to msg_queue. ### Method GET ### Endpoint /pytest_embedded.plugin.redirect ### Parameters #### Path Parameters - **_msg_queue_** (MessageQueue_) - Required - The message queue to redirect stdout to. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **redirect_stdout** (Callable) - A callable that returns a context manager for redirecting stdout. #### Response Example ```json { "example": "redirect_stdout_context_manager" } ``` ### Examples ```python >>> with redirect(): >>> print('this should be logged and sent to pexpect_proc') ``` ``` -------------------------------- ### Python: Basic expect() usage with different patterns Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/usages/expecting Demonstrates the basic usage of the expect() function with various pattern types including strings, bytes, and compiled regular expressions. This function is fundamental for asserting expected output from a device under test (DUT). ```python import re def test_basic_expect(dut): dut.write('this would be redirected') dut.expect(b'this') dut.expect('would') dut.expect('[be]{2}') dut.expect(re.compile(b'redirected')) ``` -------------------------------- ### Class: LinuxSerial Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-idf Handles serial communication for Linux DUTs. ```APIDOC ## Class: LinuxSerial ### Description Handles serial communication for Linux DUTs. ### Methods - **hard_reset**() -> None - Performs a fake hardware reset. ``` -------------------------------- ### IdfUnityDutMixin API Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-idf Provides ESP-IDF specific Unity test framework related functions for DUT interaction. ```APIDOC ## IdfUnityDutMixin Methods ### `confirm_write(_write_str: Any, *_ , _expect_pattern: Any | None = None, _expect_str: Any | None = None, _timeout: int = 1, _retry_times: int = 3_)` **Description**: Confirms writing to the device, optionally matching patterns or strings, with configurable timeout and retry times. **Parameters**: - `write_str` (Any) - Required - The string to write. - `expect_pattern` (Any | None) - Optional - Pattern to expect. - `expect_str` (Any | None) - Optional - String to expect. - `timeout` (int) - Optional - Timeout in seconds (default: 1). - `retry_times` (int) - Optional - Number of retries (default: 3). ### `run_all_single_board_cases(_group: str | list | None = None, _reset: bool = False, _timeout: float = 30, _run_ignore_cases: bool = False, _name: str | list | None = None, _attributes: dict | None = None, _dry_run: bool = False_) -> None` **Description**: Runs all single-board test cases, including multi-stage and normal cases. Supports filtering by group, name, and attributes. Includes options for reset, timeout, running ignored cases, and dry runs. **Parameters**: - `group` (str | list | None) - Optional - Test case group or list of groups. Supports 'and' (&) and inversion (!). - `reset` (bool) - Optional - Whether to perform a hardware reset before running. - `timeout` (float) - Optional - Timeout in seconds (default: 30). - `run_ignore_cases` (bool) - Optional - Whether to run ignored test cases. - `name` (str | list | None) - Optional - Test case name or list of names. - `attributes` (dict | None) - Optional - Dictionary of attributes for filtering. - `dry_run` (bool) - Optional - If True, only shows test case names without running them (set logging level to INFO). ### `run_single_board_case(_name: str, _reset: bool = False, _timeout: float = 30_) -> None` **Description**: Runs a specific single-board test case. Configurable with reset and timeout. **Parameters**: - `name` (str) - Required - The name of the test case. - `reset` (bool) - Optional - Whether to perform a hardware reset before running. - `timeout` (float) - Optional - Timeout in seconds (default: 30). ### `_property _test_menu: list[UnittestMenuCase]_` **Description**: Property that returns the list of parsed unittest menu cases. ``` -------------------------------- ### ArduinoSerial Class Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-arduino The ArduinoSerial class extends EspSerial to provide serial communication specific to Arduino devices. It includes functionality for automatic flashing upon test startup. ```APIDOC ## ArduinoSerial Class ### Description Handles serial communication for Arduino devices, with automatic flashing capabilities. ### Class `_pytest_embedded_arduino.serial.ArduinoSerial` ### Inherits From `EspSerial` ### Parameters - **app** (ArduinoApp) - An instance of the `ArduinoApp` class. - **target** (str | None, optional) - The target chip. Defaults to None. ### Constants - **SUGGEST_FLASH_BAUDRATE** (int) - A suggested baud rate for flashing (921600). ### Methods - **flash()** -> None - Flashes the binary files to the connected board. ``` -------------------------------- ### NuttxDut Class Methods - pytest-embedded Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded-nuttx The NuttxDut class provides a generic DUT (Device Under Test) interface for NuttX RTOS. It includes methods for resetting the device to the NuttShell prompt, retrieving the return code of the last program, writing data to the NuttShell, and writing data while capturing the response until a timeout. ```python class NuttxDut(Dut): PROMPT_NSH = 'nsh>' PROMPT_TIMEOUT_S = 30 def reset_to_nsh(self, ready_prompt: str = 'nsh>') -> None: """Resets the board and waits until the Nuttshell prompt appears. Defaults to ‘nsh>’. Parameters: **ready_prompt** (str) – string on prompt that signals completion. Returns: None """ pass def return_code(self, timeout: int = 30) -> int: """Matches the ‘echo $?’ response and extracts the integer value corresponding to the last program return code. The first regex option on expect is for serial interface, while the second will match QEMU. Returns: return code. Return type: int """ pass def write(self, data: str) -> None: """Write to NuttShell and sleep for a few hundred milliseconds to ensure there is time for Nuttshell prompt appear again. Parameters: **data** (str) – data to be passed on to Nuttshell. Returns: None. """ pass def write_and_return(self, data: str, timeout: int = 2) -> AnyStr: """Writes to Nuttshell and returns all available serial data until the timeout. This is useful when parsing and reusing the data is required, and pexect is not enough. Parameters: * **data** (str) – data to be passed on to Nuttshell. * **timeout** (int) – how long to wait for an answer in seconds. Returns: AnyStr """ pass ``` -------------------------------- ### DutFactory Class Source: https://docs.espressif.com/projects/pytest-embedded/en/latest/apis/pytest-embedded The DutFactory class is responsible for creating and managing Device Under Test (DUT) instances. ```APIDOC ## DutFactory Class ### Description Factory class for creating and managing Device Under Test (DUT) instances. ### Attributes - **obj_stack** (list) - Stack of DUT objects. ### Methods - **close()** - Closes all DUTs created by the factory. - **create(**kwargs) - Creates and returns a new DUT instance. - **get_all_duts()** - Returns a list of all DUTs managed by the factory. - **unity_tester()** - Returns the UNITY tester instance. ```