diff --git a/.github/workflows/restat_base_c_checker.yml b/.github/workflows/restat_base_c_checker.yml new file mode 100644 index 0000000..4571b0c --- /dev/null +++ b/.github/workflows/restat_base_c_checker.yml @@ -0,0 +1,33 @@ +name: restat_base C checker +on: + push: + branches: [ master ] + paths: + - 'sw/restat_base/src/**/*.c' + - 'sw/restat_base/src/**/*.h' + pull_request: + branches: [ master ] + paths: + - 'sw/restat_base/src/**/*.c' + - 'sw/restat_base/src/**/*.h' +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Check length of line in modules + id: long_line_checker + run: | + echo "Checking the length of lines in modules" + modules_ok=0 + modules=($(find sw/restat_base/src/ -type f -name '*.c' -exec echo '{}' \;)) + for mod in "${modules[@]}"; do line_length=$(wc -L < "${mod}"); echo "${mod} : $line_length"; [[ $line_length -gt 300 ]] && modules_ok=1; done + [[ $modules_ok -eq 0 ]] && echo "All modules are good" || exit 1 + - name: Check number of lines in modules + id: num_line_checker + run: | + echo "Checking the number of lines in modules" + modules_ok=0 + modules=($(find sw/restat_base/src/ -type f -name '*.c' -exec echo '{}' \;)) + for mod in "${modules[@]}"; do line_numbers=$(wc -l < "${mod}"); echo "${mod} : $line_numbers"; [[ $line_numbers -gt 300 ]] && modules_ok=1; done + [[ $modules_ok -eq 0 ]] && echo "All modules are good" && exit 0 || exit 1 diff --git a/.github/workflows/restat_desktop_cc_checker.yml b/.github/workflows/restat_desktop_cc_checker.yml index fc4e053..1f52807 100755 --- a/.github/workflows/restat_desktop_cc_checker.yml +++ b/.github/workflows/restat_desktop_cc_checker.yml @@ -1,13 +1,15 @@ -name: restat-desktop CC checker +name: restatdesk CC checker on: push: branches: [ master ] paths: - - 'sw/restat-desktop/**' + - 'sw/restatdesk/**/*.cc' + - 'sw/restatdesk/**/*.h' pull_request: branches: [ master ] paths: - - 'sw/restat-desktop/**' + - 'sw/restatdesk/**/*.cc' + - 'sw/restatdesk/**/*.h' jobs: build: runs-on: ubuntu-latest @@ -16,19 +18,16 @@ jobs: - name: Check length of line in modules id: long_line_checker run: | - echo Checking length of line in modules + echo "Checking the length of lines in modules" modules_ok=0 - modules=($(find sw/ -type f -name '*.cc' -exec echo '{}' \;)) - for mod in "${modules[@]}"; do line_length=$(wc -L < "${mod}"); [[ $line_length -gt 80 ]] && modules_ok=1; done - [[ $modules_ok -eq 0 ]] && echo ::set-output name=status::success || echo ::set-output name=status::failure + modules=($(find sw/restatdesk/ -type f -name '*.cc' -exec echo '{}' \;)) + for mod in "${modules[@]}"; do line_length=$(wc -L < "${mod}"); echo "${mod} : $line_length"; [[ $line_length -gt 500 ]] && modules_ok=1; done + [[ $modules_ok -eq 0 ]] && echo "All modules are good" || exit 1 - name: Check number of lines in modules id: num_line_checker run: | - echo Checking number of lines in modules + echo "Checking the number of lines in modules" modules_ok=0 - modules=($(find sw/ -type f -name '*.cc' -exec echo '{}' \;)) - for mod in "${modules[@]}"; do line_numbers=$(wc -l < "${mod}"); [[ $line_numbers -gt 300 ]] && modules_ok=1; done - [[ $modules_ok -eq 0 ]] && echo ::set-output name=status::success || echo ::set-output name=status::failure - - name: Check on failures - if: steps.long_line_checker.outputs.status == 'failure' || steps.num_line_checker.outputs.status == 'failure' - run: exit 1 + modules=($(find sw/restatdesk/ -type f -name '*.cc' -exec echo '{}' \;)) + for mod in "${modules[@]}"; do line_numbers=$(wc -l < "${mod}"); echo "${mod} : $line_numbers"; [[ $line_numbers -gt 500 ]] && modules_ok=1; done + [[ $modules_ok -eq 0 ]] && echo "All modules are good" && exit 0 || exit 1 diff --git a/.github/workflows/restat_desktop_cc_checker_build.yml b/.github/workflows/restat_desktop_cc_checker_build.yml index 6829cb9..43b369e 100644 --- a/.github/workflows/restat_desktop_cc_checker_build.yml +++ b/.github/workflows/restat_desktop_cc_checker_build.yml @@ -1,31 +1,38 @@ -name: restat-desktop C++ CI +name: restatdesk build checker on: push: branches: [ master ] paths: - - 'sw/restat-desktop/**' + - 'sw/restatdesk/**/*.cc' + - 'sw/restatdesk/**/*.h' pull_request: branches: [ master ] paths: - - 'sw/restat-desktop/**' + - 'sw/restatdesk/**/*.cc' + - 'sw/restatdesk/**/*.h' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: install GTK-- + - name: install gtkmm id: install_gtkmm run: | sudo apt-get update - sudo apt-get install jq - sudo apt-get install libgtkmm-3.0-dev + sudo apt-get upgrade -y + sudo apt-get install -y pkg-config + sudo apt-get install -y libserial-dev + sudo apt-get install -y libgtkmm-3.0-dev + sudo apt-get install -y libgtk-4-dev + sudo apt-get install -y software-properties-common + sudo apt-get install -y libgtkmm-4.0-dev - name: make all id: gnu_make_all run: | - cd sw/restat-desktop/build + cd sw/restatdesk/build make all - name: make clean id: gnu_make_clean run: | - cd sw/restat-desktop/build + cd sw/restatdesk/build make clean diff --git a/.github/workflows/restat_device_c_checker.yml b/.github/workflows/restat_device_c_checker.yml deleted file mode 100755 index e7776ab..0000000 --- a/.github/workflows/restat_device_c_checker.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: restat-device C checker -on: - push: - branches: [ master ] - paths: - - 'sw/restat-device0/**' - pull_request: - branches: [ master ] - paths: - - 'sw/restat-device1/**' -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Check length of line in modules - id: long_line_checker - run: | - echo Checking length of line in modules - modules_ok=0 - modules=($(find sw/ -type f -name '*.c' -exec echo '{}' \;)) - for mod in "${modules[@]}"; do line_length=$(wc -L < "${mod}"); [[ $line_length -gt 80 ]] && modules_ok=1; done - [[ $modules_ok -eq 0 ]] && echo ::set-output name=status::success || echo ::set-output name=status::failure - - name: Check number of lines in modules - id: num_line_checker - run: | - echo Checking number of lines in modules - modules_ok=0 - modules=($(find sw/ -type f -name '*.c' -exec echo '{}' \;)) - for mod in "${modules[@]}"; do line_numbers=$(wc -l < "${mod}"); [[ $line_numbers -gt 300 ]] && modules_ok=1; done - [[ $modules_ok -eq 0 ]] && echo ::set-output name=status::success || echo ::set-output name=status::failure - - name: Check on failures - if: steps.long_line_checker.outputs.status == 'failure' || steps.num_line_checker.outputs.status == 'failure' - run: exit 1 diff --git a/.github/workflows/restat_toc.yaml b/.github/workflows/restat_toc.yaml deleted file mode 100755 index ab779a6..0000000 --- a/.github/workflows/restat_toc.yaml +++ /dev/null @@ -1,11 +0,0 @@ -name: restat toc -on: - push: - paths: - - '**.md' -jobs: - generateTOC: - name: TOC Generator - runs-on: ubuntu-latest - steps: - - uses: technote-space/toc-generator@v2 diff --git a/.github/workflows/restat_toc.yml b/.github/workflows/restat_toc.yml new file mode 100644 index 0000000..c09313e --- /dev/null +++ b/.github/workflows/restat_toc.yml @@ -0,0 +1,25 @@ +name: restat toc + +on: + push: + branches: [ master ] + paths: + - '**.md' + pull_request: + branches: [ master ] + paths: + - '**.md' + +permissions: + contents: write + +jobs: + generateTOC: + name: restat toc + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Generate TOC + uses: technote-space/toc-generator@v4 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index e0c44ec..8d9adab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,87 @@ +# ========================================== +# 1. Global & Common Ignores +# ========================================== + +# OS Metadata +.DS_Store +Thumbs.db +*~ +*.swp +*.swo + +# Compiler & Build Artifacts (Generic) +*.o +*.obj +*.a +*.lib +*.so +*.dylib +*.dll +*.d +*.slo +*.lo +*.gch +*.pch +*.mod +*.smod +*.lai +*.la +*.exe +*.out +*.app +*.lss +core + +# Development Caches & Local Configurations +.cache/ +.clangd +.idea/ +.vs/ +*.pfx + +# Python generic ignores __pycache__/ *.py[cod] -*.o \ No newline at end of file +*.pyi +.venv/ +venv/ +ENV/ +env/ + +# CMake generic ignores +CMakeCache.txt +CMakeFiles/ +CMakeScripts/ +Testing/ +Makefile +cmake_install.cmake +install_manifest.txt +compile_commands.json +CTestTestfile.cmake +_deps/ +CPackConfig.cmake +CPackSourceConfig.cmake +CTestConfig.cmake + + +# ========================================== +# 2. Sub-project Ignores (Software - sw/) +# ========================================== + +### sw/restat_base +sw/restat_base/build/ + +### sw/restatdesk +sw/restatdesk/build/ +sw/restatdesk/resources.cc + + +# ========================================== +# 3. Sub-project Ignores (Hardware - hw/) +# ========================================== + +# KiCad / CAD backups and local caches +hw/**/*.kicad_pcb-bak +hw/**/*.sch-bak +hw/**/fp-info-cache +hw/**/*-backups/ \ No newline at end of file diff --git a/README.md b/README.md index 2a79b16..315d652 100644 --- a/README.md +++ b/README.md @@ -10,51 +10,156 @@ other information that should be provided before the tool is installed. [![GitHub issues open](https://img.shields.io/github/issues/electux/restat.svg)](https://github.com/electux/restat/issues) [![GitHub contributors](https://img.shields.io/github/contributors/electux/restat.svg)](https://github.com/electux/restat/graphs/contributors) + [![restat_base C checker](https://github.com/electux/restat/actions/workflows/restat_base_c_checker.yml/badge.svg)](https://github.com/electux/restat/actions/workflows/restat_base_c_checker.yml) + [![restatdesk CC checker](https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker.yml/badge.svg)](https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker.yml) + [![restatdesk build checker](https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker_build.yml/badge.svg)](https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker_build.yml) + [![restat toc](https://github.com/electux/restat/actions/workflows/restat_toc.yml/badge.svg)](https://github.com/electux/restat/actions/workflows/restat_toc.yml) + **Table of Contents** +- [System Components](#system-components) + - [1. restat Firmware (`restat_base`)](#1-restat-firmware-restat_base) + - [2. restatdesk GUI Application (`restatdesk`)](#2-restatdesk-gui-application-restatdesk) +- [Command Interface (restat Protocol)](#command-interface-restat-protocol) - [Installation](#installation) + - [1. Firmware (`restat_base`)](#1-firmware-restat_base) + - [2. Desktop Application (`restatdesk`)](#2-desktop-application-restatdesk) - [Usage](#usage) + - [1. GUI Panel](#1-gui-panel) + - [2. Test Commands](#2-test-commands) - [Dependencies](#dependencies) -- [Project structure](#project-structure) + - [Firmware (`restat_base`)](#firmware-restat_base) + - [Desktop GUI (`restatdesk`)](#desktop-gui-restatdesk) +- [Project Structure](#project-structure) - [Docs](#docs) - [Copyright and licence](#copyright-and-licence) +### System Components + +**restat** consists of two primary components: + +#### 1. restat Firmware (`restat_base`) +A low-level C firmware designed for Pico RP2040 microcontrollers to actuate, time, and persist relay outputs. +* **Role**: Actuates 8 mechanical relay channels using high-precision timers and persists configurations directly to onboard Flash memory. +* **Features**: + * Multi-interface Command Dispatcher (Serial, TCP/IP, BLE). + * Variable Execution Plan Parser: Processes complex execution strings concurrently to set states and schedules. + * Flash-Based Plan Persistence: Automatically stores execution plans at a `1.5 MB` flash offset (`0x180000`) and restores configurations upon reboot. + * Precise Timing Engine: Millisecond-level accuracy for Timed modes. + * Safety Watchdog & Sound Indicators: Recovery loops coupled with active buzzer signaling. + +#### 2. restatdesk GUI Application (`restatdesk`) +A responsive, cross-platform C++ application built on **gtkmm 4** and **GTK 4**. +* **Role**: Configures, controls, and monitors the relay station in real-time. +* **Features**: + * Real-Time LED Indicators: High-visibility green status lights showing live channel states. + * Configurable Relay Modes: + * **Toggle Mode**: Activates or deactivates relays on click. + * **Timer Mode**: Executes timed sequences with flexible starting states (Active = ON on Start, Deactive = OFF on Start). + * Dynamic Plan Builder: Serializes only active relay states into a single, variable-length plan command to protect relay lifespans. + * Sleek Green-on-Black Dark Mode: Custom CSS styles compiled directly into the binary as GResource packages. + * Multithreaded System Logs: Visualized console output and persistent file logging. + +--- + +### Command Interface (restat Protocol) + +All commands sent to the `restat_base` firmware must be wrapped in start/end markers: ``. + +| Command | Action | Description | +|---|---|---| +| `` | Identify | Returns board identification (e.g. ``) | +| `` | Get Version | Returns firmware version (e.g. ``) | +| `` | Channel ON | Sets channel `X` (1-8) to ON (active) state | +| `` | Channel OFF | Sets channel `X` (1-8) to OFF (deactive) state | +| `` | Timed Channel | Starts timer on channel `X` for `MS` milliseconds starting ON | +| `` | All ON | Turns all channels ON concurrently | +| `` | All OFF | Turns all channels OFF concurrently | +| `` | Binary Mask | Sets all 8 channels to binary state `MASK` (e.g. `10101010`) | +| `` | Execute Plan | Sends a variable-length configuration plan containing relay states and saves it to Flash | +| `` | Channel Status | Returns the status string of channel `X` | +| `` | All Status | Returns status dump for all channels | +| `` | Reset | Performs soft system reset using watchdog | + +--- ### Installation ![Debian Linux OS](https://raw.githubusercontent.com/electux/restat/dev/docs/debtux.png) -Navigate to release [page](https://github.com/electux/restat/releases) download and extract release archive. - -To install **restat** follow next instructions -``` -in progress +#### 1. Firmware (`restat_base`) +1. Setup the Raspberry Pi Pico SDK on your host system. +2. Navigate to the firmware workspace and build the project: + ```bash + cd sw/restat_base + mkdir -p build && cd build + cmake .. + make -j$(nproc) + ``` +3. Boot the RP2040 board in BOOTSEL mode by holding the boot button while connecting USB, and copy `restat_base.uf2` to the mounted mass storage device. + +#### 2. Desktop Application (`restatdesk`) +Ensure all compiler tools and GTK 4 libraries are installed (see dependencies), then run: +```bash +cd sw/restatdesk/build +make all ``` +The executable `restatdesk` will be compiled and ready to run inside the `build/` directory. + +--- ### Usage -Planned in picking and packaging in micro-factories. -``` -in progress +#### 1. GUI Panel +Launch the compiled desktop client: +```bash +./sw/restatdesk/build/restatdesk ``` +Configure your connection type (Serial Port path, TCP IP/Port, or Bluetooth address) inside the Settings window, toggle active relay options in the UI, and click **Execute Plan** in the main window or under the `Command` menu to apply changes. -### Dependencies - -**restat** requires next modules and libraries -``` -in progress +#### 2. Test Commands +You can also connect to the station via raw serial console or socket connection (e.g., using `minicom` or `nc`) and issue raw protocol packages: +```bash +# Set channel 1 to ON + ``` -### Project structure +--- -**restat** is based on POP. -``` -in progress -``` +### Dependencies + +#### Firmware (`restat_base`) +* Raspberry Pi Pico SDK (v1.5.0+) +* GCC ARM Embedded Toolchain (`arm-none-eabi-gcc`) +* CMake & GNU Make + +#### Desktop GUI (`restatdesk`) +* C++23 compatible compiler (GCC 13+) +* `gtkmm-4.0` & `libgtk-4-dev` +* `libserial-dev` +* `pkg-config` +* GNU Make + +--- + +### Project Structure + +The codebase is organized as follows: +* [`sw/restat_base/`](file:///data/dev/raspberry/restat/github/restat/sw/restat_base) - Core Pico firmware: + - `src/command/` - Dispatcher and frame parser. + - `src/device/` - Watchdog, buzzer, relay, and flash persistence drivers. +* [`sw/restat_base_tests/`](file:///data/dev/raspberry/restat/github/restat/sw/restat_base_tests) - C++ GoogleTest suite for host-based firmware logic validation. +* [`sw/restatdesk/`](file:///data/dev/raspberry/restat/github/restat/sw/restatdesk) - GTK 4 client: + - `com/` - Serial, TCP, and BLE client layers. + - `config/` - File configuration load/store manager. + - `model/` - Relay delegates, channel states, and business logic. + - `view/` - GUI window tabs, widgets, and GResource styled assets. +* [`sw/restatdesk_tests/`](file:///data/dev/raspberry/restat/github/restat/sw/restatdesk_tests) - C++ GoogleTest suite for desktop client controllers and helpers. +* [`docs/`](file:///data/dev/raspberry/restat/github/restat/docs) - Documentation source files. ### Docs @@ -71,8 +176,4 @@ Copyright (C) 2020 - 2024 by [electux.github.io/restat](https://electux.github.i Lets help and support Raspberry PI && GNOME. - -RPi - -GNOME - +Foundations diff --git a/docs/GNOME.png b/docs/GNOME.png deleted file mode 100644 index dad3734..0000000 Binary files a/docs/GNOME.png and /dev/null differ diff --git a/docs/RPi.png b/docs/RPi.png deleted file mode 100644 index 7975ced..0000000 Binary files a/docs/RPi.png and /dev/null differ diff --git a/docs/build/doctrees/environment.pickle b/docs/build/doctrees/environment.pickle index 2dacc20..0aea87e 100644 Binary files a/docs/build/doctrees/environment.pickle and b/docs/build/doctrees/environment.pickle differ diff --git a/docs/build/doctrees/index.doctree b/docs/build/doctrees/index.doctree index 193b1eb..6e4d688 100644 Binary files a/docs/build/doctrees/index.doctree and b/docs/build/doctrees/index.doctree differ diff --git a/docs/build/html/.buildinfo b/docs/build/html/.buildinfo index a4d5510..8bc6723 100644 --- a/docs/build/html/.buildinfo +++ b/docs/build/html/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: 2e449e5e4407c6ca24699f725982b8ce +config: 574c3deb57811c1dd9a2ed1359a26029 tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/html/_sources/index.rst.txt b/docs/build/html/_sources/index.rst.txt index 23329a7..220f5c3 100644 --- a/docs/build/html/_sources/index.rst.txt +++ b/docs/build/html/_sources/index.rst.txt @@ -12,7 +12,7 @@ other information that should be provided before the tool is installed. self -|GitHub issues| |Documentation Status| |GitHub contributors| +|GitHub issues| |Documentation Status| |GitHub contributors| |restat_base C checker| |restatdesk CC checker| |restatdesk build checker| |restat toc| .. |GitHub issues| image:: https://img.shields.io/github/issues/electux/restat.svg :target: https://github.com/electux/restat/issues @@ -23,33 +23,168 @@ other information that should be provided before the tool is installed. .. |Documentation Status| image:: https://readthedocs.org/projects/restat/badge/?version=latest :target: https://restat.readthedocs.io/projects/restat/en/latest/?badge=latest +.. |restat_base C checker| image:: https://github.com/electux/restat/actions/workflows/restat_base_c_checker.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_base_c_checker.yml + +.. |restatdesk CC checker| image:: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker.yml + +.. |restatdesk build checker| image:: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker_build.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker_build.yml + +.. |restat toc| image:: https://github.com/electux/restat/actions/workflows/restat_toc.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_toc.yml + +System Components +----------------- + +**restat** consists of two primary components: + +1. restat Firmware (``restat_base``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A low-level C firmware designed for Pico RP2040 microcontrollers to actuate, time, and persist relay outputs. + +* **Role**: Actuates 8 mechanical relay channels using high-precision timers and persists configurations directly to onboard Flash memory. +* **Features**: + * Multi-interface Command Dispatcher (Serial, TCP/IP, BLE). + * Variable Execution Plan Parser: Processes complex execution strings concurrently to set states and schedules. + * Flash-Based Plan Persistence: Automatically stores execution plans at a ``1.5 MB`` flash offset (``0x180000``) and restores configurations upon reboot. + * Precise Timing Engine: Millisecond-level accuracy for Timed modes. + * Safety Watchdog & Sound Indicators: Recovery loops coupled with active buzzer signaling. + +2. restatdesk GUI Application (``restatdesk``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A responsive, cross-platform C++ application built on **gtkmm 4** and **GTK 4**. + +* **Role**: Configures, controls, and monitors the relay station in real-time. +* **Features**: + + * Real-Time LED Indicators: High-visibility green status lights showing live channel states. + * Configurable Relay Modes: + + * **Toggle Mode**: Activates or deactivates relays on click. + * **Timer Mode**: Executes timed sequences with flexible starting states (Active = ON on Start, Deactive = OFF on Start). + + * Dynamic Plan Builder: Serializes only active relay states into a single, variable-length plan command to protect relay lifespans. + * Sleek Green-on-Black Dark Mode: Custom CSS styles compiled directly into the binary as GResource packages. + * Multithreaded System Logs: Visualized console output and persistent file logging. + + +Command Interface (restat Protocol) +----------------------------------- + +All commands sent to the ``restat_base`` firmware must be wrapped in start/end markers: ````. + ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| Command | Action | Description | ++=====================================+==================+===================================================================================+ +| ```` | Identify | Returns board identification (e.g. ````) | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Get Version | Returns firmware version (e.g. ````) | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Channel ON | Sets channel ``X`` (1-8) to ON (active) state | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Channel OFF | Sets channel ``X`` (1-8) to OFF (deactive) state | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Timed Channel | Starts timer on channel ``X`` for ``MS`` milliseconds starting ON | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | All ON | Turns all channels ON concurrently | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | All OFF | Turns all channels OFF concurrently | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Binary Mask | Sets all 8 channels to binary state ``MASK`` (e.g. ``10101010``) | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Execute Plan | Sends a variable-length configuration plan containing relay states and saves | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Channel Status | Returns the status string of channel ``X`` | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | All Status | Returns status dump for all channels | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Reset | Performs soft system reset using watchdog | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ + Installation -------------- +------------ + +1. Firmware (``restat_base``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Setup the Raspberry Pi Pico SDK on your host system, then build: + +.. code-block:: bash -Navigate to release `page`_ download and extract release archive. + cd sw/restat_base + mkdir -p build && cd build + cmake .. + make -j$(nproc) -.. _page: https://github.com/electux/restat/releases +Boot the board in BOOTSEL mode and copy the compiled ``restat_base.uf2`` to the Pico mass storage volume. -To install **restat** type the following +2. Desktop Application (``restatdesk``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Ensure all C++23 compiler tools and GTK 4 libraries are installed, then run: .. code-block:: bash - in progress + cd sw/restatdesk/build + make all -Dependencies -------------- +The executable ``restatdesk`` will be ready inside the ``build/`` directory. + +Usage +----- + +1. GUI Panel +~~~~~~~~~~~~ +Launch the desktop client: -**restat** requires next modules and libraries - in progress +.. code-block:: bash + + ./sw/restatdesk/build/restatdesk -Project structure ------------------- +Configure the connection (Serial, TCP/IP, or BLE) in the Settings window, toggle active relay options in the UI, and click **Execute Plan** in the main window or under the ``Command`` menu to transmit changes. -**restat** is based on POP. +2. Test Commands +~~~~~~~~~~~~~~~~ +Connect directly to the station via terminal console or socket connection (e.g. ``minicom`` or ``nc``) and send raw protocol frames: .. code-block:: bash - in progress + # Set channel 1 to ON + + +Dependencies +------------ + +Firmware (``restat_base``) +~~~~~~~~~~~~~~~~~~~~~~~~~~ +* Raspberry Pi Pico SDK (v1.5.0+) +* GCC ARM Embedded Toolchain (``arm-none-eabi-gcc``) +* CMake & GNU Make + +Desktop GUI (``restatdesk``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +* C++23 compatible compiler (GCC 13+) +* ``gtkmm-4.0`` & ``libgtk-4-dev`` +* ``libserial-dev`` +* ``pkg-config`` +* GNU Make + +Project Structure +----------------- + +The codebase layout is structured as follows: + +* `sw/restat_base/ `_ - Core Pico firmware: + * ``src/command/`` - Dispatcher and frame parser. + * ``src/device/`` - Watchdog, buzzer, relay, and flash persistence drivers. +* `sw/restat_base_tests/ `_ - C++ GoogleTest suite for host-based firmware logic validation. +* `sw/restatdesk/ `_ - GTK 4 client: + * ``com/`` - Serial, TCP, and BLE client layers. + * ``config/`` - File configuration load/store manager. + * ``model/`` - Relay delegates, channel states, and business logic. + * ``view/`` - GUI window tabs, widgets, and GResource styled assets. +* `sw/restatdesk_tests/ `_ - C++ GoogleTest suite for desktop client controllers and helpers. +* `docs/ `_ - Documentation source files. Copyright and licence ---------------------- @@ -64,3 +199,11 @@ Copyright and licence Copyright (C) 2020 - 2024 by `electux.github.io/restat `_ +Lets help and support Raspberry PI && GNOME. + +.. image:: https://raw.githubusercontent.com/electux/restat/master/docs/foundations.png + :alt: Foundations + :width: 192px + :height: 109px + + diff --git a/docs/build/html/index.html b/docs/build/html/index.html index 04f33e5..e96cd47 100644 --- a/docs/build/html/index.html +++ b/docs/build/html/index.html @@ -40,34 +40,195 @@

restat
-

GitHub issues Documentation Status GitHub contributors

+

GitHub issues Documentation Status GitHub contributors restat_base C checker restatdesk CC checker restatdesk build checker restat toc

+ +
+

System Components

+

restat consists of two primary components:

+
+

1. restat Firmware (restat_base)

+

A low-level C firmware designed for Pico RP2040 microcontrollers to actuate, time, and persist relay outputs.

+
    +
  • Role: Actuates 8 mechanical relay channels using high-precision timers and persists configurations directly to onboard Flash memory.

  • +
  • Features: +* Multi-interface Command Dispatcher (Serial, TCP/IP, BLE). +* Variable Execution Plan Parser: Processes complex execution strings concurrently to set states and schedules. +* Flash-Based Plan Persistence: Automatically stores execution plans at a 1.5 MB flash offset (0x180000) and restores configurations upon reboot. +* Precise Timing Engine: Millisecond-level accuracy for Timed modes. +* Safety Watchdog & Sound Indicators: Recovery loops coupled with active buzzer signaling.

  • +
+
+
+

2. restatdesk GUI Application (restatdesk)

+

A responsive, cross-platform C++ application built on gtkmm 4 and GTK 4.

+
    +
  • Role: Configures, controls, and monitors the relay station in real-time.

  • +
  • Features:

    +
      +
    • Real-Time LED Indicators: High-visibility green status lights showing live channel states.

    • +
    • Configurable Relay Modes:

      +
        +
      • Toggle Mode: Activates or deactivates relays on click.

      • +
      • Timer Mode: Executes timed sequences with flexible starting states (Active = ON on Start, Deactive = OFF on Start).

      • +
      +
    • +
    • Dynamic Plan Builder: Serializes only active relay states into a single, variable-length plan command to protect relay lifespans.

    • +
    • Sleek Green-on-Black Dark Mode: Custom CSS styles compiled directly into the binary as GResource packages.

    • +
    • Multithreaded System Logs: Visualized console output and persistent file logging.

    • +
    +
  • +
+
+
+
+

Command Interface (restat Protocol)

+

All commands sent to the restat_base firmware must be wrapped in start/end markers: <rs#TARGET#ACTION#PARAMS#end>.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Command

Action

Description

<rs#sys#id#end>

Identify

Returns board identification (e.g. <rs#sys#rs:333:2023:0#end>)

<rs#sys#version#end>

Get Version

Returns firmware version (e.g. <rs#sys#restat v1.0.0#end>)

<rs#ch#X#on#end>

Channel ON

Sets channel X (1-8) to ON (active) state

<rs#ch#X#off#end>

Channel OFF

Sets channel X (1-8) to OFF (deactive) state

<rs#ch#X#tmr#MS#end>

Timed Channel

Starts timer on channel X for MS milliseconds starting ON

<rs#all#on#end>

All ON

Turns all channels ON concurrently

<rs#all#off#end>

All OFF

Turns all channels OFF concurrently

<rs#all#mask#MASK#end>

Binary Mask

Sets all 8 channels to binary state MASK (e.g. 10101010)

<rs#all#plan#[plan_string]#end>

Execute Plan

Sends a variable-length configuration plan containing relay states and saves

<rs#ch#X#stat#end>

Channel Status

Returns the status string of channel X

<rs#all#stat#end>

All Status

Returns status dump for all channels

<rs#sys#reset#end>

Reset

Performs soft system reset using watchdog

Installation

-

Navigate to release page download and extract release archive.

-

To install restat type the following

-
in progress
+
+

1. Firmware (restat_base)

+

Setup the Raspberry Pi Pico SDK on your host system, then build:

+
cd sw/restat_base
+mkdir -p build && cd build
+cmake ..
+make -j$(nproc)
+
+
+

Boot the board in BOOTSEL mode and copy the compiled restat_base.uf2 to the Pico mass storage volume.

+
+
+

2. Desktop Application (restatdesk)

+

Ensure all C++23 compiler tools and GTK 4 libraries are installed, then run:

+
cd sw/restatdesk/build
+make all
+
+
+

The executable restatdesk will be ready inside the build/ directory.

+
+
+
+

Usage

+
+

1. GUI Panel

+

Launch the desktop client:

+
./sw/restatdesk/build/restatdesk
 
+

Configure the connection (Serial, TCP/IP, or BLE) in the Settings window, toggle active relay options in the UI, and click Execute Plan in the main window or under the Command menu to transmit changes.

+
+
+

2. Test Commands

+

Connect directly to the station via terminal console or socket connection (e.g. minicom or nc) and send raw protocol frames:

+
# Set channel 1 to ON
+<rs#ch#1#on#end>
+
+
+

Dependencies

-
-
restat requires next modules and libraries

in progress

-
-
+
+

Firmware (restat_base)

+
    +
  • Raspberry Pi Pico SDK (v1.5.0+)

  • +
  • GCC ARM Embedded Toolchain (arm-none-eabi-gcc)

  • +
  • CMake & GNU Make

  • +
+
+
+

Desktop GUI (restatdesk)

+
    +
  • C++23 compatible compiler (GCC 13+)

  • +
  • gtkmm-4.0 & libgtk-4-dev

  • +
  • libserial-dev

  • +
  • pkg-config

  • +
  • GNU Make

  • +
+
-

Project structure

-

restat is based on POP.

-
in progress
-
-
+

Project Structure

+

The codebase layout is structured as follows:

+
    +
  • sw/restat_base/ - Core Pico firmware: +* src/command/ - Dispatcher and frame parser. +* src/device/ - Watchdog, buzzer, relay, and flash persistence drivers.

  • +
  • sw/restat_base_tests/ - C++ GoogleTest suite for host-based firmware logic validation.

  • +
  • sw/restatdesk/ - GTK 4 client: +* com/ - Serial, TCP, and BLE client layers. +* config/ - File configuration load/store manager. +* model/ - Relay delegates, channel states, and business logic. +* view/ - GUI window tabs, widgets, and GResource styled assets.

  • +
  • sw/restatdesk_tests/ - C++ GoogleTest suite for desktop client controllers and helpers.

  • +
  • docs/ - Documentation source files.

  • +
@@ -81,9 +242,28 @@

Copyright and licenceTable of Contents

diff --git a/docs/build/html/searchindex.js b/docs/build/html/searchindex.js index 8af1f4d..3e0d4b9 100644 --- a/docs/build/html/searchindex.js +++ b/docs/build/html/searchindex.js @@ -1 +1 @@ -Search.setIndex({"docnames": ["index"], "filenames": ["index.rst"], "titles": ["restat"], "terms": {"i": 0, "control": 0, "relai": 0, "interfac": 0, "station": 0, "automat": 0, "The": 0, "readm": 0, "us": 0, "introduc": 0, "tool": 0, "provid": 0, "instruct": 0, "how": 0, "ani": 0, "machin": 0, "mai": 0, "have": 0, "other": 0, "inform": 0, "should": 0, "befor": 0, "navig": 0, "releas": 0, "page": 0, "download": 0, "extract": 0, "archiv": 0, "To": 0, "type": 0, "follow": 0, "progress": 0, "requir": 0, "next": 0, "modul": 0, "librari": 0, "base": 0, "pop": 0, "c": 0, "2020": 0, "2024": 0, "electux": 0, "github": 0, "io": 0}, "objects": {}, "objtypes": {}, "objnames": {}, "titleterms": {"restat": 0, "instal": 0, "depend": 0, "project": 0, "structur": 0, "copyright": 0, "licenc": 0}, "envversion": {"sphinx.domains.c": 3, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 9, "sphinx.domains.index": 1, "sphinx.domains.javascript": 3, "sphinx.domains.math": 2, "sphinx.domains.python": 4, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx.ext.viewcode": 1, "sphinx": 60}, "alltitles": {"restat": [[0, "restat"]], "Installation": [[0, "installation"]], "Dependencies": [[0, "dependencies"]], "Project structure": [[0, "project-structure"]], "Copyright and licence": [[0, "copyright-and-licence"]]}, "indexentries": {}}) \ No newline at end of file +Search.setIndex({"docnames": ["index"], "filenames": ["index.rst"], "titles": ["restat"], "terms": {"i": 0, "control": 0, "relai": 0, "station": 0, "automat": 0, "The": 0, "readm": 0, "us": 0, "introduc": 0, "tool": 0, "provid": 0, "instruct": 0, "how": 0, "ani": 0, "machin": 0, "mai": 0, "have": 0, "other": 0, "inform": 0, "should": 0, "befor": 0, "consist": 0, "two": 0, "primari": 0, "A": 0, "low": 0, "level": 0, "c": 0, "design": 0, "pico": 0, "rp2040": 0, "microcontrol": 0, "actuat": 0, "time": 0, "persist": 0, "output": 0, "role": 0, "8": 0, "mechan": 0, "channel": 0, "high": 0, "precis": 0, "timer": 0, "configur": 0, "directli": 0, "onboard": 0, "flash": 0, "memori": 0, "featur": 0, "multi": 0, "dispatch": 0, "serial": 0, "tcp": 0, "ip": 0, "ble": 0, "variabl": 0, "execut": 0, "plan": 0, "parser": 0, "process": 0, "complex": 0, "string": 0, "concurr": 0, "set": 0, "state": 0, "schedul": 0, "base": 0, "store": 0, "5": 0, "mb": 0, "offset": 0, "0x180000": 0, "restor": 0, "upon": 0, "reboot": 0, "engin": 0, "millisecond": 0, "accuraci": 0, "mode": 0, "safeti": 0, "watchdog": 0, "sound": 0, "indic": 0, "recoveri": 0, "loop": 0, "coupl": 0, "activ": 0, "buzzer": 0, "signal": 0, "respons": 0, "cross": 0, "platform": 0, "built": 0, "gtkmm": 0, "4": 0, "gtk": 0, "monitor": 0, "real": 0, "led": 0, "visibl": 0, "green": 0, "statu": 0, "light": 0, "show": 0, "live": 0, "toggl": 0, "deactiv": 0, "click": 0, "sequenc": 0, "flexibl": 0, "start": 0, "ON": 0, "off": 0, "dynam": 0, "builder": 0, "onli": 0, "singl": 0, "length": 0, "protect": 0, "lifespan": 0, "sleek": 0, "black": 0, "dark": 0, "custom": 0, "css": 0, "style": 0, "compil": 0, "binari": 0, "gresourc": 0, "packag": 0, "multithread": 0, "log": 0, "visual": 0, "consol": 0, "file": 0, "all": 0, "sent": 0, "must": 0, "wrap": 0, "end": 0, "marker": 0, "r": 0, "target": 0, "action": 0, "param": 0, "descript": 0, "sy": 0, "id": 0, "identifi": 0, "return": 0, "board": 0, "identif": 0, "e": 0, "g": 0, "333": 0, "2023": 0, "0": 0, "version": 0, "get": 0, "v1": 0, "ch": 0, "x": 0, "tmr": 0, "m": 0, "turn": 0, "mask": 0, "10101010": 0, "plan_str": 0, "send": 0, "contain": 0, "save": 0, "stat": 0, "dump": 0, "reset": 0, "perform": 0, "soft": 0, "setup": 0, "raspberri": 0, "pi": 0, "sdk": 0, "your": 0, "host": 0, "build": 0, "cd": 0, "sw": 0, "mkdir": 0, "p": 0, "cmake": 0, "make": 0, "j": 0, "nproc": 0, "boot": 0, "bootsel": 0, "copi": 0, "uf2": 0, "mass": 0, "storag": 0, "volum": 0, "ensur": 0, "23": 0, "librari": 0, "ar": 0, "run": 0, "readi": 0, "insid": 0, "directori": 0, "launch": 0, "client": 0, "connect": 0, "window": 0, "option": 0, "ui": 0, "main": 0, "under": 0, "menu": 0, "transmit": 0, "chang": 0, "via": 0, "termin": 0, "socket": 0, "minicom": 0, "nc": 0, "raw": 0, "frame": 0, "gcc": 0, "arm": 0, "embed": 0, "toolchain": 0, "none": 0, "eabi": 0, "gnu": 0, "compat": 0, "13": 0, "libgtk": 0, "dev": 0, "libseri": 0, "pkg": 0, "config": 0, "codebas": 0, "layout": 0, "follow": 0, "core": 0, "src": 0, "devic": 0, "driver": 0, "restat_base_test": 0, "googletest": 0, "suit": 0, "logic": 0, "valid": 0, "com": 0, "layer": 0, "load": 0, "manag": 0, "model": 0, "deleg": 0, "busi": 0, "view": 0, "tab": 0, "widget": 0, "asset": 0, "restatdesk_test": 0, "helper": 0, "doc": 0, "document": 0, "sourc": 0, "2020": 0, "2024": 0, "electux": 0, "github": 0, "io": 0, "let": 0, "help": 0, "support": 0, "gnome": 0}, "objects": {}, "objtypes": {}, "objnames": {}, "titleterms": {"restat": 0, "system": 0, "compon": 0, "1": 0, "firmwar": 0, "restat_bas": 0, "2": 0, "restatdesk": 0, "gui": 0, "applic": 0, "command": 0, "interfac": 0, "protocol": 0, "instal": 0, "desktop": 0, "usag": 0, "panel": 0, "test": 0, "depend": 0, "project": 0, "structur": 0, "copyright": 0, "licenc": 0}, "envversion": {"sphinx.domains.c": 3, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 9, "sphinx.domains.index": 1, "sphinx.domains.javascript": 3, "sphinx.domains.math": 2, "sphinx.domains.python": 4, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx.ext.viewcode": 1, "sphinx": 60}, "alltitles": {"restat": [[0, "restat"]], "System Components": [[0, "system-components"]], "1. restat Firmware (restat_base)": [[0, "restat-firmware-restat-base"]], "2. restatdesk GUI Application (restatdesk)": [[0, "restatdesk-gui-application-restatdesk"]], "Command Interface (restat Protocol)": [[0, "command-interface-restat-protocol"]], "Installation": [[0, "installation"]], "1. Firmware (restat_base)": [[0, "firmware-restat-base"]], "2. Desktop Application (restatdesk)": [[0, "desktop-application-restatdesk"]], "Usage": [[0, "usage"]], "1. GUI Panel": [[0, "gui-panel"]], "2. Test Commands": [[0, "test-commands"]], "Dependencies": [[0, "dependencies"]], "Firmware (restat_base)": [[0, "id1"]], "Desktop GUI (restatdesk)": [[0, "desktop-gui-restatdesk"]], "Project Structure": [[0, "project-structure"]], "Copyright and licence": [[0, "copyright-and-licence"]]}, "indexentries": {}}) \ No newline at end of file diff --git a/docs/foundations.png b/docs/foundations.png new file mode 100644 index 0000000..40cb7e6 Binary files /dev/null and b/docs/foundations.png differ diff --git a/docs/source/conf.py b/docs/source/conf.py index 81747f1..fb0e043 100755 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -21,11 +21,10 @@ import sys from os.path import abspath -from typing import Any, List, Dict, Tuple __author__ = 'Vladimir Roncevic' __copyright__ = '(C) 2024, https://vroncevic.github.io/restat' -__credits__: List[str] = ['Vladimir Roncevic', 'Python Software Foundation'] +__credits__: list[str] = ['Vladimir Roncevic', 'Python Software Foundation'] __license__ = 'https://github.com/vroncevic/restat/blob/dev/LICENSE' __version__ = '1.0.0' __maintainer__ = 'Vladimir Roncevic' @@ -39,30 +38,30 @@ author: str = 'Vladimir Roncevic ' version: str = '1.0.0' release: str = 'https://github.com/vroncevic/restat/releases' -extensions: List[str] = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] -templates_path: List[str] = ['_templates'] +extensions: list[str] = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] +templates_path: list[str] = ['_templates'] source_suffix: str = '.rst' master_doc: str = 'index' language: str = 'en' -html_static_path: List[str] = ['_static'] -exclude_patterns: List[str] = [] +html_static_path: list[str] = ['_static'] +exclude_patterns: list[str] = [] pygments_style: str = 'sphinx' html_theme: str = 'classic' -html_static_path: List[str] = ['_static'] +html_static_path: list[str] = ['_static'] htmlhelp_basename: str = 'restatdoc' -latex_elements: Dict[Any, Any] = {} -latex_documents: List[Tuple[Any, ...]] = [( +latex_elements: dict[object, object] = {} +latex_documents: list[tuple[object, ...]] = [( master_doc, 'restat.tex', 'restat Documentation', 'Vladimir Roncevic \\textless{}elektron.ronca@gmail.com\\textgreater{}', 'manual' )] -man_pages: List[Tuple[Any, ...]] = [( +man_pages: list[tuple[object, ...]] = [( master_doc, 'restat', 'restat Documentation', [author], 1 )] -texinfo_documents: List[Tuple[Any, ...]] = [( +texinfo_documents: list[tuple[object, ...]] = [( master_doc, 'restat', 'restat Documentation', author, 'restat', 'One line description of project.', 'Miscellaneous' )] epub_title: str = project -epub_exclude_files: List[str] = ['search.html'] +epub_exclude_files: list[str] = ['search.html'] diff --git a/docs/source/index.rst b/docs/source/index.rst index 23329a7..220f5c3 100755 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -12,7 +12,7 @@ other information that should be provided before the tool is installed. self -|GitHub issues| |Documentation Status| |GitHub contributors| +|GitHub issues| |Documentation Status| |GitHub contributors| |restat_base C checker| |restatdesk CC checker| |restatdesk build checker| |restat toc| .. |GitHub issues| image:: https://img.shields.io/github/issues/electux/restat.svg :target: https://github.com/electux/restat/issues @@ -23,33 +23,168 @@ other information that should be provided before the tool is installed. .. |Documentation Status| image:: https://readthedocs.org/projects/restat/badge/?version=latest :target: https://restat.readthedocs.io/projects/restat/en/latest/?badge=latest +.. |restat_base C checker| image:: https://github.com/electux/restat/actions/workflows/restat_base_c_checker.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_base_c_checker.yml + +.. |restatdesk CC checker| image:: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker.yml + +.. |restatdesk build checker| image:: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker_build.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_desktop_cc_checker_build.yml + +.. |restat toc| image:: https://github.com/electux/restat/actions/workflows/restat_toc.yml/badge.svg + :target: https://github.com/electux/restat/actions/workflows/restat_toc.yml + +System Components +----------------- + +**restat** consists of two primary components: + +1. restat Firmware (``restat_base``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A low-level C firmware designed for Pico RP2040 microcontrollers to actuate, time, and persist relay outputs. + +* **Role**: Actuates 8 mechanical relay channels using high-precision timers and persists configurations directly to onboard Flash memory. +* **Features**: + * Multi-interface Command Dispatcher (Serial, TCP/IP, BLE). + * Variable Execution Plan Parser: Processes complex execution strings concurrently to set states and schedules. + * Flash-Based Plan Persistence: Automatically stores execution plans at a ``1.5 MB`` flash offset (``0x180000``) and restores configurations upon reboot. + * Precise Timing Engine: Millisecond-level accuracy for Timed modes. + * Safety Watchdog & Sound Indicators: Recovery loops coupled with active buzzer signaling. + +2. restatdesk GUI Application (``restatdesk``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A responsive, cross-platform C++ application built on **gtkmm 4** and **GTK 4**. + +* **Role**: Configures, controls, and monitors the relay station in real-time. +* **Features**: + + * Real-Time LED Indicators: High-visibility green status lights showing live channel states. + * Configurable Relay Modes: + + * **Toggle Mode**: Activates or deactivates relays on click. + * **Timer Mode**: Executes timed sequences with flexible starting states (Active = ON on Start, Deactive = OFF on Start). + + * Dynamic Plan Builder: Serializes only active relay states into a single, variable-length plan command to protect relay lifespans. + * Sleek Green-on-Black Dark Mode: Custom CSS styles compiled directly into the binary as GResource packages. + * Multithreaded System Logs: Visualized console output and persistent file logging. + + +Command Interface (restat Protocol) +----------------------------------- + +All commands sent to the ``restat_base`` firmware must be wrapped in start/end markers: ````. + ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| Command | Action | Description | ++=====================================+==================+===================================================================================+ +| ```` | Identify | Returns board identification (e.g. ````) | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Get Version | Returns firmware version (e.g. ````) | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Channel ON | Sets channel ``X`` (1-8) to ON (active) state | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Channel OFF | Sets channel ``X`` (1-8) to OFF (deactive) state | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Timed Channel | Starts timer on channel ``X`` for ``MS`` milliseconds starting ON | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | All ON | Turns all channels ON concurrently | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | All OFF | Turns all channels OFF concurrently | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Binary Mask | Sets all 8 channels to binary state ``MASK`` (e.g. ``10101010``) | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Execute Plan | Sends a variable-length configuration plan containing relay states and saves | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Channel Status | Returns the status string of channel ``X`` | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | All Status | Returns status dump for all channels | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ +| ```` | Reset | Performs soft system reset using watchdog | ++-------------------------------------+------------------+-----------------------------------------------------------------------------------+ + Installation -------------- +------------ + +1. Firmware (``restat_base``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Setup the Raspberry Pi Pico SDK on your host system, then build: + +.. code-block:: bash -Navigate to release `page`_ download and extract release archive. + cd sw/restat_base + mkdir -p build && cd build + cmake .. + make -j$(nproc) -.. _page: https://github.com/electux/restat/releases +Boot the board in BOOTSEL mode and copy the compiled ``restat_base.uf2`` to the Pico mass storage volume. -To install **restat** type the following +2. Desktop Application (``restatdesk``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Ensure all C++23 compiler tools and GTK 4 libraries are installed, then run: .. code-block:: bash - in progress + cd sw/restatdesk/build + make all -Dependencies -------------- +The executable ``restatdesk`` will be ready inside the ``build/`` directory. + +Usage +----- + +1. GUI Panel +~~~~~~~~~~~~ +Launch the desktop client: -**restat** requires next modules and libraries - in progress +.. code-block:: bash + + ./sw/restatdesk/build/restatdesk -Project structure ------------------- +Configure the connection (Serial, TCP/IP, or BLE) in the Settings window, toggle active relay options in the UI, and click **Execute Plan** in the main window or under the ``Command`` menu to transmit changes. -**restat** is based on POP. +2. Test Commands +~~~~~~~~~~~~~~~~ +Connect directly to the station via terminal console or socket connection (e.g. ``minicom`` or ``nc``) and send raw protocol frames: .. code-block:: bash - in progress + # Set channel 1 to ON + + +Dependencies +------------ + +Firmware (``restat_base``) +~~~~~~~~~~~~~~~~~~~~~~~~~~ +* Raspberry Pi Pico SDK (v1.5.0+) +* GCC ARM Embedded Toolchain (``arm-none-eabi-gcc``) +* CMake & GNU Make + +Desktop GUI (``restatdesk``) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +* C++23 compatible compiler (GCC 13+) +* ``gtkmm-4.0`` & ``libgtk-4-dev`` +* ``libserial-dev`` +* ``pkg-config`` +* GNU Make + +Project Structure +----------------- + +The codebase layout is structured as follows: + +* `sw/restat_base/ `_ - Core Pico firmware: + * ``src/command/`` - Dispatcher and frame parser. + * ``src/device/`` - Watchdog, buzzer, relay, and flash persistence drivers. +* `sw/restat_base_tests/ `_ - C++ GoogleTest suite for host-based firmware logic validation. +* `sw/restatdesk/ `_ - GTK 4 client: + * ``com/`` - Serial, TCP, and BLE client layers. + * ``config/`` - File configuration load/store manager. + * ``model/`` - Relay delegates, channel states, and business logic. + * ``view/`` - GUI window tabs, widgets, and GResource styled assets. +* `sw/restatdesk_tests/ `_ - C++ GoogleTest suite for desktop client controllers and helpers. +* `docs/ `_ - Documentation source files. Copyright and licence ---------------------- @@ -64,3 +199,11 @@ Copyright and licence Copyright (C) 2020 - 2024 by `electux.github.io/restat `_ +Lets help and support Raspberry PI && GNOME. + +.. image:: https://raw.githubusercontent.com/electux/restat/master/docs/foundations.png + :alt: Foundations + :width: 192px + :height: 109px + + diff --git a/restat.code-workspace b/restat.code-workspace index 876a149..2b13ffd 100644 --- a/restat.code-workspace +++ b/restat.code-workspace @@ -4,5 +4,16 @@ "path": "." } ], - "settings": {} + "settings": { + "files.exclude": { + "**/*.o": true, + "**/*.lss": true, + "**/core": true, + "**/resources.cc": true, + "**/build/": true, + "**/.built": true, + "**/.depend": true, + "**/Make.dep": true + } + } } \ No newline at end of file diff --git a/sw/.editorconfig b/sw/.editorconfig index ffea4cf..72716a4 100644 --- a/sw/.editorconfig +++ b/sw/.editorconfig @@ -1,3 +1,3 @@ -[**.{c,h,cfg}] +[**.*] indent_style = tab tab_width = 4 diff --git a/sw/restat-desktop/build/Makefile b/sw/restat-desktop/build/Makefile deleted file mode 100644 index 493adf7..0000000 --- a/sw/restat-desktop/build/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -# -# @brief restat-desktop -# @version 1.0.0 -# @date Mon 13 Dec 2021 11:45:04 PM CET -# @company None, free software to use 2021 -# @author Vladimir Roncevic -# - -CC=g++ -RM=rm - -include ccflags.mk -include ldflags.mk -include sources.mk -include objects.mk - -EXECUTABLE=restat-desktop - -all: $(SOURCES) $(EXECUTABLE) - -$(EXECUTABLE): $(OBJECTS) - $(CC) $(LDFLAGS) $(OBJECTS) -o $@ `pkg-config gtkmm-3.0 --libs` - -.cc.o: - $(CC) $(CFLAGS) $< -o $@ `pkg-config gtkmm-3.0 --cflags` - -clean: - $(RM) -rf ../*.o $(EXECUTABLE) diff --git a/sw/restat-desktop/build/ccflags.mk b/sw/restat-desktop/build/ccflags.mk deleted file mode 100644 index ce0af30..0000000 --- a/sw/restat-desktop/build/ccflags.mk +++ /dev/null @@ -1,9 +0,0 @@ -# -# @brief restat-desktop -# @version 1.0.0 -# @date Mon 13 Dec 2021 11:45:04 PM CET -# @company None, free software to use 2021 -# @author Vladimir Roncevic -# - -CFLAGS=-c -Wall diff --git a/sw/restat-desktop/build/ldflags.mk b/sw/restat-desktop/build/ldflags.mk deleted file mode 100644 index 3dd0f64..0000000 --- a/sw/restat-desktop/build/ldflags.mk +++ /dev/null @@ -1,9 +0,0 @@ -# -# @brief restat-desktop -# @version 1.0.0 -# @date Mon 13 Dec 2021 11:45:04 PM CET -# @company None, free software to use 2021 -# @author Vladimir Roncevic -# - -LDFLAGS= diff --git a/sw/restat-desktop/build/objects.mk b/sw/restat-desktop/build/objects.mk deleted file mode 100644 index 851491b..0000000 --- a/sw/restat-desktop/build/objects.mk +++ /dev/null @@ -1,9 +0,0 @@ -# -# @brief restat-desktop -# @version 1.0.0 -# @date Mon 13 Dec 2021 11:45:04 PM CET -# @company None, free software to use 2021 -# @author Vladimir Roncevic -# - -OBJECTS=$(SOURCES:.cc=.o) diff --git a/sw/restat-desktop/build/sources.mk b/sw/restat-desktop/build/sources.mk deleted file mode 100644 index b0908c6..0000000 --- a/sw/restat-desktop/build/sources.mk +++ /dev/null @@ -1,9 +0,0 @@ -# -# @brief restat-desktop -# @version 1.0.0 -# @date Mon 13 Dec 2021 11:45:04 PM CET -# @company None, free software to use 2021 -# @author Vladimir Roncevic -# - -SOURCES=../restat_desktop.cc ../main.cc diff --git a/sw/restat-desktop/main.cc b/sw/restat-desktop/main.cc deleted file mode 100644 index ffcd131..0000000 --- a/sw/restat-desktop/main.cc +++ /dev/null @@ -1,27 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ -/* - * main.cc - * Copyright (C) 2021 Vladimir Roncevic - * - * restat is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * restat 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ -#include "restat_desktop.h" -#include - -int main(int argc, char *argv[]) -{ - auto app = Gtk::Application::create(argc, argv, "org.gtkmm.restat"); - Restat window_instance; - return app->run(window_instance); -} diff --git a/sw/restat-desktop/restat_desktop.cc b/sw/restat-desktop/restat_desktop.cc deleted file mode 100644 index c54cf28..0000000 --- a/sw/restat-desktop/restat_desktop.cc +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ -/* - * restat_desktop.cc - * Copyright (C) 2021 Vladimir Roncevic - * - * restat is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * restat 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ -#include -#include "restat_desktop.h" - -Restat::Restat() -{ - this->set_title(RESTAT_TITLE); - this->set_border_width(RESTAT_BORDER_WIDTH); - this->add(this->main_grid); -} - -Restat::~Restat() -{ - std::cout << "Clean up code/data" << std::endl; -} diff --git a/sw/restat-desktop/restat_desktop.h b/sw/restat-desktop/restat_desktop.h deleted file mode 100644 index 5387525..0000000 --- a/sw/restat-desktop/restat_desktop.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ -/* - * restat_desktop.h - * Copyright (C) 2021 Vladimir Roncevic - * - * restat is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * restat 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef RESTAT_DESKTOP_H -#define RESTAT_DESKTOP_H - -#include -#include - -#define RESTAT_TITLE "restat" -#define RESTAT_VERSION "1.0.0" -#define RESTAT_BORDER_WIDTH 10 - -class Restat : public Gtk::Window -{ -public: - Restat(); - ~Restat(); - -protected: - Gtk::Grid main_grid; -}; - -#endif diff --git a/sw/restat-device0/CMakeLists.txt b/sw/restat-device0/CMakeLists.txt deleted file mode 100644 index 8a6008e..0000000 --- a/sw/restat-device0/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -# -# @brief restat main entry point for build process -# @version v1.0.3 -# @date 2021-12-14 -# @author Vladimir Roncevic -# - -# Setup CMake version and RPI Pico SDK import -cmake_minimum_required(VERSION 3.12) -include(pico_sdk_import.cmake) - -# Setup project info -project(restat-device0 C CXX ASM) -set(CMAKE_PROJECT_VERSION 1.0.0) -set(CMAKE_C_STANDARD 11) -set(CMAKE_CXX_STANDARD 17) -set(PRO_PATH ${PROJECT_SOURCE_DIR}) - -# Initialize the SDK -pico_sdk_init() - -# Setup project url -include(pro_auto_set_url.cmake) - -# Add source directory -add_subdirectory(src) - diff --git a/sw/restat-device0/src/CMakeLists.txt b/sw/restat-device0/src/CMakeLists.txt deleted file mode 100644 index f2a066c..0000000 --- a/sw/restat-device0/src/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -# -# @brief restat setup output files -# @version v1.0.3 -# @date 2021-12-14 -# @author Vladimir Roncevic -# - -# Create executable -add_executable("${CMAKE_PROJECT_NAME}" main.c) - -# Pull in our pico_stdlib which pulls in commonly used features -target_link_libraries("${CMAKE_PROJECT_NAME}" pico_stdlib) - -# Create extra output files map/bin/hex -pico_add_extra_outputs("${CMAKE_PROJECT_NAME}") - -# Add url via pico_set_program_url -pro_auto_set_url("${CMAKE_PROJECT_NAME}") - diff --git a/sw/restat-device0/src/main.c b/sw/restat-device0/src/main.c deleted file mode 100644 index ecf1c0d..0000000 --- a/sw/restat-device0/src/main.c +++ /dev/null @@ -1,37 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ -/* - * main.c - * Copyright (C) 2021 Vladimir Roncevic - * - * restat is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * restat 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program_name. If not, see . - */ - -#include "pico/stdlib.h" - -int main() { -#ifndef PICO_DEFAULT_LED_PIN -#warning blink example requires a board with a regular LED -#else - const uint LED_PIN = PICO_DEFAULT_LED_PIN; - gpio_init(LED_PIN); - gpio_set_dir(LED_PIN, GPIO_OUT); - while (true) { - gpio_put(LED_PIN, 1); - sleep_ms(250); - gpio_put(LED_PIN, 0); - sleep_ms(250); - } -#endif -} - diff --git a/sw/restat-device1/CMakeLists.txt b/sw/restat-device1/CMakeLists.txt deleted file mode 100644 index 0338f96..0000000 --- a/sw/restat-device1/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -# -# @brief restat main entry point for build process -# @version v1.0.3 -# @date 2021-12-14 -# @author Vladimir Roncevic -# - -# Setup CMake version and RPI Pico SDK import -cmake_minimum_required(VERSION 3.12) -include(pico_sdk_import.cmake) - -# Setup project info -project(restat-device1 C CXX ASM) -set(CMAKE_PROJECT_VERSION 1.0.0) -set(CMAKE_C_STANDARD 11) -set(CMAKE_CXX_STANDARD 17) -set(PRO_PATH ${PROJECT_SOURCE_DIR}) - -# Initialize the SDK -pico_sdk_init() - -# Setup project url -include(pro_auto_set_url.cmake) - -# Add source directory -add_subdirectory(src) - diff --git a/sw/restat-device1/pico_sdk_import.cmake b/sw/restat-device1/pico_sdk_import.cmake deleted file mode 100644 index d36d2a9..0000000 --- a/sw/restat-device1/pico_sdk_import.cmake +++ /dev/null @@ -1,97 +0,0 @@ -# -# @brief restat RPI Pico SDK import -# @version v1.0.3 -# @date 2021-12-14 -# @author Vladimir Roncevic -# - -# Checking SDK path -if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH)) - set(PICO_SDK_PATH $ENV{PICO_SDK_PATH}) - message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')") -endif () - -# Checking SDK path fetched from GIT -if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT)) - set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT}) - message( - "Using PICO_SDK_FETCH_FROM_GIT" - "from environment ('${PICO_SDK_FETCH_FROM_GIT}')" - ) -endif () - -if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH)) - set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH}) - message( - "Using PICO_SDK_FETCH_FROM_GIT_PATH" - "from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')" - ) -endif () - -# Setup RPI PICO SDK path -set( - PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the RPI Pi Pico SDK" -) -set( - PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" - CACHE BOOL - "Set to ON to fetch copy of SDK from git if not otherwise locatable" -) -set( - PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" - CACHE FILEPATH "location to download SDK" -) - -# Fetch RPI PI SDK from GitHub -if (NOT PICO_SDK_PATH) - if (PICO_SDK_FETCH_FROM_GIT) - include(FetchContent) - set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR}) - if (PICO_SDK_FETCH_FROM_GIT_PATH) - get_filename_component( - FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" - REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}" - ) - endif () - FetchContent_Declare( - pico_sdk - GIT_REPOSITORY https://github.com/RPIpi/pico-sdk - GIT_TAG master - ) - if (NOT pico_sdk) - message("Downloading RPI Pi Pico SDK") - FetchContent_Populate(pico_sdk) - set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR}) - endif () - set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE}) - else () - message( - FATAL_ERROR - "SDK location was not specified." - "Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT." - ) - endif () -endif () - -get_filename_component( - PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}" -) -if (NOT EXISTS ${PICO_SDK_PATH}) - message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found") -endif () - -set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake) - -# Check RPI PI SDK init configuration -if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE}) - message( - FATAL_ERROR - "Dir '${PICO_SDK_PATH}' does not appear to contain RPI Pi Pico SDK" - ) -endif () - -set( - PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to RPI Pi Pico SDK" FORCE -) - -include(${PICO_SDK_INIT_CMAKE_FILE}) diff --git a/sw/restat-device1/pro_auto_set_url.cmake b/sw/restat-device1/pro_auto_set_url.cmake deleted file mode 100644 index fa80ae1..0000000 --- a/sw/restat-device1/pro_auto_set_url.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# @brief restat setup project url -# @version v1.0.3 -# @date 2021-12-14 -# @author Vladimir Roncevic -# - -# Macro for setup project url -macro(pro_auto_set_url TARGET) - file( - RELATIVE_PATH URL_REL_PATH "${PRO_PATH}" "${CMAKE_CURRENT_LIST_DIR}" - ) - pico_set_program_url(${TARGET} "${URL_REL_PATH}") -endmacro() - diff --git a/sw/restat-device1/src/CMakeLists.txt b/sw/restat-device1/src/CMakeLists.txt deleted file mode 100644 index f2a066c..0000000 --- a/sw/restat-device1/src/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -# -# @brief restat setup output files -# @version v1.0.3 -# @date 2021-12-14 -# @author Vladimir Roncevic -# - -# Create executable -add_executable("${CMAKE_PROJECT_NAME}" main.c) - -# Pull in our pico_stdlib which pulls in commonly used features -target_link_libraries("${CMAKE_PROJECT_NAME}" pico_stdlib) - -# Create extra output files map/bin/hex -pico_add_extra_outputs("${CMAKE_PROJECT_NAME}") - -# Add url via pico_set_program_url -pro_auto_set_url("${CMAKE_PROJECT_NAME}") - diff --git a/sw/restat-device1/src/main.c b/sw/restat-device1/src/main.c deleted file mode 100644 index ecf1c0d..0000000 --- a/sw/restat-device1/src/main.c +++ /dev/null @@ -1,37 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ -/* - * main.c - * Copyright (C) 2021 Vladimir Roncevic - * - * restat is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * restat 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program_name. If not, see . - */ - -#include "pico/stdlib.h" - -int main() { -#ifndef PICO_DEFAULT_LED_PIN -#warning blink example requires a board with a regular LED -#else - const uint LED_PIN = PICO_DEFAULT_LED_PIN; - gpio_init(LED_PIN); - gpio_set_dir(LED_PIN, GPIO_OUT); - while (true) { - gpio_put(LED_PIN, 1); - sleep_ms(250); - gpio_put(LED_PIN, 0); - sleep_ms(250); - } -#endif -} - diff --git a/sw/restat_base/.clang-format b/sw/restat_base/.clang-format new file mode 100644 index 0000000..e89be99 --- /dev/null +++ b/sw/restat_base/.clang-format @@ -0,0 +1,20 @@ +BasedOnStyle: LLVM +IndentWidth: 2 +TabWidth: 2 +UseTab: Never +ColumnLimit: 80 + +# Align function call arguments and parameters to block indent (closing parenthesis on a new line) +AlignAfterOpenBracket: BlockIndent + +# Keep C++11 braced lists formatted nicely +Cpp11BracedListStyle: true + +# Brace wrapping settings (Attach style, open braces on the same line) +BreakBeforeBraces: Attach + +# Other styling preferences +AllowShortBlocksOnASingleLine: Never +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false diff --git a/sw/restat-desktop/.editorconfig b/sw/restat_base/.editorconfig similarity index 100% rename from sw/restat-desktop/.editorconfig rename to sw/restat_base/.editorconfig diff --git a/sw/restat_base/.vscode/c_cpp_properties.json b/sw/restat_base/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..bb410fd --- /dev/null +++ b/sw/restat_base/.vscode/c_cpp_properties.json @@ -0,0 +1,17 @@ +{ + "configurations": [ + { + "name": "restat-base", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [], + "compilerPath": "/usr/bin/arm-none-eabi-gcc", + "intelliSenseMode": "linux-gcc-arm", + "cStandard": "c11", + "cppStandard": "c++17", + "compileCommands": "${workspaceFolder}/compile_commands.json" + } + ], + "version": 4 +} diff --git a/sw/restat_base/.vscode/settings.json b/sw/restat_base/.vscode/settings.json new file mode 100644 index 0000000..0c04c53 --- /dev/null +++ b/sw/restat_base/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.configureOnOpen": false +} diff --git a/sw/restat_base/.vscode/tasks.json b/sw/restat_base/.vscode/tasks.json new file mode 100644 index 0000000..339e2f8 --- /dev/null +++ b/sw/restat_base/.vscode/tasks.json @@ -0,0 +1,26 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "restat-base build", + "type": "shell", + "command": "", + "args": [ + "make", + "--directory=${workspaceFolder}/build" + ], + "problemMatcher": [] + }, + { + "label": "restat-base clean", + "type": "shell", + "command": "", + "args": [ + "make", + "--directory=${workspaceFolder}/build", + "clean" + ], + "problemMatcher": [] + } + ] +} diff --git a/sw/restat_base/CMakeLists.txt b/sw/restat_base/CMakeLists.txt new file mode 100644 index 0000000..865b59c --- /dev/null +++ b/sw/restat_base/CMakeLists.txt @@ -0,0 +1,33 @@ +# +# @brief restat-base main entry point for build process +# @version v1.0.3 +# @date 2021-12-15 +# @author Vladimir Roncevic +# + +# Sets CMake version +cmake_minimum_required(VERSION 3.12) + +# Pico SDK import setup +include(pico_sdk_import.cmake) + +# Sets project info +project(restat-base C CXX ASM) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_PROJECT_VERSION 1.0.0) +set(CMAKE_C_STANDARD 11) +set(CMAKE_CXX_STANDARD 17) +set(PRO_PATH ${PROJECT_SOURCE_DIR}) +set(PICO_BOARD "pico") + +# Initializes the SDK +pico_sdk_init() + +# Adds linker flags +add_link_options(-Wl,-gc-sections,--print-memory-usage) + +# Sets project url +include(pro_auto_set_url.cmake) + +# Adds source directory +add_subdirectory(src) diff --git a/sw/restat-device0/pico_sdk_import.cmake b/sw/restat_base/pico_sdk_import.cmake similarity index 96% rename from sw/restat-device0/pico_sdk_import.cmake rename to sw/restat_base/pico_sdk_import.cmake index d36d2a9..5acd121 100644 --- a/sw/restat-device0/pico_sdk_import.cmake +++ b/sw/restat_base/pico_sdk_import.cmake @@ -1,10 +1,12 @@ # -# @brief restat RPI Pico SDK import +# @brief restat-base RPI Pico SDK import # @version v1.0.3 -# @date 2021-12-14 +# @date 2021-12-15 # @author Vladimir Roncevic # +set(PICO_SDK_PATH "/opt/pico/pico-sdk") + # Checking SDK path if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH)) set(PICO_SDK_PATH $ENV{PICO_SDK_PATH}) diff --git a/sw/restat-device0/pro_auto_set_url.cmake b/sw/restat_base/pro_auto_set_url.cmake similarity index 82% rename from sw/restat-device0/pro_auto_set_url.cmake rename to sw/restat_base/pro_auto_set_url.cmake index fa80ae1..c7f5c96 100644 --- a/sw/restat-device0/pro_auto_set_url.cmake +++ b/sw/restat_base/pro_auto_set_url.cmake @@ -1,7 +1,7 @@ # -# @brief restat setup project url +# @brief restat-base setup project url # @version v1.0.3 -# @date 2021-12-14 +# @date 2021-12-15 # @author Vladimir Roncevic # @@ -12,4 +12,3 @@ macro(pro_auto_set_url TARGET) ) pico_set_program_url(${TARGET} "${URL_REL_PATH}") endmacro() - diff --git a/sw/restat_base/restat-base.code-workspace b/sw/restat_base/restat-base.code-workspace new file mode 100644 index 0000000..e80851b --- /dev/null +++ b/sw/restat_base/restat-base.code-workspace @@ -0,0 +1,19 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": { + "clangd.arguments": [ + "--query-driver=/usr/bin/arm-none-eabi-*" + ], + "files.exclude": { + "**/*.o": true, + "**/.built": true, + "**/.depend": true, + "**/Make.dep": true, + "**/build/": true + } + } +} diff --git a/sw/restat_base/src/CMakeLists.txt b/sw/restat_base/src/CMakeLists.txt new file mode 100644 index 0000000..8ac6de8 --- /dev/null +++ b/sw/restat_base/src/CMakeLists.txt @@ -0,0 +1,43 @@ +# +# @brief restat-base setup output files +# @version v1.0.3 +# @date 2021-12-15 +# @author Vladimir Roncevic +# + +# Prepares PIO target for WS2812 (headers and implementation) +pico_simple_hardware_target(pio) + +# Enable verbose logging globally +add_compile_definitions(VERBOSE) + +# Adds sub-structure includes +include_directories(.) +include_directories(io) +include_directories(ws2812) +include_directories(device) +include_directories(command) + +# Adds sub-structure sources +add_subdirectory(io) +add_subdirectory(ws2812) +add_subdirectory(device) +add_subdirectory(command) + +# Sets executable +add_executable("${CMAKE_PROJECT_NAME}" main.c) + +# Enables USB output +pico_enable_stdio_usb("${CMAKE_PROJECT_NAME}" 1) + +# Disables UART output +pico_enable_stdio_uart("${CMAKE_PROJECT_NAME}" 0) + +# Links all libraries +target_link_libraries("${CMAKE_PROJECT_NAME}" command device io ws2812) + +# Creates extra output files map/bin/hex +pico_add_extra_outputs("${CMAKE_PROJECT_NAME}") + +# Adds URL via pico_set_program_url +pro_auto_set_url("${CMAKE_PROJECT_NAME}") diff --git a/sw/restat_base/src/command/CMakeLists.txt b/sw/restat_base/src/command/CMakeLists.txt new file mode 100644 index 0000000..00311aa --- /dev/null +++ b/sw/restat_base/src/command/CMakeLists.txt @@ -0,0 +1,9 @@ +# +# @brief command library setup +# @version v1.0.0 +# @date 2026-08-21 +# + +add_library(command parser.c command_tbl.c) +target_include_directories(command PUBLIC .) +target_link_libraries(command device pico_stdlib) diff --git a/sw/restat_base/src/command/command_tbl.c b/sw/restat_base/src/command/command_tbl.c new file mode 100644 index 0000000..2f84f15 --- /dev/null +++ b/sw/restat_base/src/command/command_tbl.c @@ -0,0 +1,289 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * command_tbl.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char *const RESTAT_VERSION = "restat v1.0.0"; +static const char *const RESTAT_BOARD_ID = "rs:333:2023:0"; + +static const uint8_t STATUS_LED_DEFAULT_VAL = 255; + +static const char CMD_CHANNEL_MIN_CHAR = '1'; +static const char CMD_CHANNEL_MAX_CHAR = '8'; +static const size_t CMD_CHANNEL_CHAR_INDEX = 6; + +static const size_t CMD_TIMER_ARGS_OFFSET = 12; +static const size_t CMD_PULSE_ARGS_OFFSET = 14; +static const size_t CMD_BLINK_ARGS_OFFSET = 14; +static const size_t CMD_MASK_ARGS_OFFSET = 12; + +static const size_t CMD_MASK_SUFFIX_OFFSET = 20; + +static const size_t CMD_PREFIX_CH_LEN = 6; +static const char *const CMD_PREFIX_CH = "rs#ch#"; + +static const size_t CMD_TMR_LEN = 5; +static const char *const CMD_TMR = "#tmr#"; + +static const size_t CMD_PULSE_LEN = 7; +static const char *const CMD_PULSE = "#pulse#"; + +static const size_t CMD_BLINK_LEN = 7; +static const char *const CMD_BLINK = "#blink#"; + +static const char *const CMD_STAT_SUFFIX = "#stat#end"; + +static const size_t CMD_PREFIX_MASK_LEN = 12; +static const char *const CMD_PREFIX_MASK = "rs#all#mask#"; + +static const char *const CMD_SUFFIX_END = "#end"; + +typedef void (*cmd_handler_t)(const char *cmd_str); + +typedef struct { + const char *pattern; + cmd_handler_t handler; +} command_entry_t; + +static void cmd_handle_board_id(const char *cmd_str) { + (void)cmd_str; + printf("", RESTAT_BOARD_ID); +} + +static void cmd_handle_version(const char *cmd_str) { + (void)cmd_str; + printf("", RESTAT_VERSION); +} + +static void cmd_handle_all_channels(const char *cmd_str) { + bool on = (strstr(cmd_str, "#on#") != NULL); + + relay_set_all(on); + if (on) { + status_led_write( + STATUS_LED_DEFAULT_VAL, STATUS_LED_DEFAULT_VAL, STATUS_LED_DEFAULT_VAL + ); + } else { + status_led_write(0, 0, 0); + } + printf("", on ? "on" : "off"); +} + +static void cmd_handle_channel(const char *cmd_str) { + char ch_char = cmd_str[CMD_CHANNEL_CHAR_INDEX]; + uint32_t channel = ch_char - CMD_CHANNEL_MIN_CHAR; + bool on = (strstr(cmd_str, "#on#") != NULL); + + if (channel < RELAY_NUM_CHANNELS) { + relay_set(channel, on); + printf("", ch_char, on ? "on" : "off"); + } +} + +static void cmd_handle_timer(const char *cmd_str) { + char ch_char = cmd_str[CMD_CHANNEL_CHAR_INDEX]; + uint32_t channel = ch_char - CMD_CHANNEL_MIN_CHAR; + uint32_t milliseconds = 0; + + if (sscanf(cmd_str + CMD_TIMER_ARGS_OFFSET, "%u#end", &milliseconds) == 1) { + if (channel < RELAY_NUM_CHANNELS) { + relay_start_timer(channel, milliseconds, true); + printf( + "", ch_char, milliseconds + ); + } + } +} + +static void cmd_handle_plan(char *cmd_str) { + // Persist the original plan string first + persist_save_plan(cmd_str); + + // Parse command: "rs#all#plan#ch#1#on#ch#3#tmron#500#end" + char *token = strtok(cmd_str, "#"); // "rs" + if (!token) return; + token = strtok(NULL, "#"); // "all" + if (!token) return; + token = strtok(NULL, "#"); // "plan" + if (!token) return; + + while (1) { + token = strtok(NULL, "#"); // "ch" or "end" + if (!token || strcmp(token, "end") == 0) { + break; + } + + if (strcmp(token, "ch") == 0) { + token = strtok(NULL, "#"); // index + if (!token) break; + uint32_t channel = (uint32_t)(atoi(token) - 1); + + token = strtok(NULL, "#"); // mode: "on", "off", "tmron", "tmroff" + if (!token) break; + + if (strcmp(token, "off") == 0) { + relay_set(channel, false); + } else if (strcmp(token, "on") == 0) { + relay_set(channel, true); + } else if (strcmp(token, "tmron") == 0) { + token = strtok(NULL, "#"); + if (token) { + uint32_t duration_ms = (uint32_t)atoi(token); + relay_start_timer(channel, duration_ms, true); + } + } else if (strcmp(token, "tmroff") == 0) { + token = strtok(NULL, "#"); + if (token) { + uint32_t duration_ms = (uint32_t)atoi(token); + relay_start_timer(channel, duration_ms, false); + } + } + } + } + + printf(""); +} + +static void cmd_handle_mask(const char *cmd_str) { + for (uint32_t i = 0; i < RELAY_NUM_CHANNELS; i++) { + char bit = cmd_str[CMD_MASK_ARGS_OFFSET + i]; + bool on = (bit == '1'); + relay_set(i, on); + } + printf( + "", cmd_str + CMD_MASK_ARGS_OFFSET + ); +} + +static void cmd_handle_reset(const char *cmd_str) { + (void)cmd_str; + printf(""); + fflush(stdout); + buzzer_beep_stop(); + watchdog_reboot(0, 0, 0); +} + +static void cmd_handle_channel_status(const char *cmd_str) { + char ch_char = cmd_str[CMD_CHANNEL_CHAR_INDEX]; + uint32_t channel = ch_char - CMD_CHANNEL_MIN_CHAR; + if (channel < RELAY_NUM_CHANNELS) { + char status_buf[64]; + relay_get_status(channel, status_buf, sizeof(status_buf)); + printf("", status_buf); + } +} + +static void cmd_handle_all_status(const char *cmd_str) { + (void)cmd_str; + char all_status_buf[256] = "channels: "; + uint32_t offset = 10; + for (uint32_t i = 0; i < RELAY_NUM_CHANNELS; i++) { + char status_buf[48]; + relay_get_status(i, status_buf, sizeof(status_buf)); + const char *state_str = strstr(status_buf, "ON") ? "ON" : "OFF"; + int written = snprintf( + all_status_buf + offset, sizeof(all_status_buf) - offset, "%u:%s ", + i + 1, state_str + ); + if (written > 0) { + offset += (uint32_t)written; + } + } + printf("", all_status_buf); +} + +static const command_entry_t command_tbl[] = { + {"rs#ch#1#on#end", cmd_handle_channel}, + {"rs#ch#1#off#end", cmd_handle_channel}, + {"rs#ch#2#on#end", cmd_handle_channel}, + {"rs#ch#2#off#end", cmd_handle_channel}, + {"rs#ch#3#on#end", cmd_handle_channel}, + {"rs#ch#3#off#end", cmd_handle_channel}, + {"rs#ch#4#on#end", cmd_handle_channel}, + {"rs#ch#4#off#end", cmd_handle_channel}, + {"rs#ch#5#on#end", cmd_handle_channel}, + {"rs#ch#5#off#end", cmd_handle_channel}, + {"rs#ch#6#on#end", cmd_handle_channel}, + {"rs#ch#6#off#end", cmd_handle_channel}, + {"rs#ch#7#on#end", cmd_handle_channel}, + {"rs#ch#7#off#end", cmd_handle_channel}, + {"rs#ch#8#on#end", cmd_handle_channel}, + {"rs#ch#8#off#end", cmd_handle_channel}, + {"rs#all#on#end", cmd_handle_all_channels}, + {"rs#all#off#end", cmd_handle_all_channels}, + {"rs#all#stat#end", cmd_handle_all_status}, + {"rs#sys#reset#end", cmd_handle_reset}, + {"rs#sys#id#end", cmd_handle_board_id}, + {"rs#sys#version#end", cmd_handle_version}, +}; + +static const size_t command_tbl_size = + sizeof(command_tbl) / sizeof(command_tbl[0]); + +void command_dispatch(const char *cmd_str) { + // Check for plan commands: "rs#all#plan#..." + if (strncmp(cmd_str, "rs#all#plan#", 12) == 0) { + char local_buf[256]; + strncpy(local_buf, cmd_str, sizeof(local_buf) - 1); + local_buf[sizeof(local_buf) - 1] = '\0'; + cmd_handle_plan(local_buf); + return; + } + + // Check for timer commands: "rs#ch#X#tmr#Y#end" + if (strncmp(cmd_str, CMD_PREFIX_CH, CMD_PREFIX_CH_LEN) == 0 && + cmd_str[CMD_CHANNEL_CHAR_INDEX] >= CMD_CHANNEL_MIN_CHAR && + cmd_str[CMD_CHANNEL_CHAR_INDEX] <= CMD_CHANNEL_MAX_CHAR && + strncmp(cmd_str + CMD_CHANNEL_CHAR_INDEX + 1, CMD_TMR, CMD_TMR_LEN) == + 0) { + cmd_handle_timer(cmd_str); + return; + } + + // Check for channel status commands: "rs#ch#X#stat#end" + if (strncmp(cmd_str, CMD_PREFIX_CH, CMD_PREFIX_CH_LEN) == 0 && + cmd_str[CMD_CHANNEL_CHAR_INDEX] >= CMD_CHANNEL_MIN_CHAR && + cmd_str[CMD_CHANNEL_CHAR_INDEX] <= CMD_CHANNEL_MAX_CHAR && + strcmp(cmd_str + CMD_CHANNEL_CHAR_INDEX + 1, CMD_STAT_SUFFIX) == 0) { + cmd_handle_channel_status(cmd_str); + return; + } + + // Check for mask commands: "rs#all#mask#10101010#end" + if (strncmp(cmd_str, CMD_PREFIX_MASK, CMD_PREFIX_MASK_LEN) == 0 && + strcmp(cmd_str + CMD_MASK_SUFFIX_OFFSET, CMD_SUFFIX_END) == 0) { + cmd_handle_mask(cmd_str); + return; + } + + for (size_t i = 0; i < command_tbl_size; i++) { + if (strcmp(cmd_str, command_tbl[i].pattern) == 0) { + command_tbl[i].handler(cmd_str); + return; + } + } +} diff --git a/sw/restat_base/src/command/dispatcher.h b/sw/restat_base/src/command/dispatcher.h new file mode 100644 index 0000000..dca9c1f --- /dev/null +++ b/sw/restat_base/src/command/dispatcher.h @@ -0,0 +1,35 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * dispatcher.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief Dispatches a parsed command string to its registered handler +/// +/// Matches the input string against the command registration table. +/// +/// @param cmd_str [in] The null-terminated command string to route +void command_dispatch(const char *cmd_str); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base/src/command/parser.c b/sw/restat_base/src/command/parser.c new file mode 100644 index 0000000..289e328 --- /dev/null +++ b/sw/restat_base/src/command/parser.c @@ -0,0 +1,80 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * parser.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#include +#include + +typedef enum { PARSER_STATE_IDLE, PARSER_STATE_RECEIVING } parser_state_t; + +static parser_state_t parser_state = PARSER_STATE_IDLE; +static uint32_t parser_idx = 0; +static const uint32_t PARSER_TIMEOUT_US = 0; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Processes a single character inside the parsing state machine +/// +/// @param c [in] Character to process +/// @param buf [out] Destination buffer to store parsed command +/// @param max_len [in] Maximum capacity of the destination buffer +/// @return True if a complete command frame was successfully parsed, else false +static bool parser_process_char(char c, char *buf, uint32_t max_len) { + if (c == '\r' || c == '\n') { + return false; + } + + if (c == '<') { + parser_state = PARSER_STATE_RECEIVING; + parser_idx = 0; + return false; + } + + if (parser_state == PARSER_STATE_RECEIVING) { + if (c == '>') { + buf[parser_idx] = '\0'; + parser_state = PARSER_STATE_IDLE; + parser_idx = 0; + return true; + } + + if (parser_idx < (max_len - 1)) { + buf[parser_idx++] = c; + } else { + parser_state = PARSER_STATE_IDLE; + parser_idx = 0; + } + } + + return false; +} + +//////////////////////////////////////////////////////////////////////////// +/// @brief Reads and parses command requests from the input stream +/// +/// @param buf [out] Destination buffer to store parsed command +/// @param max_len [in] Maximum capacity of the destination buffer +/// @return True if a command was parsed, else false +bool parser_get_command(char *buf, uint32_t max_len) { + int16_t rc = getchar_timeout_us(PARSER_TIMEOUT_US); + while (rc != PICO_ERROR_TIMEOUT) { + if (parser_process_char((char)rc, buf, max_len)) { + return true; + } + rc = getchar_timeout_us(PARSER_TIMEOUT_US); + } + return false; +} diff --git a/sw/restat_base/src/command/parser.h b/sw/restat_base/src/command/parser.h new file mode 100644 index 0000000..2ff9f86 --- /dev/null +++ b/sw/restat_base/src/command/parser.h @@ -0,0 +1,41 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * parser.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief Fetches and parses a command frame from the USB CDC interface +/// +/// Accumulates incoming characters. Only returns true and populates `buf` +/// when a complete frame enclosed in '<' and '>' markers is received. +/// +/// @param buf [out] Destination buffer to store parsed command +/// @param max_len [in] Maximum capacity of the destination buffer +/// @return True if a complete command frame was successfully parsed, else false +bool parser_get_command(char *buf, uint32_t max_len); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base/src/device/CMakeLists.txt b/sw/restat_base/src/device/CMakeLists.txt new file mode 100644 index 0000000..764702b --- /dev/null +++ b/sw/restat_base/src/device/CMakeLists.txt @@ -0,0 +1,9 @@ +# +# @brief device library setup +# @version v1.0.0 +# @date 2026-08-21 +# + +add_library(device relay.c buzzer.c status_led.c persist.c) +target_include_directories(device PUBLIC .) +target_link_libraries(device io ws2812 pico_stdlib hardware_pio hardware_flash) diff --git a/sw/restat_base/src/device/buzzer.c b/sw/restat_base/src/device/buzzer.c new file mode 100644 index 0000000..1d22818 --- /dev/null +++ b/sw/restat_base/src/device/buzzer.c @@ -0,0 +1,73 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * buzzer.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#include +#include +#include + +static const uint32_t BUZZER_PIN = 6; +static const uint32_t BUZZER_PWM_CHAN = 0; // PWM_CHAN_A + +static const uint16_t BUZZER_BEEP_START_DUTY = 80; +static const uint32_t BUZZER_BEEP_START_MS = 100; + +static const uint16_t BUZZER_BEEP_CHANGED_DUTY = 80; +static const uint32_t BUZZER_BEEP_CHANGED_MS = 50; + +static const uint16_t BUZZER_BEEP_STOP_DUTY = 100; +static const uint32_t BUZZER_BEEP_STOP_MS = 300; + +static const uint64_t US_TO_MS = 1000; + +bool buzzer_init(void) { + io_pwm_init(BUZZER_PIN, BUZZER_PWM_CHAN); + io_pwm_write(BUZZER_PIN, BUZZER_PWM_CHAN, 0); + return true; +} + +void buzzer_write(uint16_t value) { + io_pwm_write(BUZZER_PIN, BUZZER_PWM_CHAN, value); +} + +void buzzer_beep_start(void) { + buzzer_write(BUZZER_BEEP_START_DUTY); + sleep_ms(BUZZER_BEEP_START_MS); + buzzer_write(0); +} + +static uint64_t buzzer_off_time = 0; + +void buzzer_beep_changed(void) { + buzzer_write(BUZZER_BEEP_CHANGED_DUTY); + buzzer_off_time = time_us_64() / US_TO_MS + BUZZER_BEEP_CHANGED_MS; +} + +void buzzer_tick(void) { + if (buzzer_off_time > 0) { + if ((time_us_64() / US_TO_MS) >= buzzer_off_time) { + buzzer_write(0); + buzzer_off_time = 0; + } + } +} + +void buzzer_beep_stop(void) { + buzzer_write(BUZZER_BEEP_STOP_DUTY); + sleep_ms(BUZZER_BEEP_STOP_MS); + buzzer_write(0); +} diff --git a/sw/restat_base/src/device/buzzer.h b/sw/restat_base/src/device/buzzer.h new file mode 100644 index 0000000..aa29fac --- /dev/null +++ b/sw/restat_base/src/device/buzzer.h @@ -0,0 +1,58 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * buzzer.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief Initializes PWM for the buzzer +/// +/// @return True if initialization succeeded, false otherwise +bool buzzer_init(void); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Writes a duty cycle level to the buzzer PWM channel +/// +/// @param value [in] PWM level value (0 to 100) +void buzzer_write(uint16_t value); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Triggers a short startup notification beep +void buzzer_beep_start(void); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Triggers a short non-blocking notification beep for state changes +void buzzer_beep_changed(void); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Polling tick function to turn off buzzer non-blockingly +void buzzer_tick(void); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Triggers a longer shutdown/reset beep (blocking, pre-reset) +void buzzer_beep_stop(void); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base/src/device/persist.c b/sw/restat_base/src/device/persist.c new file mode 100644 index 0000000..8392060 --- /dev/null +++ b/sw/restat_base/src/device/persist.c @@ -0,0 +1,58 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * persist.c + * Copyright (C) 2026 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ +#include +#include +#include +#include + +#define FLASH_TARGET_OFFSET (1536 * 1024) // 1.5 MB offset + +void persist_save_plan(const char *plan_str) { + // Prepare a page buffer (256 bytes) to write + uint8_t write_buf[FLASH_PAGE_SIZE]; + memset(write_buf, 0, sizeof(write_buf)); + + // Copy plan_str to buffer + strncpy((char *)write_buf, plan_str, sizeof(write_buf) - 1); + + // Disable interrupts before erasing and writing + uint32_t ints = save_and_disable_interrupts(); + + // Erase one sector (4096 bytes) at the target offset + flash_range_erase(FLASH_TARGET_OFFSET, FLASH_SECTOR_SIZE); + + // Write one page (256 bytes) + flash_range_program(FLASH_TARGET_OFFSET, write_buf, FLASH_PAGE_SIZE); + + // Restore interrupts + restore_interrupts(ints); +} + +bool persist_load_plan(char *buf, size_t max_len) { + // Flash is mapped to memory starting at XIP_BASE (0x10000000) + const uint8_t *flash_target_contents = (const uint8_t *)(XIP_BASE + FLASH_TARGET_OFFSET); + + // Check if it starts with a valid pattern + if (strncmp((const char *)flash_target_contents, "rs#all#plan#", 12) == 0) { + strncpy(buf, (const char *)flash_target_contents, max_len - 1); + buf[max_len - 1] = '\0'; + return true; + } + return false; +} diff --git a/sw/restat_base/src/device/persist.h b/sw/restat_base/src/device/persist.h new file mode 100644 index 0000000..6d86ae9 --- /dev/null +++ b/sw/restat_base/src/device/persist.h @@ -0,0 +1,31 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * persist.h + * Copyright (C) 2026 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ +#pragma once + +#include +#include +#include + +#define PERSIST_MAX_LEN 256 + +// Save a plan string to flash +void persist_save_plan(const char *plan_str); + +// Load the plan string from flash. Returns true if valid plan was found. +bool persist_load_plan(char *buf, size_t max_len); diff --git a/sw/restat_base/src/device/relay.c b/sw/restat_base/src/device/relay.c new file mode 100644 index 0000000..01eb8b5 --- /dev/null +++ b/sw/restat_base/src/device/relay.c @@ -0,0 +1,137 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * relay.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#include +#include +#include +#include +#include + +static const uint32_t relay_pins[RELAY_NUM_CHANNELS] = { + 21, 20, 19, 18, 17, 16, 15, 14, +}; + +static const uint64_t US_TO_MS = 1000; +static const uint64_t MS_TO_SEC = 1000; + +typedef struct { + relay_mode_t mode; + bool active; + uint64_t start_time; + uint64_t duration_ms; + bool start_on; +} relay_state_internal_t; + +static relay_state_internal_t relay_states[RELAY_NUM_CHANNELS]; +static bool current_phys_state[RELAY_NUM_CHANNELS] = {false}; + +bool relay_init(void) { + for (int i = 0; i < RELAY_NUM_CHANNELS; i++) { + io_gpio_init(relay_pins[i], true); + io_gpio_write(relay_pins[i], true); + current_phys_state[i] = false; + + relay_states[i].mode = RELAY_MODE_TOGGLE; + relay_states[i].active = false; + relay_states[i].start_time = 0; + relay_states[i].duration_ms = 0; + relay_states[i].start_on = false; + } + return true; +} + +static void relay_set_phys(uint32_t channel, bool state) { + if (channel < RELAY_NUM_CHANNELS) { + if (current_phys_state[channel] != state) { + current_phys_state[channel] = state; + io_gpio_write(relay_pins[channel], !state); + buzzer_beep_changed(); + } + } +} + +void relay_set(uint32_t channel, bool state) { + if (channel < RELAY_NUM_CHANNELS) { + relay_states[channel].active = false; + relay_states[channel].mode = RELAY_MODE_TOGGLE; + relay_set_phys(channel, state); + } +} + +void relay_set_all(bool state) { + for (int i = 0; i < RELAY_NUM_CHANNELS; i++) { + relay_set(i, state); + } +} + +void relay_start_timer(uint32_t channel, uint32_t duration_ms, bool start_on) { + if (channel < RELAY_NUM_CHANNELS) { + relay_states[channel].mode = RELAY_MODE_TIMER; + relay_states[channel].active = true; + relay_states[channel].start_time = time_us_64() / US_TO_MS; + relay_states[channel].duration_ms = (uint64_t)duration_ms; + relay_states[channel].start_on = start_on; + relay_set_phys(channel, start_on); + } +} + +void relay_tick(void) { + uint64_t now_ms = time_us_64() / US_TO_MS; + for (uint32_t i = 0; i < RELAY_NUM_CHANNELS; i++) { + if (!relay_states[i].active) { + continue; + } + + if (relay_states[i].mode == RELAY_MODE_TIMER) { + if (now_ms - relay_states[i].start_time >= relay_states[i].duration_ms) { + bool next_state = !relay_states[i].start_on; + relay_set_phys(i, next_state); + relay_states[i].active = false; + relay_states[i].mode = RELAY_MODE_TOGGLE; + printf("", i + 1, next_state ? "on" : "off"); + fflush(stdout); + } + } + } +} + +void relay_get_status(uint32_t channel, char *buf, uint32_t max_len) { + if (channel >= RELAY_NUM_CHANNELS) { + snprintf(buf, max_len, "invalid channel"); + return; + } + + const char *phys_state = current_phys_state[channel] ? "ON" : "OFF"; + if (!relay_states[channel].active) { + snprintf(buf, max_len, "Channel %u: %s (Toggle)", channel + 1, phys_state); + } else { + switch (relay_states[channel].mode) { + case RELAY_MODE_TIMER: { + uint64_t elapsed = time_us_64() / US_TO_MS - relay_states[channel].start_time; + uint64_t remaining = (relay_states[channel].duration_ms > elapsed) ? + (relay_states[channel].duration_ms - elapsed) : 0; + snprintf(buf, max_len, "Channel %u: %s (Timer, rem: %llums)", + channel + 1, phys_state, remaining); + break; + } + default: + snprintf(buf, max_len, "Channel %u: %s", channel + 1, phys_state); + break; + } + } +} diff --git a/sw/restat_base/src/device/relay.h b/sw/restat_base/src/device/relay.h new file mode 100644 index 0000000..af166f8 --- /dev/null +++ b/sw/restat_base/src/device/relay.h @@ -0,0 +1,72 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * relay.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief Total number of relay channels +enum { RELAY_NUM_CHANNELS = 8 }; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Relay modes +typedef enum { + RELAY_MODE_TOGGLE, + RELAY_MODE_TIMER +} relay_mode_t; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Initializes all relay GPIO channels +/// +/// @return True if initialization succeeded, false otherwise +bool relay_init(void); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Sets the state of a specific relay channel +/// +/// @param channel [in] Relay channel index (0 to RELAY_NUM_CHANNELS - 1) +/// @param state [in] True to turn ON, false to turn OFF +void relay_set(uint32_t channel, bool state); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Sets the state of all relay channels simultaneously +/// +/// @param state [in] True to turn all ON, false to turn all OFF +void relay_set_all(bool state); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Starts a timer mode on a relay channel +void relay_start_timer(uint32_t channel, uint32_t duration_ms, bool start_on); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Non-blocking tick routine for relay timings +void relay_tick(void); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Returns a status string for the given relay channel +void relay_get_status(uint32_t channel, char *buf, uint32_t max_len); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base/src/device/status_led.c b/sw/restat_base/src/device/status_led.c new file mode 100644 index 0000000..3ccb62e --- /dev/null +++ b/sw/restat_base/src/device/status_led.c @@ -0,0 +1,49 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * status_led.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#include +#include +#include + +static const uint32_t STATUS_LED_PIN = 13; +static const uint32_t STATUS_LED_PIO_SM = 0; +static const uint32_t STATUS_LED_FREQ = 800000; +static const uint32_t PIXEL_RGB_SHIFT_R = 8; +static const uint32_t PIXEL_RGB_SHIFT_G = 16; +static const uint32_t PIO_SM_PUT_SHIFT = 8; + +bool status_led_init(void) { + ws2812_init init = { + .pio = pio0, + .sm = STATUS_LED_PIO_SM, + .offset = pio_add_program(pio0, &ws2812_program), + .pin = STATUS_LED_PIN, + .freq = STATUS_LED_FREQ, + .rgbw = false}; + + ws2812_program_init(&init); + status_led_write(0, 0, 0); + return true; +} + +void status_led_write(uint8_t red, uint8_t green, uint8_t blue) { + uint pixel_rgb = ((uint)(red) << PIXEL_RGB_SHIFT_R) | + ((uint)(green) << PIXEL_RGB_SHIFT_G) | + ((uint)(blue)); + pio_sm_put_blocking(pio0, STATUS_LED_PIO_SM, pixel_rgb << PIO_SM_PUT_SHIFT); +} diff --git a/sw/restat_base/src/device/status_led.h b/sw/restat_base/src/device/status_led.h new file mode 100644 index 0000000..ad4e8b9 --- /dev/null +++ b/sw/restat_base/src/device/status_led.h @@ -0,0 +1,44 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * status_led.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief Initializes PIO state machine for the WS2812 status LED +/// +/// @return True if initialization succeeded, false otherwise +bool status_led_init(void); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Writes red, green, and blue values to the WS2812 status LED +/// +/// @param red [in] Red component intensity (0 to 255) +/// @param green [in] Green component intensity (0 to 255) +/// @param blue [in] Blue component intensity (0 to 255) +void status_led_write(uint8_t red, uint8_t green, uint8_t blue); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base/src/io/CMakeLists.txt b/sw/restat_base/src/io/CMakeLists.txt new file mode 100644 index 0000000..001df28 --- /dev/null +++ b/sw/restat_base/src/io/CMakeLists.txt @@ -0,0 +1,9 @@ +# +# @brief io library setup +# @version v1.0.0 +# @date 2026-08-21 +# + +add_library(io io_gpio.c io_pwm.c) +target_include_directories(io PUBLIC .) +target_link_libraries(io pico_stdlib hardware_gpio hardware_pwm) diff --git a/sw/restat_base/src/io/io_gpio.c b/sw/restat_base/src/io/io_gpio.c new file mode 100644 index 0000000..c18a9cf --- /dev/null +++ b/sw/restat_base/src/io/io_gpio.c @@ -0,0 +1,38 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * io_gpio.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#include +#include +#include + +void io_gpio_init(uint32_t pin, bool is_output) { + gpio_init(pin); + if (is_output) { + gpio_set_dir(pin, GPIO_OUT); + } else { + gpio_set_dir(pin, GPIO_IN); + } +} + +void io_gpio_write(uint32_t pin, bool value) { + gpio_put(pin, value); +} + +bool io_gpio_read(uint32_t pin) { + return gpio_get(pin); +} diff --git a/sw/restat_base/src/io/io_gpio.h b/sw/restat_base/src/io/io_gpio.h new file mode 100644 index 0000000..dbba959 --- /dev/null +++ b/sw/restat_base/src/io/io_gpio.h @@ -0,0 +1,51 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * io_gpio.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief Initializes a GPIO pin as input or output +/// +/// @param pin [in] GPIO pin number to initialize +/// @param is_output [in] True to configure as output, false for input +void io_gpio_init(uint32_t pin, bool is_output); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Drives a GPIO pin to a high or low level +/// +/// @param pin [in] GPIO pin number to write +/// @param value [in] True to set high, false to set low +void io_gpio_write(uint32_t pin, bool value); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Reads the current state of a GPIO pin +/// +/// @param pin [in] GPIO pin number to read +/// @return True if the pin is high, false if low +bool io_gpio_read(uint32_t pin); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base/src/io/io_pwm.c b/sw/restat_base/src/io/io_pwm.c new file mode 100644 index 0000000..fb09433 --- /dev/null +++ b/sw/restat_base/src/io/io_pwm.c @@ -0,0 +1,42 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * io_pwm.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#include +#include +#include + +static const uint32_t PWM_WRAP_VAL = 500; +static const uint32_t PWM_INITIAL_LEVEL = 1; +static const float PWM_CLKDIV = 50.0f; +static const uint16_t PWM_MAX_DUTY_LEVEL = 100; + +void io_pwm_init(uint32_t pin, uint32_t channel) { + gpio_set_function(pin, GPIO_FUNC_PWM); + uint32_t slice_num = pwm_gpio_to_slice_num(pin); + pwm_set_wrap(slice_num, PWM_WRAP_VAL); + pwm_set_chan_level(slice_num, channel, PWM_INITIAL_LEVEL); + pwm_set_clkdiv(slice_num, PWM_CLKDIV); + pwm_set_enabled(slice_num, true); +} + +void io_pwm_write(uint32_t pin, uint32_t channel, uint16_t duty_level) { + if (duty_level <= PWM_MAX_DUTY_LEVEL) { + uint32_t slice_num = pwm_gpio_to_slice_num(pin); + pwm_set_chan_level(slice_num, channel, duty_level); + } +} diff --git a/sw/restat_base/src/io/io_pwm.h b/sw/restat_base/src/io/io_pwm.h new file mode 100644 index 0000000..e3ce71b --- /dev/null +++ b/sw/restat_base/src/io/io_pwm.h @@ -0,0 +1,44 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * io_pwm.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief Initializes PWM on a specific pin and PWM channel +/// +/// @param pin [in] GPIO pin to initialize for PWM +/// @param channel [in] PWM channel to use +void io_pwm_init(uint32_t pin, uint32_t channel); + +//////////////////////////////////////////////////////////////////////////// +/// @brief Writes PWM duty cycle to a specific pin and PWM channel +/// +/// @param pin [in] GPIO pin with PWM enabled +/// @param channel [in] PWM channel to write +/// @param duty_percent [in] Duty cycle as percentage (0-100) +void io_pwm_write(uint32_t pin, uint32_t channel, uint16_t duty_percent); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base/src/main.c b/sw/restat_base/src/main.c new file mode 100644 index 0000000..5781441 --- /dev/null +++ b/sw/restat_base/src/main.c @@ -0,0 +1,103 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * main.c + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum { RESTAT_REQ_LEN = 256 }; +static const uint32_t USB_CONN_CHECK_MS = 100; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Performs unified initialization of all hardware devices +/// @return true for success else false +static bool device_init(void) { + if (!stdio_init_all()) { + return false; + } + + if (!relay_init()) { + return false; + } + + if (!status_led_init()) { + return false; + } + + if (!buzzer_init()) { + return false; + } + + buzzer_beep_start(); + + return true; +} + +//////////////////////////////////////////////////////////////////////////// +/// @brief Main entry point for restat-base +/// @return 0 for success exit else 1 for failed exit +int main() { + //////////////////////////////////////////////////////////////////////////// + /// Performs device initialization + if (!device_init()) { + return 1; + } + + //////////////////////////////////////////////////////////////////////////// + /// Waits for USB connection + while (!tud_cdc_connected()) { + sleep_ms(USB_CONN_CHECK_MS); + } + + // Load and execute persisted plan if any + char persisted_plan[PERSIST_MAX_LEN] = {0}; + if (persist_load_plan(persisted_plan, sizeof(persisted_plan))) { + printf("\n", persisted_plan); + fflush(stdout); + command_dispatch(persisted_plan); + } + + //////////////////////////////////////////////////////////////////////////// + /// Command buffer for received request + char request[RESTAT_REQ_LEN] = {0}; + + while (true) { + //////////////////////////////////////////////////////////////////////////// + /// Run non-blocking timings + relay_tick(); + buzzer_tick(); + + //////////////////////////////////////////////////////////////////////////// + /// Fetch and process channel command request + if (parser_get_command(request, RESTAT_REQ_LEN)) { + command_dispatch(request); + memset(request, 0, RESTAT_REQ_LEN * sizeof(char)); + } + } + + return 0; +} diff --git a/sw/restat_base/src/ws2812/CMakeLists.txt b/sw/restat_base/src/ws2812/CMakeLists.txt new file mode 100644 index 0000000..b9a61b8 --- /dev/null +++ b/sw/restat_base/src/ws2812/CMakeLists.txt @@ -0,0 +1,10 @@ +# +# @brief restat-base ws2812 pio +# @version v1.0.3 +# @date 2023-09-05 +# @author Vladimir Roncevic +# + +# Adds WS2812 target library as interface (header-only) +add_library(ws2812 INTERFACE) +target_include_directories(ws2812 INTERFACE .) diff --git a/sw/restat_base/src/ws2812/ws2812.pio.h b/sw/restat_base/src/ws2812/ws2812.pio.h new file mode 100644 index 0000000..547afe3 --- /dev/null +++ b/sw/restat_base/src/ws2812/ws2812.pio.h @@ -0,0 +1,188 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * ws2812.pio.h + * Copyright (C) 2025 Vladimir Roncevic + * + * restat-base is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * restat-base 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program_name. If not, see . + */ +#pragma once + +#if !PICO_NO_HARDWARE +#include "hardware/clocks.h" +#include "hardware/pio.h" + +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief PIO program instructions for WS2812 +static const uint16_t ws2812_program_instructions[] = { + // .wrap_target + 0x6221, // 0: out x, 1 side 0 [2] + 0x1123, // 1: jmp !x, 3 side 1 [1] + 0x1400, // 2: jmp 0 side 1 [4] + 0xa442, // 3: nop side 0 [4] + // .wrap +}; + +#if !PICO_NO_HARDWARE + +//////////////////////////////////////////////////////////////////////////// +/// @brief PIO program instruction structure for WS2812 +static const struct pio_program ws2812_program = { + .instructions = ws2812_program_instructions, + .length = 4, + .origin = -1, +}; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Prepares default configuration +/// @param offset represents programm address +/// @return PIO configuration structure for WS2812 +static inline pio_sm_config ws2812_program_get_default_config(uint offset) { + const uint wrap_target_val = 0; + const uint wrap_val = 3; + + pio_sm_config config = pio_get_default_sm_config(); + uint wrap_target = offset + wrap_target_val; + uint wrap = offset + wrap_val; + + sm_config_set_wrap(&config, wrap_target, wrap); + sm_config_set_sideset(&config, 1, false, false); + + return config; +} + +//////////////////////////////////////////////////////////////////////////// +/// @brief WS2812 init structure +typedef struct _ws2812_init { + PIO pio; + uint sm; + uint offset; + uint pin; + float freq; + bool rgbw; +} ws2812_init; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Performs WS2812 program initialization +/// @param init represents pointer to WS2812 init structure +static inline void ws2812_program_init(ws2812_init *init) { + const int t1 = 2; + const int t2 = 5; + const int t3 = 3; + + pio_gpio_init(init->pio, init->pin); + pio_sm_set_consecutive_pindirs(init->pio, init->sm, init->pin, 1, true); + + pio_sm_config config = ws2812_program_get_default_config(init->offset); + + sm_config_set_sideset_pins(&config, init->pin); + sm_config_set_out_shift(&config, false, true, init->rgbw ? 32 : 24); + sm_config_set_fifo_join(&config, PIO_FIFO_JOIN_TX); + + int cycles_per_bit = (t1 + t2 + t3); + float div = clock_get_hz(clk_sys) / (init->freq * cycles_per_bit); + + sm_config_set_clkdiv(&config, div); + pio_sm_init(init->pio, init->sm, init->offset, &config); + pio_sm_set_enabled(init->pio, init->sm, true); +} + +#endif + +//////////////////////////////////////////////////////////////////////////// +/// @brief PIO program instructions for WS2812 (parallel) +static const uint16_t ws2812_parallel_program_instructions[] = { + // .wrap_target + 0x6020, // 0: out x, 32 + 0xa10b, // 1: mov pins, !null [1] + 0xa401, // 2: mov pins, x [4] + 0xa103, // 3: mov pins, null [1] + // .wrap +}; + +#if !PICO_NO_HARDWARE + +//////////////////////////////////////////////////////////////////////////// +/// @brief PIO program instruction structure for WS2812 (parallel) +static const struct pio_program ws2812_parallel_program = { + .instructions = ws2812_parallel_program_instructions, + .length = 4, + .origin = -1, +}; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Prepares default configuration (parallel) +/// @param offset represents program address +/// @return PIO configuration structure for WS2812 +static inline pio_sm_config +ws2812_parallel_program_get_default_config(uint offset) { + const uint wrap_target_val = 0; + const uint wrap_val = 3; + + pio_sm_config config = pio_get_default_sm_config(); + uint wrap_target = offset + wrap_target_val; + uint wrap = offset + wrap_val; + sm_config_set_wrap(&config, wrap_target, wrap); + + return config; +} + +//////////////////////////////////////////////////////////////////////////// +/// @brief WS2812 parallel init structure +typedef struct _ws2812_parallel_init { + PIO pio; + uint sm; + uint offset; + uint pin_base; + uint pin_count; + float freq; +} ws2812_parallel_init; + +//////////////////////////////////////////////////////////////////////////// +/// @brief Performs WS2812 parallel program initialization +/// @param init represents pointer to WS2812 parallel init structure +static inline void ws2812_parallel_program_init(ws2812_parallel_init *init) { + const int t1 = 2; + const int t2 = 5; + const int t3 = 3; + + uint max_pin_count = init->pin_base + init->pin_count; + + for (uint i = init->pin_base; i < max_pin_count; i++) { + pio_gpio_init(init->pio, i); + } + + pio_sm_set_consecutive_pindirs( + init->pio, init->sm, init->pin_base, init->pin_count, true + ); + + pio_sm_config config = + ws2812_parallel_program_get_default_config(init->offset); + + sm_config_set_out_shift(&config, true, true, 32); + sm_config_set_out_pins(&config, init->pin_base, init->pin_count); + sm_config_set_out_pins(&config, init->pin_base, init->pin_count); + sm_config_set_fifo_join(&config, PIO_FIFO_JOIN_TX); + + int cycles_per_bit = (t1 + t2 + t3); + + float div = clock_get_hz(clk_sys) / (init->freq * cycles_per_bit); + + sm_config_set_clkdiv(&config, div); + pio_sm_init(init->pio, init->sm, init->offset, &config); + pio_sm_set_enabled(init->pio, init->sm, true); +} + +#endif diff --git a/sw/restat_base_tests/CMakeLists.txt b/sw/restat_base_tests/CMakeLists.txt new file mode 100644 index 0000000..706f3d4 --- /dev/null +++ b/sw/restat_base_tests/CMakeLists.txt @@ -0,0 +1,49 @@ +cmake_minimum_required(VERSION 3.12) +project(restat_base_tests C CXX) + +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +enable_testing() + +# 1. Include Mocks first so that standard Pico and device includes are intercepted +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/mocks + ${CMAKE_CURRENT_SOURCE_DIR}/../restat_base/src + ${CMAKE_CURRENT_SOURCE_DIR}/../restat_base/src/command +) + +# 2. Add Googletest subdirectory from restatdesk_tests (offline/local reuse) +add_subdirectory( + ${CMAKE_CURRENT_SOURCE_DIR}/../restatdesk_tests/googletest + ${CMAKE_CURRENT_BINARY_DIR}/googletest_build +) + +# Include Googletest headers +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/../restatdesk_tests/googletest/googletest/include + ${CMAKE_CURRENT_SOURCE_DIR}/../restatdesk_tests/googletest/googlemock/include +) + +# 3. Create test executable compiling base C modules with host mock structures +add_executable( + restat_base_tests + main.cc + mocks/mocks.cc + ../restat_base/src/command/parser.c + ../restat_base/src/command/command_tbl.c + tests/test_parser.cc + tests/test_command.cc +) + +# 4. Link GoogleTest libraries +target_link_libraries( + restat_base_tests + PUBLIC + gtest + gtest_main + gmock + gmock_main +) + +include(GoogleTest) +gtest_discover_tests(restat_base_tests) diff --git a/sw/restat_base_tests/build/googletest_build/googletest/generated/GTestConfig.cmake b/sw/restat_base_tests/build/googletest_build/googletest/generated/GTestConfig.cmake new file mode 100644 index 0000000..9ab9a5e --- /dev/null +++ b/sw/restat_base_tests/build/googletest_build/googletest/generated/GTestConfig.cmake @@ -0,0 +1,37 @@ + +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was Config.cmake.in ######## + +get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE) + +macro(set_and_check _var _file) + set(${_var} "${_file}") + if(NOT EXISTS "${_file}") + message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !") + endif() +endmacro() + +macro(check_required_components _NAME) + foreach(comp ${${_NAME}_FIND_COMPONENTS}) + if(NOT ${_NAME}_${comp}_FOUND) + if(${_NAME}_FIND_REQUIRED_${comp}) + set(${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() + +#################################################################################### +include(CMakeFindDependencyMacro) +if (ON) + set(THREADS_PREFER_PTHREAD_FLAG ) + find_dependency(Threads) +endif() +if (OFF) + find_dependency(absl) + find_dependency(re2) +endif() + +include("${CMAKE_CURRENT_LIST_DIR}/GTestTargets.cmake") +check_required_components("") diff --git a/sw/restat_base_tests/build/googletest_build/googletest/generated/GTestConfigVersion.cmake b/sw/restat_base_tests/build/googletest_build/googletest/generated/GTestConfigVersion.cmake new file mode 100644 index 0000000..a290d14 --- /dev/null +++ b/sw/restat_base_tests/build/googletest_build/googletest/generated/GTestConfigVersion.cmake @@ -0,0 +1,43 @@ +# This is a basic version file for the Config-mode of find_package(). +# It is used by write_basic_package_version_file() as input file for configure_file() +# to create a version-file which can be installed along a config.cmake file. +# +# The created file sets PACKAGE_VERSION_EXACT if the current version string and +# the requested version string are exactly the same and it sets +# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version. +# The variable CVF_VERSION must be set before calling configure_file(). + +set(PACKAGE_VERSION "1.17.0") + +if (PACKAGE_FIND_VERSION_RANGE) + # Package version must be in the requested version range + if ((PACKAGE_FIND_VERSION_RANGE_MIN STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN) + OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_GREATER PACKAGE_FIND_VERSION_MAX) + OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_GREATER_EQUAL PACKAGE_FIND_VERSION_MAX))) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + endif() +else() + if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) + endif() + endif() +endif() + + +# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: +if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "") + return() +endif() + +# check that the installed version has the same 32/64bit-ness as the one which is currently searching: +if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8") + math(EXPR installedBits "8 * 8") + set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") + set(PACKAGE_VERSION_UNSUITABLE TRUE) +endif() diff --git a/sw/restat_base_tests/build/googletest_build/googletest/generated/gmock.pc b/sw/restat_base_tests/build/googletest_build/googletest/generated/gmock.pc new file mode 100644 index 0000000..e152eba --- /dev/null +++ b/sw/restat_base_tests/build/googletest_build/googletest/generated/gmock.pc @@ -0,0 +1,10 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gmock +Description: GoogleMock (without main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Requires: gtest = 1.17.0 +Libs: -L${libdir} -lgmock +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restat_base_tests/build/googletest_build/googletest/generated/gmock_main.pc b/sw/restat_base_tests/build/googletest_build/googletest/generated/gmock_main.pc new file mode 100644 index 0000000..df9620a --- /dev/null +++ b/sw/restat_base_tests/build/googletest_build/googletest/generated/gmock_main.pc @@ -0,0 +1,10 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Requires: gmock = 1.17.0 +Libs: -L${libdir} -lgmock_main +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restat_base_tests/build/googletest_build/googletest/generated/gtest.pc b/sw/restat_base_tests/build/googletest_build/googletest/generated/gtest.pc new file mode 100644 index 0000000..aeb8b52 --- /dev/null +++ b/sw/restat_base_tests/build/googletest_build/googletest/generated/gtest.pc @@ -0,0 +1,9 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restat_base_tests/build/googletest_build/googletest/generated/gtest_main.pc b/sw/restat_base_tests/build/googletest_build/googletest/generated/gtest_main.pc new file mode 100644 index 0000000..d103700 --- /dev/null +++ b/sw/restat_base_tests/build/googletest_build/googletest/generated/gtest_main.pc @@ -0,0 +1,10 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gtest_main +Description: GoogleTest (with main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Requires: gtest = 1.17.0 +Libs: -L${libdir} -lgtest_main +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restat_base_tests/build/restat_base_tests b/sw/restat_base_tests/build/restat_base_tests new file mode 100755 index 0000000..71925f6 Binary files /dev/null and b/sw/restat_base_tests/build/restat_base_tests differ diff --git a/sw/restat_base_tests/build/restat_base_tests[1]_include.cmake b/sw/restat_base_tests/build/restat_base_tests[1]_include.cmake new file mode 100644 index 0000000..2836a0e --- /dev/null +++ b/sw/restat_base_tests/build/restat_base_tests[1]_include.cmake @@ -0,0 +1,5 @@ +if(EXISTS "/data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests[1]_tests.cmake") + include("/data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests[1]_tests.cmake") +else() + add_test(restat_base_tests_NOT_BUILT restat_base_tests_NOT_BUILT) +endif() diff --git a/sw/restat_base_tests/build/restat_base_tests[1]_tests.cmake b/sw/restat_base_tests/build/restat_base_tests[1]_tests.cmake new file mode 100644 index 0000000..45b18c5 --- /dev/null +++ b/sw/restat_base_tests/build/restat_base_tests[1]_tests.cmake @@ -0,0 +1,27 @@ +add_test([=[ParserTest.WellFormedCommand]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=ParserTest.WellFormedCommand]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParserTest.WellFormedCommand]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParserTest.IncompleteCommand]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=ParserTest.IncompleteCommand]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParserTest.IncompleteCommand]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParserTest.IgnoresWhitespace]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=ParserTest.IgnoresWhitespace]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParserTest.IgnoresWhitespace]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParserTest.BufferOverflowHandling]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=ParserTest.BufferOverflowHandling]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParserTest.BufferOverflowHandling]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.BoardIdAndVersion]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.BoardIdAndVersion]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.BoardIdAndVersion]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.ChannelControl]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.ChannelControl]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.ChannelControl]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.AllChannelsControl]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.AllChannelsControl]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.AllChannelsControl]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.TimerCommand]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.TimerCommand]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.TimerCommand]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.MaskCommand]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.MaskCommand]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.MaskCommand]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.PlanCommand]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.PlanCommand]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.PlanCommand]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.ChannelStatus]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.ChannelStatus]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.ChannelStatus]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.AllStatus]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.AllStatus]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.AllStatus]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[CommandTest.SystemReset]=] /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build/restat_base_tests [==[--gtest_filter=CommandTest.SystemReset]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[CommandTest.SystemReset]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restat_base_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +set( restat_base_tests_TESTS ParserTest.WellFormedCommand ParserTest.IncompleteCommand ParserTest.IgnoresWhitespace ParserTest.BufferOverflowHandling CommandTest.BoardIdAndVersion CommandTest.ChannelControl CommandTest.AllChannelsControl CommandTest.TimerCommand CommandTest.MaskCommand CommandTest.PlanCommand CommandTest.ChannelStatus CommandTest.AllStatus CommandTest.SystemReset) diff --git a/sw/restat_base_tests/main.cc b/sw/restat_base_tests/main.cc new file mode 100644 index 0000000..dc42b1a --- /dev/null +++ b/sw/restat_base_tests/main.cc @@ -0,0 +1,6 @@ +#include "gtest/gtest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/sw/restat_base_tests/mocks/device/buzzer.h b/sw/restat_base_tests/mocks/device/buzzer.h new file mode 100644 index 0000000..60b6c63 --- /dev/null +++ b/sw/restat_base_tests/mocks/device/buzzer.h @@ -0,0 +1,11 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +void buzzer_beep_stop(void); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base_tests/mocks/device/persist.h b/sw/restat_base_tests/mocks/device/persist.h new file mode 100644 index 0000000..7cbc455 --- /dev/null +++ b/sw/restat_base_tests/mocks/device/persist.h @@ -0,0 +1,11 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +void persist_save_plan(const char *plan); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base_tests/mocks/device/relay.h b/sw/restat_base_tests/mocks/device/relay.h new file mode 100644 index 0000000..e435619 --- /dev/null +++ b/sw/restat_base_tests/mocks/device/relay.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +enum { RELAY_NUM_CHANNELS = 8 }; + +typedef enum { + RELAY_MODE_TOGGLE, + RELAY_MODE_TIMER +} relay_mode_t; + +bool relay_init(void); +void relay_set(uint32_t channel, bool state); +void relay_set_all(bool state); +void relay_start_timer(uint32_t channel, uint32_t milliseconds, bool start_on); +void relay_tick(void); +void relay_get_status(uint32_t channel, char *buf, uint32_t max_len); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base_tests/mocks/device/status_led.h b/sw/restat_base_tests/mocks/device/status_led.h new file mode 100644 index 0000000..6e1bc9d --- /dev/null +++ b/sw/restat_base_tests/mocks/device/status_led.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void status_led_write(uint8_t r, uint8_t g, uint8_t b); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base_tests/mocks/hardware/watchdog.h b/sw/restat_base_tests/mocks/hardware/watchdog.h new file mode 100644 index 0000000..b042e03 --- /dev/null +++ b/sw/restat_base_tests/mocks/hardware/watchdog.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void watchdog_reboot(uint32_t pc, uint32_t sp, uint32_t delay_ms); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base_tests/mocks/mocks.cc b/sw/restat_base_tests/mocks/mocks.cc new file mode 100644 index 0000000..90175ca --- /dev/null +++ b/sw/restat_base_tests/mocks/mocks.cc @@ -0,0 +1,121 @@ +#include "mocks.h" +#include "pico/stdlib.h" +#include "hardware/watchdog.h" +#include "device/relay.h" +#include "device/buzzer.h" +#include "device/status_led.h" +#include "device/persist.h" +#include +#include + +std::queue mock_input_queue; +std::vector relay_calls; +static std::string channel_statuses[RELAY_NUM_CHANNELS]; + +bool buzzer_beep_stop_called = false; +uint8_t mock_led_r = 0; +uint8_t mock_led_g = 0; +uint8_t mock_led_b = 0; +bool watchdog_reboot_called = false; +std::string last_saved_plan; + +void mock_push_input(const std::string& str) { + for (char c : str) { + mock_input_queue.push(c); + } +} + +void mock_clear_input() { + std::queue empty; + std::swap(mock_input_queue, empty); +} + +void mock_clear_relay_calls() { + relay_calls.clear(); +} + +void mock_set_channel_status(uint32_t channel, const std::string& status) { + if (channel < RELAY_NUM_CHANNELS) { + channel_statuses[channel] = status; + } +} + +void mock_clear_system_states() { + buzzer_beep_stop_called = false; + mock_led_r = 0; + mock_led_g = 0; + mock_led_b = 0; + watchdog_reboot_called = false; + last_saved_plan.clear(); + for (uint32_t i = 0; i < RELAY_NUM_CHANNELS; i++) { + channel_statuses[i].clear(); + } +} + +extern "C" { + +int16_t getchar_timeout_us(uint32_t timeout_us) { + (void)timeout_us; + if (mock_input_queue.empty()) { + return PICO_ERROR_TIMEOUT; + } + char c = mock_input_queue.front(); + mock_input_queue.pop(); + return (int16_t)(uint8_t)c; +} + +void watchdog_reboot(uint32_t pc, uint32_t sp, uint32_t delay_ms) { + (void)pc; + (void)sp; + (void)delay_ms; + watchdog_reboot_called = true; +} + +bool relay_init(void) { + return true; +} + +void relay_set(uint32_t channel, bool state) { + RelayMockCall call = {RelayMockCall::SET, channel, state, 0, false}; + relay_calls.push_back(call); +} + +void relay_set_all(bool state) { + RelayMockCall call = {RelayMockCall::SET_ALL, 0, state, 0, false}; + relay_calls.push_back(call); +} + +void relay_start_timer(uint32_t channel, uint32_t milliseconds, bool start_on) { + RelayMockCall call = {RelayMockCall::TIMER, channel, false, milliseconds, start_on}; + relay_calls.push_back(call); +} + +void relay_tick(void) { + // No-op +} + +void relay_get_status(uint32_t channel, char *buf, uint32_t max_len) { + if (channel < RELAY_NUM_CHANNELS) { + if (!channel_statuses[channel].empty()) { + snprintf(buf, max_len, "%s", channel_statuses[channel].c_str()); + } else { + snprintf(buf, max_len, "channel %u: OFF", channel + 1); + } + } +} + +void buzzer_beep_stop(void) { + buzzer_beep_stop_called = true; +} + +void status_led_write(uint8_t r, uint8_t g, uint8_t b) { + mock_led_r = r; + mock_led_g = g; + mock_led_b = b; +} + +void persist_save_plan(const char *plan) { + last_saved_plan = plan; +} + +} diff --git a/sw/restat_base_tests/mocks/mocks.h b/sw/restat_base_tests/mocks/mocks.h new file mode 100644 index 0000000..02486ef --- /dev/null +++ b/sw/restat_base_tests/mocks/mocks.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include +#include + +// Mock queue for getchar_timeout_us +extern std::queue mock_input_queue; +void mock_push_input(const std::string& str); +void mock_clear_input(); + +// Mock call registry for relay +struct RelayMockCall { + enum CallType { + SET, SET_ALL, TIMER + } type; + uint32_t channel; + bool state; + uint32_t timer_ms; + bool timer_start_on; +}; + +extern std::vector relay_calls; +void mock_clear_relay_calls(); +void mock_set_channel_status(uint32_t channel, const std::string& status); + +// Mock states for buzzer, status_led, watchdog, persist +extern bool buzzer_beep_stop_called; +extern uint8_t mock_led_r; +extern uint8_t mock_led_g; +extern uint8_t mock_led_b; +extern bool watchdog_reboot_called; +extern std::string last_saved_plan; + +void mock_clear_system_states(); diff --git a/sw/restat_base_tests/mocks/pico/stdlib.h b/sw/restat_base_tests/mocks/pico/stdlib.h new file mode 100644 index 0000000..9aa68d1 --- /dev/null +++ b/sw/restat_base_tests/mocks/pico/stdlib.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +#define PICO_ERROR_TIMEOUT (-1) + +#ifdef __cplusplus +extern "C" { +#endif + +int16_t getchar_timeout_us(uint32_t timeout_us); + +#ifdef __cplusplus +} +#endif diff --git a/sw/restat_base_tests/restat_base_tests.code-workspace b/sw/restat_base_tests/restat_base_tests.code-workspace new file mode 100644 index 0000000..5709732 --- /dev/null +++ b/sw/restat_base_tests/restat_base_tests.code-workspace @@ -0,0 +1,8 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": {} +} diff --git a/sw/restat_base_tests/tests/test_command.cc b/sw/restat_base_tests/tests/test_command.cc new file mode 100644 index 0000000..e4fd03b --- /dev/null +++ b/sw/restat_base_tests/tests/test_command.cc @@ -0,0 +1,178 @@ +#include "gtest/gtest.h" +#include "mocks/mocks.h" +#include "command/dispatcher.h" +#include +#include +#include + +class StdoutCapture { +public: + StdoutCapture() { + fflush(stdout); + old_stdout = dup(fileno(stdout)); + if (pipe(pipe_fds) == 0) { + dup2(pipe_fds[1], fileno(stdout)); + close(pipe_fds[1]); + } + } + std::string GetCapture() { + fflush(stdout); + dup2(old_stdout, fileno(stdout)); + close(old_stdout); + + std::string out; + char buf[1024]; + ssize_t bytes_read; + int flags = fcntl(pipe_fds[0], F_GETFL, 0); + fcntl(pipe_fds[0], F_SETFL, flags | O_NONBLOCK); + while ((bytes_read = read(pipe_fds[0], buf, sizeof(buf) - 1)) > 0) { + buf[bytes_read] = '\0'; + out += buf; + } + close(pipe_fds[0]); + return out; + } +private: + int old_stdout; + int pipe_fds[2]; +}; + +class CommandTest : public ::testing::Test { +protected: + void SetUp() override { + mock_clear_relay_calls(); + mock_clear_system_states(); + } +}; + +TEST_F(CommandTest, BoardIdAndVersion) { + { + StdoutCapture capture; + command_dispatch("rs#sys#id#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + } + { + StdoutCapture capture; + command_dispatch("rs#sys#version#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + } +} + +TEST_F(CommandTest, ChannelControl) { + StdoutCapture capture; + command_dispatch("rs#ch#1#on#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + ASSERT_EQ(relay_calls.size(), 1); + EXPECT_EQ(relay_calls[0].type, RelayMockCall::SET); + EXPECT_EQ(relay_calls[0].channel, 0); + EXPECT_TRUE(relay_calls[0].state); + + mock_clear_relay_calls(); + { + StdoutCapture capture2; + command_dispatch("rs#ch#8#off#end"); + std::string output2 = capture2.GetCapture(); + EXPECT_EQ(output2, ""); + } + ASSERT_EQ(relay_calls.size(), 1); + EXPECT_EQ(relay_calls[0].type, RelayMockCall::SET); + EXPECT_EQ(relay_calls[0].channel, 7); + EXPECT_FALSE(relay_calls[0].state); +} + +TEST_F(CommandTest, AllChannelsControl) { + { + StdoutCapture capture; + command_dispatch("rs#all#on#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + ASSERT_EQ(relay_calls.size(), 1); + EXPECT_EQ(relay_calls[0].type, RelayMockCall::SET_ALL); + EXPECT_TRUE(relay_calls[0].state); + EXPECT_EQ(mock_led_r, 255); + EXPECT_EQ(mock_led_g, 255); + EXPECT_EQ(mock_led_b, 255); + } + { + mock_clear_relay_calls(); + StdoutCapture capture; + command_dispatch("rs#all#off#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + ASSERT_EQ(relay_calls.size(), 1); + EXPECT_EQ(relay_calls[0].type, RelayMockCall::SET_ALL); + EXPECT_FALSE(relay_calls[0].state); + EXPECT_EQ(mock_led_r, 0); + EXPECT_EQ(mock_led_g, 0); + EXPECT_EQ(mock_led_b, 0); + } +} + +TEST_F(CommandTest, TimerCommand) { + StdoutCapture capture; + command_dispatch("rs#ch#3#tmr#15000#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + ASSERT_EQ(relay_calls.size(), 1); + EXPECT_EQ(relay_calls[0].type, RelayMockCall::TIMER); + EXPECT_EQ(relay_calls[0].channel, 2); + EXPECT_EQ(relay_calls[0].timer_ms, 15000); + EXPECT_TRUE(relay_calls[0].timer_start_on); +} + +TEST_F(CommandTest, MaskCommand) { + StdoutCapture capture; + command_dispatch("rs#all#mask#10101010#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + ASSERT_EQ(relay_calls.size(), 8); + for (uint32_t i = 0; i < 8; i++) { + EXPECT_EQ(relay_calls[i].type, RelayMockCall::SET); + EXPECT_EQ(relay_calls[i].channel, i); + EXPECT_EQ(relay_calls[i].state, (i % 2 == 0)); + } +} + +TEST_F(CommandTest, PlanCommand) { + StdoutCapture capture; + command_dispatch("rs#all#plan#ch#1#on#ch#2#tmroff#15000#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + EXPECT_EQ(last_saved_plan, "rs#all#plan#ch#1#on#ch#2#tmroff#15000#end"); + ASSERT_EQ(relay_calls.size(), 2); + EXPECT_EQ(relay_calls[0].type, RelayMockCall::SET); + EXPECT_EQ(relay_calls[0].channel, 0); + EXPECT_TRUE(relay_calls[0].state); + + EXPECT_EQ(relay_calls[1].type, RelayMockCall::TIMER); + EXPECT_EQ(relay_calls[1].channel, 1); + EXPECT_EQ(relay_calls[1].timer_ms, 15000); + EXPECT_FALSE(relay_calls[1].timer_start_on); +} + +TEST_F(CommandTest, ChannelStatus) { + mock_set_channel_status(3, "channel 4: ON (timer)"); + StdoutCapture capture; + command_dispatch("rs#ch#4#stat#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); +} + +TEST_F(CommandTest, AllStatus) { + StdoutCapture capture; + command_dispatch("rs#all#stat#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); +} + +TEST_F(CommandTest, SystemReset) { + StdoutCapture capture; + command_dispatch("rs#sys#reset#end"); + std::string output = capture.GetCapture(); + EXPECT_EQ(output, ""); + EXPECT_TRUE(buzzer_beep_stop_called); + EXPECT_TRUE(watchdog_reboot_called); +} diff --git a/sw/restat_base_tests/tests/test_parser.cc b/sw/restat_base_tests/tests/test_parser.cc new file mode 100644 index 0000000..078dc9e --- /dev/null +++ b/sw/restat_base_tests/tests/test_parser.cc @@ -0,0 +1,40 @@ +#include "gtest/gtest.h" +#include "mocks/mocks.h" +#include "command/parser.h" + +class ParserTest : public ::testing::Test { +protected: + void SetUp() override { + mock_clear_input(); + } +}; + +TEST_F(ParserTest, WellFormedCommand) { + mock_push_input(""); + char buf[64]; + bool success = parser_get_command(buf, sizeof(buf)); + EXPECT_TRUE(success); + EXPECT_STREQ(buf, "rs#ch#1#on#end"); +} + +TEST_F(ParserTest, IncompleteCommand) { + mock_push_input("\n"); + char buf[64]; + bool success = parser_get_command(buf, sizeof(buf)); + EXPECT_TRUE(success); + EXPECT_STREQ(buf, "rs#ch#2#off#end"); +} + +TEST_F(ParserTest, BufferOverflowHandling) { + mock_push_input("<12345678901234567890>"); + char buf[10]; + bool success = parser_get_command(buf, sizeof(buf)); + EXPECT_FALSE(success); +} diff --git a/sw/restatdesk/.clang-format b/sw/restatdesk/.clang-format new file mode 100644 index 0000000..8c75b63 --- /dev/null +++ b/sw/restatdesk/.clang-format @@ -0,0 +1,6 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +TabWidth: 4 +UseTab: Never +NamespaceIndentation: All +AlignAfterOpenBracket: BlockIndent diff --git a/sw/restat-desktop/build/.editorconfig b/sw/restatdesk/.editorconfig similarity index 100% rename from sw/restat-desktop/build/.editorconfig rename to sw/restatdesk/.editorconfig diff --git a/sw/restatdesk/.vscode/.editorconfig b/sw/restatdesk/.vscode/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/.vscode/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/.vscode/launch.json b/sw/restatdesk/.vscode/launch.json new file mode 100644 index 0000000..19e21dc --- /dev/null +++ b/sw/restatdesk/.vscode/launch.json @@ -0,0 +1,30 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "restatdesk debug", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/build/restatdesk", + "args": [], + "stopAtEntry": false, + "cwd": "${fileDirname}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "preLaunchTask": "restatdesk build", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + }, + { + "description": "Set Disassembly Flavor to Intel", + "text": "-gdb-set disassembly-flavor intel", + "ignoreFailures": true + } + ] + } + ] +} \ No newline at end of file diff --git a/sw/restatdesk/.vscode/settings.json b/sw/restatdesk/.vscode/settings.json new file mode 100644 index 0000000..bd659fc --- /dev/null +++ b/sw/restatdesk/.vscode/settings.json @@ -0,0 +1,40 @@ +{ + "files.associations": { + "*.h": "cpp" + }, + "clangd.fallbackFlags": [ + "-std=c++23", + "-I${workspaceFolder}", + "-I/usr/include/gtkmm-4.0", + "-I/usr/lib/x86_64-linux-gnu/gtkmm-4.0/include", + "-I/usr/include/giomm-2.68", + "-I/usr/lib/x86_64-linux-gnu/giomm-2.68/include", + "-I/usr/include/glib-2.0", + "-I/usr/lib/x86_64-linux-gnu/glib-2.0/include", + "-I/usr/include/libmount", + "-I/usr/include/blkid", + "-I/usr/include/glibmm-2.68", + "-I/usr/lib/x86_64-linux-gnu/glibmm-2.68/include", + "-I/usr/include/sigc++-3.0", + "-I/usr/lib/x86_64-linux-gnu/sigc++-3.0/include", + "-I/usr/include/gtk-4.0", + "-I/usr/include/pango-1.0", + "-I/usr/include/harfbuzz", + "-I/usr/include/freetype2", + "-I/usr/include/libpng16", + "-I/usr/include/fribidi", + "-I/usr/include/cairo", + "-I/usr/include/pixman-1", + "-I/usr/include/gdk-pixbuf-2.0", + "-I/usr/include/x86_64-linux-gnu", + "-I/usr/include/webp", + "-I/usr/include/graphene-1.0", + "-I/usr/lib/x86_64-linux-gnu/graphene-1.0/include", + "-I/usr/include/cairomm-1.16", + "-I/usr/lib/x86_64-linux-gnu/cairomm-1.16/include", + "-I/usr/include/pangomm-2.48", + "-I/usr/lib/x86_64-linux-gnu/pangomm-2.48/include", + "-I/usr/include/gtk-4.0/unix-print", + "-pthread" + ] +} \ No newline at end of file diff --git a/sw/restatdesk/.vscode/tasks.json b/sw/restatdesk/.vscode/tasks.json new file mode 100644 index 0000000..b619073 --- /dev/null +++ b/sw/restatdesk/.vscode/tasks.json @@ -0,0 +1,26 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "restatdesk build", + "type": "shell", + "command": "", + "args": [ + "make", + "--directory=${workspaceFolder}/build" + ], + "problemMatcher": [] + }, + { + "label": "restatdesk clean", + "type": "shell", + "command": "", + "args": [ + "make", + "--directory=${workspaceFolder}/build", + "clean" + ], + "problemMatcher": [] + } + ] +} diff --git a/sw/restatdesk/app_controller.cc b/sw/restatdesk/app_controller.cc new file mode 100644 index 0000000..6a4f410 --- /dev/null +++ b/sw/restatdesk/app_controller.cc @@ -0,0 +1,389 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// app_controller.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Electux::App; + +namespace { + constexpr std::chrono::milliseconds cThreadSleepDuration{100}; +} // namespace + +AppController::AppController( + std::unique_ptr configManager, + std::unique_ptr comChannel, + std::unique_ptr comConfigurator, + std::unique_ptr logger, + std::unique_ptr commandFormatter, + std::unique_ptr responseProcessor +) + : m_configManager(std::move(configManager)), + m_comChannel(std::move(comChannel)), + m_comConfigurator(std::move(comConfigurator)), + m_logger(std::move(logger)), + m_commandFormatter(std::move(commandFormatter)), + m_responseProcessor(std::move(responseProcessor)) {} + +AppController::~AppController() { + m_stopThread = true; + if (m_readThread.joinable()) { + m_readThread.join(); + } + if (m_comChannel) { + m_comChannel->close(); + } +} + +void AppController::startup() { + m_configManager->init(); + configureLogger(); + configureComChannel(); + + m_stopThread = false; + m_readThread = std::thread(&AppController::readLoop, this); + + m_logger->log("Application started.", Logger::LogLevel::Info); + + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::string cmdBoardId = m_commandFormatter->getCommandBoardId(); + + if (!cmdBoardId.empty()) { + std::vector cmdBytes(cmdBoardId.begin(), cmdBoardId.end()); + m_comChannel->write(cmdBytes); + } + + std::string cmdVersion = m_commandFormatter->getCommandVersion(); + + if (!cmdVersion.empty()) { + std::vector cmdBytes(cmdVersion.begin(), cmdVersion.end()); + m_comChannel->write(cmdBytes); + } + + std::string cmdAllStat = + m_commandFormatter->getCommandStatusAllChannels(); + + if (!cmdAllStat.empty()) { + std::vector cmdBytes(cmdAllStat.begin(), cmdAllStat.end()); + m_comChannel->write(cmdBytes); + } + } +} + +void AppController::turnOnAllChannels() { + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::string cmd = m_commandFormatter->getCommandOnAllChannels(); + if (!cmd.empty()) { + std::vector cmdBytes(cmd.begin(), cmd.end()); + m_comChannel->write(cmdBytes); + } + } +} + +void AppController::turnOffAllChannels() { + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::string cmd = m_commandFormatter->getCommandOffAllChannels(); + if (!cmd.empty()) { + std::vector cmdBytes(cmd.begin(), cmd.end()); + m_comChannel->write(cmdBytes); + } + } +} + +void AppController::requestAllChannelsStatus() { + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::string cmd = m_commandFormatter->getCommandStatusAllChannels(); + if (!cmd.empty()) { + std::vector cmdBytes(cmd.begin(), cmd.end()); + m_comChannel->write(cmdBytes); + } + } +} + +void AppController::resetSystem() { + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::string cmd = m_commandFormatter->getCommandReset(); + if (!cmd.empty()) { + std::vector cmdBytes(cmd.begin(), cmd.end()); + m_comChannel->write(cmdBytes); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + m_comChannel->close(); + } + } +} + +void AppController::requestBoardId() { + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::string cmd = m_commandFormatter->getCommandBoardId(); + if (!cmd.empty()) { + std::vector cmdBytes(cmd.begin(), cmd.end()); + m_comChannel->write(cmdBytes); + } + } +} + +void AppController::requestVersion() { + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::string cmd = m_commandFormatter->getCommandVersion(); + if (!cmd.empty()) { + std::vector cmdBytes(cmd.begin(), cmd.end()); + m_comChannel->write(cmdBytes); + } + } +} + +void AppController::shutdown() { + m_stopThread = true; + + if (m_readThread.joinable()) { + m_readThread.join(); + } + + if (m_comChannel) { + m_comChannel->close(); + } + + if (m_logger) { + m_logger->log("Application shutting down.", Logger::LogLevel::Info); + m_logger->close(); + } + + m_configManager->store(true); +} + +void AppController::configureLogger() { + if (!m_logger) { + return; + } + + m_logger->close(); + + auto &config = getModel(); + auto pathKey = config.toString(Model::ModelLogKey::FilePath); + auto levelKey = config.toString(Model::ModelLogKey::LogLevel); + + m_logger->setOutputFile(config.getEntity(pathKey)); + + uint32_t levelIdx = + static_cast(std::stoul(config.getEntity(levelKey))); + m_logger->setLevel(static_cast(levelIdx)); + + m_logger->open(); +} + +void AppController::configureComChannel() { + if (!m_comChannel || !m_comConfigurator) { + return; + } + + m_comChannel->close(); + m_comConfigurator->configure(getModel(), m_comChannel.get()); +} + +const Model::IModel &AppController::getModel() const { + return m_configManager->getConfig(); +} + +void AppController::onSetupChanged(const Model::SettingsSetup &setup) { + const auto &oldConfig = m_configManager->getConfig(); + auto &newConfig = *setup.m_config; + + bool logChanged = hasLoggerConfigChanged(oldConfig, newConfig); + bool comChanged = hasSerialConfigChanged(oldConfig, newConfig) || + hasGeneralConfigChanged(oldConfig, newConfig) || + hasBleConfigChanged(oldConfig, newConfig); + + m_configManager->setConfig(newConfig); + m_configManager->store(); + + if (logChanged) { + configureLogger(); + } + + if (comChanged) { + configureComChannel(); + } + + getModel().emit_changed(); +} + +void AppController::executePlan() { + if (m_commandFormatter && m_comChannel && m_comChannel->isOpen()) { + std::vector states; + for (size_t i = 0; i < Model::Channel::cNumOfChannels; ++i) { + states.push_back(getModel().getChannelState(i)); + } + std::string cmd = m_commandFormatter->getCommandPlan(states); + if (!cmd.empty()) { + m_logger->log("Executing variable plan on channel: " + cmd, Logger::LogLevel::Info); + std::vector cmdBytes(cmd.begin(), cmd.end()); + m_comChannel->write(cmdBytes); + m_signalDataReceived.emit(cmd); + } + } +} + + + +bool AppController::hasSerialConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig +) { + for (int k = static_cast(Model::ModelSerialKey::Device); + k <= static_cast(Model::ModelSerialKey::Flow); ++k) { + auto key = oldConfig.toString(static_cast(k)); + + if (oldConfig.getEntity(key) != newConfig.getEntity(key)) { + return true; + } + } + return false; +} + +bool AppController::hasLoggerConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig +) { + for (int k = static_cast(Model::ModelLogKey::FilePath); + k <= static_cast(Model::ModelLogKey::LogLevel); ++k) { + auto key = oldConfig.toString(static_cast(k)); + + if (oldConfig.getEntity(key) != newConfig.getEntity(key)) { + return true; + } + } + return false; +} + +bool AppController::hasGeneralConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig +) { + for (int k = static_cast(Model::ModelGeneralKey::ComType); + k <= static_cast(Model::ModelGeneralKey::TcpPort); ++k) { + auto key = oldConfig.toString(static_cast(k)); + + if (oldConfig.getEntity(key) != newConfig.getEntity(key)) { + return true; + } + } + return false; +} + +bool AppController::hasBleConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig +) { + for (int k = static_cast(Model::ModelBleKey::Address); + k <= static_cast(Model::ModelBleKey::TxUuid); ++k) { + auto key = oldConfig.toString(static_cast(k)); + + if (oldConfig.getEntity(key) != newConfig.getEntity(key)) { + return true; + } + } + return false; +} + +sigc::signal AppController::signal_data_received() { + return m_signalDataReceived; +} + +void AppController::readLoop() { + while (!m_stopThread) { + try { + if (m_comChannel && m_comChannel->isOpen()) { + std::vector buffer; + m_comChannel->read(buffer, 1); + + if (!m_stopThread && !m_comChannel->isOpen()) { + std::string errorMsg = "\n[Error] Connection lost."; + auto *switchable = + dynamic_cast(m_comChannel.get()); + if (switchable) { + if (switchable->getActiveCom() == + switchable->getSerialCom()) { + errorMsg = + "\n[Error] Serial port is no longer available " + "(I/O error). Device disconnected."; + } else if ( + switchable->getActiveCom() == + switchable->getTcpCom() + ) { + errorMsg = + "\n[Error] TCP connection lost (I/O error)."; + } else if ( + switchable->getActiveCom() == + switchable->getBleCom() + ) { + errorMsg = + "\n[Error] BLE connection lost (I/O error)."; + } + } + m_signalDataReceived.emit(errorMsg); + if (m_logger) { + m_logger->log( + "Communication channel lost (I/O error).", + Logger::LogLevel::Error + ); + } + } else if (!buffer.empty()) { + std::string dataStr(buffer.begin(), buffer.end()); + + if (m_responseProcessor) { + auto payloads = m_responseProcessor->process(dataStr); + + for (const auto &payload : payloads) { + m_signalDataReceived.emit(payload); + } + + } else { + m_signalDataReceived.emit(dataStr); + } + } + + } else { + static auto lastReconnectTry = std::chrono::steady_clock::now(); + auto now = std::chrono::steady_clock::now(); + if (now - lastReconnectTry >= std::chrono::seconds(2)) { + lastReconnectTry = now; + if (m_logger) { + m_logger->log( + "Communication channel closed. Attempting to " + "reconnect...", + Logger::LogLevel::Warning + ); + } + configureComChannel(); + } + std::this_thread::sleep_for(cThreadSleepDuration); + } + } catch (...) { + std::this_thread::sleep_for(cThreadSleepDuration); + } + } +} diff --git a/sw/restatdesk/app_controller.h b/sw/restatdesk/app_controller.h new file mode 100644 index 0000000..3b685f5 --- /dev/null +++ b/sw/restatdesk/app_controller.h @@ -0,0 +1,110 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// app_controller.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + class ICom; + class IComConfigurator; +} // namespace Electux::App::Com +namespace Electux::App::Logger { + class ILog; +} +namespace Electux::App::Command { + class ICommandFormatter; + class IResponseProcessor; +} + +namespace Electux::App { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class AppController + /// @brief Coordination controller managing config loading, storing, and + /// model change propagation. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class AppController : public IAppController { + public: + AppController( + std::unique_ptr configManager, + std::unique_ptr comChannel, + std::unique_ptr comConfigurator, + std::unique_ptr logger, + std::unique_ptr commandFormatter, + std::unique_ptr responseProcessor + ); + virtual ~AppController() override; + + AppController(const AppController &) = delete; + AppController &operator=(const AppController &) = delete; + + void startup() override; + void shutdown() override; + + const Model::IModel &getModel() const override; + + void onSetupChanged(const Model::SettingsSetup &setup) override; + + void executePlan() override; + + sigc::signal signal_data_received() override; + + void turnOnAllChannels() override; + void turnOffAllChannels() override; + void requestAllChannelsStatus() override; + void resetSystem() override; + void requestBoardId() override; + void requestVersion() override; + + private: + void configureLogger(); + void configureComChannel(); + bool hasSerialConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig + ); + bool hasGeneralConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig + ); + bool hasBleConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig + ); + bool hasLoggerConfigChanged( + const Model::IModel &oldConfig, const Model::IModel &newConfig + ); + + void readLoop(); + + std::unique_ptr m_configManager; + std::unique_ptr m_comChannel; + std::unique_ptr m_comConfigurator; + std::unique_ptr m_logger; + std::unique_ptr m_commandFormatter; + std::unique_ptr m_responseProcessor; + + std::thread m_readThread; + std::atomic m_stopThread{false}; + sigc::signal m_signalDataReceived; + }; +} // namespace Electux::App diff --git a/sw/restatdesk/app_controller_factory.cc b/sw/restatdesk/app_controller_factory.cc new file mode 100644 index 0000000..7f87174 --- /dev/null +++ b/sw/restatdesk/app_controller_factory.cc @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// app_controller_factory.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace Electux::App { + std::unique_ptr createAppController( + std::unique_ptr configManager, + std::unique_ptr comChannel, + std::unique_ptr comConfigurator, + std::unique_ptr logger, + std::unique_ptr commandFormatter, + std::unique_ptr responseProcessor + ) { + return std::make_unique( + std::move(configManager), + std::move(comChannel), + std::move(comConfigurator), + std::move(logger), + std::move(commandFormatter), + std::move(responseProcessor) + ); + } +} // namespace Electux::App diff --git a/sw/restatdesk/app_controller_factory.h b/sw/restatdesk/app_controller_factory.h new file mode 100644 index 0000000..51dbc20 --- /dev/null +++ b/sw/restatdesk/app_controller_factory.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// app_controller_factory.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App { + std::unique_ptr createAppController( + std::unique_ptr configManager, + std::unique_ptr comChannel, + std::unique_ptr comConfigurator, + std::unique_ptr logger, + std::unique_ptr commandFormatter, + std::unique_ptr responseProcessor + ); +} // namespace Electux::App diff --git a/sw/restatdesk/application.cc b/sw/restatdesk/application.cc new file mode 100644 index 0000000..91dd12e --- /dev/null +++ b/sw/restatdesk/application.cc @@ -0,0 +1,378 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// application.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Application Internal Constants + /// @{ + constexpr std::string_view cApplicationId{"electux.io.restatdesk"}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Application Mapper Parameters + /// @{ + constexpr std::string_view cDetailedActionName{"app.quit"}; + constexpr std::string_view cKeyboardAccelerator{"q"}; + constexpr std::string_view cFileQuitActionName{"quit"}; + constexpr std::string_view cOptionSettingsActionName{"settings"}; + constexpr std::string_view cHelpDocActionName{"doc"}; + constexpr std::string_view cHelpAboutActionName{"about"}; + constexpr std::string_view cCmdAllOnActionName{"cmd_all_on"}; + constexpr std::string_view cCmdAllOffActionName{"cmd_all_off"}; + constexpr std::string_view cCmdAllStatActionName{"cmd_all_stat"}; + constexpr std::string_view cCmdSysResetActionName{"cmd_sys_reset"}; + constexpr std::string_view cCmdSysIdActionName{"cmd_sys_id"}; + constexpr std::string_view cCmdSysVersionActionName{"cmd_sys_version"}; + constexpr std::string_view cCmdExecutePlanActionName{"cmd_execute_plan"}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Application Menu Labels and Actions + /// @{ + constexpr std::string_view cFileLabel{"File"}; + constexpr std::string_view cFileQuitLabel{"_Quit"}; + constexpr std::string_view cFileQuitDetailedAction{"app.quit"}; + constexpr std::string_view cOptionLabel{"Option"}; + constexpr std::string_view cOptionSettingsLabel{"_Settings"}; + constexpr std::string_view cOptionSettingsDetailedAction{"app.settings"}; + constexpr std::string_view cCommandLabel{"Command"}; + constexpr std::string_view cCmdAllOnLabel{"_All Channels On"}; + constexpr std::string_view cCmdAllOnDetailedAction{"app.cmd_all_on"}; + constexpr std::string_view cCmdAllOffLabel{"_All Channels Off"}; + constexpr std::string_view cCmdAllOffDetailedAction{"app.cmd_all_off"}; + constexpr std::string_view cCmdAllStatLabel{"_All Status"}; + constexpr std::string_view cCmdAllStatDetailedAction{"app.cmd_all_stat"}; + constexpr std::string_view cCmdSysResetLabel{"_System Reset"}; + constexpr std::string_view cCmdSysResetDetailedAction{"app.cmd_sys_reset"}; + constexpr std::string_view cCmdSysIdLabel{"_Get Board ID"}; + constexpr std::string_view cCmdSysIdDetailedAction{"app.cmd_sys_id"}; + constexpr std::string_view cCmdSysVersionLabel{"_Get Version"}; + constexpr std::string_view cCmdSysVersionDetailedAction{"app.cmd_sys_version"}; + constexpr std::string_view cCmdExecutePlanLabel{"_Execute Plan"}; + constexpr std::string_view cCmdExecutePlanDetailedAction{"app.cmd_execute_plan"}; + constexpr std::string_view cHelpLabel{"Help"}; + constexpr std::string_view cHelpDocLabel{"_Documentation"}; + constexpr std::string_view cHelpDocDetailedAction{"app.doc"}; + constexpr std::string_view cHelpAboutLabel{"_About"}; + constexpr std::string_view cHelpAboutDetailedAction{"app.about"}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Application Console Messages + /// @{ + constexpr std::string_view cStartupMsg{"Startup application..."}; + constexpr std::string_view cStartupDoneMsg{"Startup application done."}; + constexpr std::string_view cActivateMsg{"Activate application..."}; + constexpr std::string_view cActivateDoneMsg{"Activate application done."}; + constexpr std::string_view cShutdownMsg{"Shutting down application..."}; + constexpr std::string_view cQuitMsg{"Quit application."}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace + +using namespace Electux::App; + +EntryApplication::EntryApplication(bool verbose) : Gtk::Application(cApplicationId.data()), m_verbose(verbose) { + auto config = Model::createDefault(); + auto configManager = Config::createConfigManager(std::move(config), m_verbose); + + auto serial = Com::createSerialCom(m_verbose); + auto *serialPtr = serial.get(); + auto serialConfigurator = Com::createSerialConfigurator(serialPtr); + + auto tcp = Com::createTcpCom(m_verbose); + auto *tcpPtr = tcp.get(); + auto tcpConfigurator = Com::createTcpConfigurator(tcpPtr); + + auto ble = Com::createBleCom(m_verbose); + auto *blePtr = ble.get(); + auto bleConfigurator = Com::createBleConfigurator(blePtr); + + auto switchableCom = Com::createSwitchableCom( + m_verbose, std::move(serial), std::move(tcp), std::move(ble) + ); + auto *switchableComPtr = switchableCom.get(); + + auto configurator = Com::createSwitchableConfigurator( + switchableComPtr, std::move(serialConfigurator), + std::move(tcpConfigurator), std::move(bleConfigurator) + ); + + auto logger = Logger::createLogger(); + auto commandFormatter = Command::createCommandFormatter(); + auto responseProcessor = Command::createResponseProcessor(); + + m_controller = createAppController( + std::move(configManager), std::move(switchableCom), + std::move(configurator), std::move(logger), std::move(commandFormatter), + std::move(responseProcessor) + ); + + Glib::set_application_name(cApplicationId.data()); +} + +EntryApplication::~EntryApplication() = default; + +Glib::RefPtr EntryApplication::create(bool verbose) { + return Glib::make_refptr_for_instance( + new EntryApplication(verbose) + ); +} + +void EntryApplication::mapping() { + set_accel_for_action( + cDetailedActionName.data(), cKeyboardAccelerator.data() + ); + + add_action( + cFileQuitActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionQuit) + ); + add_action( + cOptionSettingsActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionSettings) + ); + add_action( + cCmdAllOnActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionCmdAllOn) + ); + add_action( + cCmdAllOffActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionCmdAllOff) + ); + add_action( + cCmdAllStatActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionCmdAllStat) + ); + add_action( + cCmdSysResetActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionCmdSysReset) + ); + add_action( + cCmdSysIdActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionCmdSysId) + ); + add_action( + cCmdSysVersionActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionCmdSysVersion) + ); + add_action( + cCmdExecutePlanActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionCmdExecutePlan) + ); + add_action( + cHelpDocActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionDoc) + ); + add_action( + cHelpAboutActionName.data(), + sigc::mem_fun(*this, &EntryApplication::onActionAbout) + ); + + m_home->connect_close_request( + sigc::mem_fun(*this, &EntryApplication::onHandleClose) + ); + m_settings->setupChanged().connect( + sigc::mem_fun(*this, &EntryApplication::onSetupChanged) + ); + m_home->controlChanged().connect( + sigc::mem_fun(*this, &EntryApplication::onSetupChanged) + ); + m_home->signal_execute_plan().connect( + sigc::mem_fun(*this, &EntryApplication::onActionCmdExecutePlan) + ); + m_controller->signal_data_received().connect( + sigc::mem_fun(*m_home, &View::IHomeView::postData) + ); +} + +void EntryApplication::on_startup() { + if (m_verbose) { + std::cout << cStartupMsg << std::endl; + } + Gtk::Application::on_startup(); + + m_home = std::make_unique(); + m_settings = std::make_unique(); + m_help = std::make_unique(); + m_about = std::make_unique(); + + m_controller->startup(); + + auto menu = Gio::Menu::create(); + auto submenu_file = Gio::Menu::create(); + submenu_file->append(cFileQuitLabel.data(), cFileQuitDetailedAction.data()); + menu->append_submenu(cFileLabel.data(), submenu_file); + + auto submenu_option = Gio::Menu::create(); + submenu_option->append( + cOptionSettingsLabel.data(), cOptionSettingsDetailedAction.data() + ); + menu->append_submenu(cOptionLabel.data(), submenu_option); + + auto submenu_command = Gio::Menu::create(); + submenu_command->append( + cCmdAllOnLabel.data(), cCmdAllOnDetailedAction.data() + ); + submenu_command->append( + cCmdAllOffLabel.data(), cCmdAllOffDetailedAction.data() + ); + submenu_command->append( + cCmdAllStatLabel.data(), cCmdAllStatDetailedAction.data() + ); + submenu_command->append( + cCmdSysResetLabel.data(), cCmdSysResetDetailedAction.data() + ); + submenu_command->append( + cCmdSysIdLabel.data(), cCmdSysIdDetailedAction.data() + ); + submenu_command->append( + cCmdSysVersionLabel.data(), cCmdSysVersionDetailedAction.data() + ); + submenu_command->append( + cCmdExecutePlanLabel.data(), cCmdExecutePlanDetailedAction.data() + ); + menu->append_submenu(cCommandLabel.data(), submenu_command); + + auto submenu_help = Gio::Menu::create(); + submenu_help->append(cHelpDocLabel.data(), cHelpDocDetailedAction.data()); + submenu_help->append( + cHelpAboutLabel.data(), cHelpAboutDetailedAction.data() + ); + menu->append_submenu(cHelpLabel.data(), submenu_help); + set_menubar(menu); + mapping(); + add_window(m_home->getGtkWindow()); + + m_controller->getModel().signal_changed().connect([this]() { + SettingsSetup setup; + setup.m_config = m_controller->getModel().clone(); + m_settings->setSettingsSetup(setup); + m_settings->updateUiData(); + m_home->setControlSetup(setup); + m_home->updateUiData(); + }); + + SettingsSetup setup; + setup.m_config = m_controller->getModel().clone(); + m_settings->setSettingsSetup(setup); + m_settings->updateUiData(); + m_home->setControlSetup(setup); + m_home->updateUiData(); + + if (m_verbose) { + std::cout << cStartupDoneMsg << std::endl; + } +} + +void EntryApplication::on_activate() { + if (m_verbose) { + std::cout << cActivateMsg << std::endl; + } + Gtk::Application::on_activate(); + m_home->show(); + if (m_verbose) { + std::cout << cActivateDoneMsg << std::endl; + } +} + +void EntryApplication::on_shutdown() { + if (m_verbose) { + std::cout << cShutdownMsg << std::endl; + } + m_controller->shutdown(); + Gtk::Application::on_shutdown(); +} + +void EntryApplication::onActionQuit() { + if (m_verbose) { + std::cout << cQuitMsg << std::endl; + } + m_home->hide(); + remove_window(m_home->getGtkWindow()); + quit(); +} + +bool EntryApplication::onHandleClose() { + onActionQuit(); + return false; +} + +void EntryApplication::onActionSettings() { m_settings->show(); } + +void EntryApplication::onActionDoc() { m_help->show(); } + +void EntryApplication::onActionAbout() { m_about->show(); } + +void EntryApplication::onSetupChanged(const SettingsSetup &setup) { + m_controller->onSetupChanged(setup); +} + +void EntryApplication::onActionCmdAllOn() { + m_controller->turnOnAllChannels(); +} + +void EntryApplication::onActionCmdAllOff() { + m_controller->turnOffAllChannels(); +} + +void EntryApplication::onActionCmdAllStat() { + m_controller->requestAllChannelsStatus(); +} + +void EntryApplication::onActionCmdSysReset() { + m_controller->resetSystem(); +} + +void EntryApplication::onActionCmdSysId() { + m_controller->requestBoardId(); +} + +void EntryApplication::onActionCmdSysVersion() { + m_controller->requestVersion(); +} + +void EntryApplication::onActionCmdExecutePlan() { + m_controller->executePlan(); +} diff --git a/sw/restatdesk/application.h b/sw/restatdesk/application.h new file mode 100644 index 0000000..af68e46 --- /dev/null +++ b/sw/restatdesk/application.h @@ -0,0 +1,89 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// application.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App { + class IAppController; + + namespace Model { + class SettingsSetup; + } + + namespace View { + class IHomeView; + namespace Settings { + class ISettingsView; + } + namespace Help { + class IHelpView; + } + namespace About { + class IAboutView; + } + } // namespace View + + using SettingsSetup = Model::SettingsSetup; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class EntryApplication + /// @brief Entry point for application and main application class. + /// + /// Manages the application lifecycle, signal mapping, and coordinates + /// between the configuration manager and the various UI views. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class EntryApplication : public Gtk::Application { + public: + explicit EntryApplication(bool verbose = false); + ~EntryApplication() override; + + static Glib::RefPtr create(bool verbose = false); + + protected: + void on_startup() override; + void on_activate() override; + void on_shutdown() override; + + private: + void mapping(); + void onActionSettings(); + void onActionDoc(); + void onActionAbout(); + void onActionQuit(); + void onActionCmdAllOn(); + void onActionCmdAllOff(); + void onActionCmdAllStat(); + void onActionCmdSysReset(); + void onActionCmdSysId(); + void onActionCmdSysVersion(); + void onActionCmdExecutePlan(); + bool onHandleClose(); + void onSetupChanged(const SettingsSetup &setup); + + bool m_verbose{false}; + std::unique_ptr m_controller; + std::unique_ptr m_home; + std::unique_ptr m_settings; + std::unique_ptr m_help; + std::unique_ptr m_about; + }; +} // namespace Electux::App diff --git a/sw/restatdesk/com/.editorconfig b/sw/restatdesk/com/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/ble/.editorconfig b/sw/restatdesk/com/ble/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/ble/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/ble/ble_com.cc b/sw/restatdesk/com/ble/ble_com.cc new file mode 100644 index 0000000..91fcf6b --- /dev/null +++ b/sw/restatdesk/com/ble/ble_com.cc @@ -0,0 +1,136 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_com.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +using namespace Electux::App::Com; + +namespace { + constexpr std::string_view cConstructorMsg{"BleCom constructor called."}; + constexpr std::string_view cDestructorMsg{"BleCom destructor called."}; + constexpr std::string_view cOpenSuccessMsg{"BleCom opened successfully."}; + constexpr std::string_view cCloseSuccessMsg{"BleCom closed successfully."}; + constexpr std::string_view cWriteError{"BleCom write error: Connection is not open."}; + constexpr std::chrono::seconds cReadTimeout{5}; +} // namespace + +BleCom::BleCom(bool verbose) + : m_address(""), + m_serviceUuid(""), + m_rxUuid(""), + m_txUuid(""), + m_verbose(verbose), + m_client(nullptr) { + if (m_verbose) { + std::cout << cConstructorMsg << std::endl; + } +} + +BleCom::~BleCom() noexcept { + close(); + if (m_verbose) { + std::cout << cDestructorMsg << std::endl; + } +} + +bool BleCom::open() { + if (isOpen()) { + return true; + } + + m_client = std::make_unique(m_address, m_serviceUuid, m_rxUuid, m_txUuid, m_verbose); + + auto callback = [this](const std::vector &data) { + onNotificationReceived(data); + }; + + if (m_client->connect(callback)) { + if (m_verbose) { + std::cout << cOpenSuccessMsg << std::endl; + } + return true; + } + + m_client.reset(); + return false; +} + +bool BleCom::close() { + if (m_client) { + m_client->disconnect(); + m_client.reset(); + if (m_verbose) { + std::cout << cCloseSuccessMsg << std::endl; + } + return true; + } + return false; +} + +bool BleCom::isOpen() const { + return m_client && m_client->isConnected(); +} + +void BleCom::read(std::vector &data, size_t len) { + if (!isOpen()) { + return; + } + + data.clear(); + std::unique_lock lock(m_bufferMutex); + bool success = m_bufferCv.wait_for(lock, cReadTimeout, [this, len]() { + return m_readBuffer.size() >= len; + }); + + if (success) { + data.assign(m_readBuffer.begin(), m_readBuffer.begin() + static_cast::difference_type>(len)); + m_readBuffer.erase(m_readBuffer.begin(), m_readBuffer.begin() + static_cast::difference_type>(len)); + } else { + size_t toCopy = std::min(len, m_readBuffer.size()); + data.assign(m_readBuffer.begin(), m_readBuffer.begin() + static_cast::difference_type>(toCopy)); + m_readBuffer.erase(m_readBuffer.begin(), m_readBuffer.begin() + static_cast::difference_type>(toCopy)); + } +} + +void BleCom::write(const std::vector &data) { + if (!isOpen()) { + std::cerr << cWriteError << std::endl; + return; + } + m_client->write(data); +} + +void BleCom::setBleAddress(const std::string &address) { m_address = address; } + +void BleCom::setServiceUuid(const std::string &uuid) { m_serviceUuid = uuid; } + +void BleCom::setRxUuid(const std::string &uuid) { m_rxUuid = uuid; } + +void BleCom::setTxUuid(const std::string &uuid) { m_txUuid = uuid; } + +void BleCom::onNotificationReceived(const std::vector &data) { + std::lock_guard lock(m_bufferMutex); + m_readBuffer.insert(m_readBuffer.end(), data.begin(), data.end()); + m_bufferCv.notify_all(); +} diff --git a/sw/restatdesk/com/ble/ble_com.h b/sw/restatdesk/com/ble/ble_com.h new file mode 100644 index 0000000..9dc13ad --- /dev/null +++ b/sw/restatdesk/com/ble/ble_com.h @@ -0,0 +1,72 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_com.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class BleCom + /// @brief Implementation of BLE communication using BluezBleClient. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class BleCom : public ICom, public IBle { + public: + explicit BleCom(bool verbose = false); + ~BleCom() noexcept override; + + BleCom(const BleCom &) = delete; + BleCom &operator=(const BleCom &) = delete; + + // ICom overrides + bool open() override; + bool close() override; + bool isOpen() const override; + void read(std::vector &data, size_t len) override; + void write(const std::vector &data) override; + + // IBle overrides + void setBleAddress(const std::string &address) override; + void setServiceUuid(const std::string &uuid) override; + void setRxUuid(const std::string &uuid) override; + void setTxUuid(const std::string &uuid) override; + + private: + void onNotificationReceived(const std::vector &data); + + std::string m_address; + std::string m_serviceUuid; + std::string m_rxUuid; + std::string m_txUuid; + + bool m_verbose; + std::unique_ptr m_client; + + std::vector m_readBuffer; + mutable std::mutex m_bufferMutex; + std::condition_variable m_bufferCv; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/ble/bluez/.editorconfig b/sw/restatdesk/com/ble/bluez/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/ble/bluez/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/ble/bluez/bluez_ble_client.cc b/sw/restatdesk/com/ble/bluez/bluez_ble_client.cc new file mode 100644 index 0000000..8135e0b --- /dev/null +++ b/sw/restatdesk/com/ble/bluez/bluez_ble_client.cc @@ -0,0 +1,341 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// bluez_ble_client.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +using namespace Electux::App::Com; + +namespace { + Glib::ustring get_string_from_variant(const Glib::VariantBase& var) { + gsize length = 0; + const gchar* str = g_variant_get_string(const_cast(var.gobj()), &length); // NOLINT(cppcoreguidelines-pro-type-const-cast) + return Glib::ustring(str, length); + } + + bool get_bool_from_variant(const Glib::VariantBase& var) { + return g_variant_get_boolean(const_cast(var.gobj())) != 0; // NOLINT(cppcoreguidelines-pro-type-const-cast) + } + + constexpr const char* cDbusSessionEnv{"RESTATDESK_DBUS_SESSION"}; + constexpr const char* cBluezService{"org.bluez"}; + constexpr const char* cDbusObjectManagerPath{"/"}; + constexpr const char* cDbusObjectManagerInterface{"org.freedesktop.DBus.ObjectManager"}; + constexpr const char* cGetManagedObjectsMethod{"GetManagedObjects"}; + constexpr const char* cDbusPropertiesInterface{"org.freedesktop.DBus.Properties"}; + constexpr const char* cDeviceInterface{"org.bluez.Device1"}; + constexpr const char* cConnectedProp{"Connected"}; + constexpr const char* cGetMethod{"Get"}; + constexpr const char* cConnectMethod{"Connect"}; + constexpr const char* cServicesResolvedProp{"ServicesResolved"}; + constexpr const char* cPropertiesChangedSignal{"PropertiesChanged"}; + constexpr const char* cGattCharacteristicInterface{"org.bluez.GattCharacteristic1"}; + constexpr const char* cStartNotifyMethod{"StartNotify"}; + constexpr const char* cStopNotifyMethod{"StopNotify"}; + constexpr const char* cDisconnectMethod{"Disconnect"}; + constexpr const char* cWriteValueMethod{"WriteValue"}; + constexpr const char* cValueProp{"Value"}; + constexpr const char* cByteArrayType{"ay"}; + + constexpr const char* cConnectIncompleteError{"BluezBleClient connect error: BLE configuration is incomplete."}; + constexpr const char* cConnectDbusFailedError{"BluezBleClient connect error: Failed to connect to D-Bus ("}; + constexpr const char* cConnectDeviceNotFoundError{"BluezBleClient connect error: Device with address "}; + constexpr const char* cConnectDeviceNotFoundSuffix{" not found in managed objects."}; + constexpr const char* cConnectServicesTimeoutError{"BluezBleClient connect error: GATT services could not be resolved in time."}; + constexpr const char* cConnectCharsNotFoundError{"BluezBleClient connect error: GATT Characteristics matching RX/TX UUIDs not found."}; + constexpr const char* cConnectSuccessMsg{"BluezBleClient connected successfully to device: "}; + constexpr const char* cConnectDbusExceptionError{"BluezBleClient connect error: D-Bus call failed: "}; + constexpr const char* cDisconnectSuccessMsg{"BluezBleClient disconnected successfully."}; + constexpr const char* cWriteNotOpenError{"BluezBleClient write error: Connection is not open."}; + constexpr const char* cWriteExceptionError{"BluezBleClient write error: "}; + constexpr int cMaxServiceResolveRetries{30}; + constexpr std::chrono::milliseconds cServiceResolveRetryInterval{500}; +} // namespace + +BluezBleClient::BluezBleClient( + const std::string &address, + const std::string &serviceUuid, + const std::string &rxUuid, + const std::string &txUuid, + bool verbose +) : m_address(address), + m_serviceUuid(serviceUuid), + m_rxUuid(rxUuid), + m_txUuid(txUuid), + m_connected(false), + m_verbose(verbose), + m_subscriptionId(0) {} + +BluezBleClient::~BluezBleClient() { + disconnect(); +} + +bool BluezBleClient::connect(NotificationCallback callback) { + if (m_connected) { + return true; + } + + if (m_address.empty() || m_serviceUuid.empty() || m_rxUuid.empty() || m_txUuid.empty()) { + std::cerr << cConnectIncompleteError << std::endl; + return false; + } + + try { + bool useSessionBus = (std::getenv(cDbusSessionEnv) != nullptr); + auto busType = useSessionBus ? Gio::DBus::BusType::SESSION : Gio::DBus::BusType::SYSTEM; + m_connection = Gio::DBus::Connection::get_sync(busType); + if (!m_connection) { + std::cerr << cConnectDbusFailedError + << (useSessionBus ? "Session" : "System") << ")." << std::endl; + return false; + } + + auto objManagerProxy = Gio::DBus::Proxy::create_sync( + m_connection, + cBluezService, + cDbusObjectManagerPath, + cDbusObjectManagerInterface + ); + + // Find device path matching MAC address + Glib::VariantContainerBase objectsResult = objManagerProxy->call_sync(cGetManagedObjectsMethod); + Glib::VariantContainerBase objectsBase = Glib::VariantBase::cast_dynamic(objectsResult.get_child(0)); + + Glib::ustring devPath = BluezDeviceResolver::findDevicePath(objectsBase, m_address); + + if (devPath.empty()) { + std::cerr << cConnectDeviceNotFoundError << m_address << cConnectDeviceNotFoundSuffix << std::endl; + return false; + } + + m_devicePath = devPath; + + // Check connection status + auto propProxy = Gio::DBus::Proxy::create_sync( + m_connection, + cBluezService, + m_devicePath, + cDbusPropertiesInterface + ); + + std::vector getArgs; + getArgs.push_back(Glib::Variant::create(cDeviceInterface)); + getArgs.push_back(Glib::Variant::create(cConnectedProp)); + auto getResult = propProxy->call_sync(cGetMethod, Glib::VariantContainerBase::create_tuple(getArgs)); + Glib::VariantBase valBase; + getResult.get_child(valBase, 0); + GVariant* innerGVar = g_variant_get_variant(const_cast(valBase.gobj())); // NOLINT(cppcoreguidelines-pro-type-const-cast) + Glib::VariantBase innerVal(innerGVar, true); + bool isConnected = get_bool_from_variant(innerVal); + + if (!isConnected) { + auto deviceProxy = Gio::DBus::Proxy::create_sync( + m_connection, + cBluezService, + m_devicePath, + cDeviceInterface + ); + deviceProxy->call_sync(cConnectMethod); + } + + // Wait for services to resolve (timeout after 15 seconds) + bool servicesResolved = false; + for (int i = 0; i < cMaxServiceResolveRetries; ++i) { + std::vector getArgs2; + getArgs2.push_back(Glib::Variant::create(cDeviceInterface)); + getArgs2.push_back(Glib::Variant::create(cServicesResolvedProp)); + auto getResult2 = propProxy->call_sync(cGetMethod, Glib::VariantContainerBase::create_tuple(getArgs2)); + Glib::VariantBase valBase2; + getResult2.get_child(valBase2, 0); + GVariant* innerGVar2 = g_variant_get_variant(const_cast(valBase2.gobj())); // NOLINT(cppcoreguidelines-pro-type-const-cast) + Glib::VariantBase innerVal2(innerGVar2, true); + bool isResolved = get_bool_from_variant(innerVal2); + if (isResolved) { + servicesResolved = true; + break; + } + std::this_thread::sleep_for(cServiceResolveRetryInterval); + } + + if (!servicesResolved) { + std::cerr << cConnectServicesTimeoutError << std::endl; + return false; + } + + // Find RX and TX characteristics + if (!BluezDeviceResolver::findGattPaths(objectsBase, m_devicePath, m_serviceUuid, m_rxUuid, m_txUuid, m_rxCharPath, m_txCharPath)) { + std::cerr << cConnectCharsNotFoundError << std::endl; + return false; + } + + // Subscribe to notifications/indications on RX path + m_notificationCallback = callback; + m_subscriptionId = m_connection->signal_subscribe( + sigc::mem_fun(*this, &BluezBleClient::onPropertiesChanged), + cBluezService, + cDbusPropertiesInterface, + cPropertiesChangedSignal, + m_rxCharPath + ); + + // Start notifications on RX Characteristic + auto rxProxy = Gio::DBus::Proxy::create_sync( + m_connection, + cBluezService, + m_rxCharPath, + cGattCharacteristicInterface + ); + rxProxy->call_sync(cStartNotifyMethod); + + m_connected = true; + if (m_verbose) { + std::cout << cConnectSuccessMsg << m_address << std::endl; + } + return true; + } catch (const Glib::Error &ex) { + std::cerr << cConnectDbusExceptionError << ex.what() << std::endl; + disconnect(); + return false; + } +} + +bool BluezBleClient::disconnect() { + if (m_connected) { + if (!m_rxCharPath.empty() && m_connection) { + try { + auto rxProxy = Gio::DBus::Proxy::create_sync( + m_connection, + cBluezService, + m_rxCharPath, + cGattCharacteristicInterface + ); + rxProxy->call_sync(cStopNotifyMethod); + } catch (...) {} + } + if (m_subscriptionId > 0 && m_connection) { + m_connection->signal_unsubscribe(m_subscriptionId); + m_subscriptionId = 0; + } + if (!m_devicePath.empty() && m_connection) { + try { + auto deviceProxy = Gio::DBus::Proxy::create_sync( + m_connection, + cBluezService, + m_devicePath, + cDeviceInterface + ); + deviceProxy->call_sync(cDisconnectMethod); + } catch (...) {} + } + m_connected = false; + m_devicePath.clear(); + m_rxCharPath.clear(); + m_txCharPath.clear(); + m_connection.reset(); + m_notificationCallback = nullptr; + if (m_verbose) { + std::cout << cDisconnectSuccessMsg << std::endl; + } + return true; + } + return false; +} + +bool BluezBleClient::isConnected() const { return m_connected; } + +void BluezBleClient::write(const std::vector &data) { + if (!isConnected() || m_txCharPath.empty() || !m_connection) { + std::cerr << cWriteNotOpenError << std::endl; + return; + } + + try { + auto txProxy = Gio::DBus::Proxy::create_sync( + m_connection, + cBluezService, + m_txCharPath, + cGattCharacteristicInterface + ); + + auto dataVariant = Glib::Variant>::create(data); + std::map optionsMap; + auto optionsVariant = Glib::Variant>::create(optionsMap); + + std::vector tupleChildren; + tupleChildren.push_back(dataVariant); + tupleChildren.push_back(optionsVariant); + + auto parameters = Glib::VariantContainerBase::create_tuple(tupleChildren); + txProxy->call_sync(cWriteValueMethod, parameters); + } catch (const Glib::Error &ex) { + std::cerr << cWriteExceptionError << ex.what() << std::endl; + disconnect(); + } +} + +void BluezBleClient::onPropertiesChanged( + const Glib::RefPtr& connection, + const Glib::ustring& sender_name, + const Glib::ustring& object_path, + const Glib::ustring& interface_name, + const Glib::ustring& signal_name, + const Glib::VariantContainerBase& parameters +) { + (void)connection; + (void)sender_name; + (void)signal_name; + if (parameters.get_n_children() < 2) return; + + Glib::Variant interfaceVariant; + parameters.get_child(interfaceVariant, 0); + Glib::ustring targetInterface = interfaceVariant.get(); + + if (targetInterface == cGattCharacteristicInterface && object_path == m_rxCharPath) { + Glib::VariantContainerBase changedProps = Glib::VariantBase::cast_dynamic(parameters.get_child(1)); + size_t nProps = changedProps.get_n_children(); + for (size_t i = 0; i < nProps; ++i) { + Glib::VariantContainerBase propEntry; + changedProps.get_child(propEntry, i); + + Glib::ustring keyStr = get_string_from_variant(propEntry.get_child(0)); + + if (keyStr == cValueProp) { + Glib::VariantBase valBase = propEntry.get_child(1); + GVariant* innerGVar = g_variant_get_variant(const_cast(valBase.gobj())); // NOLINT(cppcoreguidelines-pro-type-const-cast) + Glib::VariantBase actualVal(innerGVar, true); + if (actualVal.get_type_string() == cByteArrayType) { + gsize n_elements = 0; + gconstpointer data_ptr = g_variant_get_fixed_array(const_cast(actualVal.gobj()), &n_elements, 1); // NOLINT(cppcoreguidelines-pro-type-const-cast) + if (data_ptr && n_elements > 0) { + const uint8_t* raw_bytes = static_cast(data_ptr); + std::vector bytes(raw_bytes, raw_bytes + n_elements); + + if (m_notificationCallback) { + m_notificationCallback(bytes); + } + } + } + } + } + } +} diff --git a/sw/restatdesk/com/ble/bluez/bluez_ble_client.h b/sw/restatdesk/com/ble/bluez/bluez_ble_client.h new file mode 100644 index 0000000..73c80c5 --- /dev/null +++ b/sw/restatdesk/com/ble/bluez/bluez_ble_client.h @@ -0,0 +1,80 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// bluez_ble_client.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class BluezBleClient + /// @brief Low-level BlueZ D-Bus proxy interactions for BLE devices. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class BluezBleClient { + public: + using NotificationCallback = std::function &)>; + + BluezBleClient( + const std::string &address, + const std::string &serviceUuid, + const std::string &rxUuid, + const std::string &txUuid, + bool verbose = false + ); + ~BluezBleClient(); + + BluezBleClient(const BluezBleClient &) = delete; + BluezBleClient &operator=(const BluezBleClient &) = delete; + + bool connect(NotificationCallback callback); + bool disconnect(); + bool isConnected() const; + + void write(const std::vector &data); + + private: + void onPropertiesChanged( + const Glib::RefPtr& connection, + const Glib::ustring& sender_name, + const Glib::ustring& object_path, + const Glib::ustring& interface_name, + const Glib::ustring& signal_name, + const Glib::VariantContainerBase& parameters + ); + + std::string m_address; + std::string m_serviceUuid; + std::string m_rxUuid; + std::string m_txUuid; + + bool m_connected; + bool m_verbose; + Glib::RefPtr m_connection; + Glib::ustring m_devicePath; + Glib::ustring m_rxCharPath; + Glib::ustring m_txCharPath; + guint m_subscriptionId; + + NotificationCallback m_notificationCallback; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/ble/bluez/bluez_device_resolver.cc b/sw/restatdesk/com/ble/bluez/bluez_device_resolver.cc new file mode 100644 index 0000000..162ca49 --- /dev/null +++ b/sw/restatdesk/com/ble/bluez/bluez_device_resolver.cc @@ -0,0 +1,181 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// bluez_device_resolver.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +using namespace Electux::App::Com; + +namespace { + Glib::ustring get_string_from_variant(const Glib::VariantBase& var) { + gsize length = 0; + const gchar* str = g_variant_get_string(const_cast(var.gobj()), &length); // NOLINT(cppcoreguidelines-pro-type-const-cast) + return Glib::ustring(str, length); + } + + Glib::ustring getStringProperty(const Glib::VariantBase& propValVar) { + GVariant* innerGVar = g_variant_get_variant(const_cast(propValVar.gobj())); // NOLINT(cppcoreguidelines-pro-type-const-cast) + Glib::VariantBase inner(innerGVar, true); + return get_string_from_variant(inner); + } + constexpr const char* cDeviceInterface{"org.bluez.Device1"}; + constexpr const char* cAddressProp{"Address"}; + constexpr const char* cGattCharacteristicInterface{"org.bluez.GattCharacteristic1"}; + constexpr const char* cUuidProp{"UUID"}; + constexpr const char* cServiceProp{"Service"}; + constexpr const char* cGattServiceInterface{"org.bluez.GattService1"}; + constexpr const char* cDeviceProp{"Device"}; +} // namespace + +Glib::ustring BluezDeviceResolver::findDevicePath( + const Glib::VariantContainerBase &objectsBase, + const std::string &address +) { + size_t nObjects = objectsBase.get_n_children(); + for (size_t i = 0; i < nObjects; ++i) { + Glib::VariantContainerBase objEntry; + objectsBase.get_child(objEntry, i); + + Glib::ustring path = get_string_from_variant(objEntry.get_child(0)); + + Glib::VariantContainerBase interfacesVar = Glib::VariantBase::cast_dynamic(objEntry.get_child(1)); + size_t nInterfaces = interfacesVar.get_n_children(); + for (size_t j = 0; j < nInterfaces; ++j) { + Glib::VariantContainerBase intEntry; + interfacesVar.get_child(intEntry, j); + + Glib::ustring interfaceName = get_string_from_variant(intEntry.get_child(0)); + + if (interfaceName == cDeviceInterface) { + Glib::VariantContainerBase propertiesVar = Glib::VariantBase::cast_dynamic(intEntry.get_child(1)); + size_t nProps = propertiesVar.get_n_children(); + for (size_t k = 0; k < nProps; ++k) { + Glib::VariantContainerBase propEntry; + propertiesVar.get_child(propEntry, k); + + Glib::ustring propName = get_string_from_variant(propEntry.get_child(0)); + + if (propName == cAddressProp) { + Glib::VariantBase propValBase = propEntry.get_child(1); + GVariant* innerGVar = g_variant_get_variant(const_cast(propValBase.gobj())); + Glib::VariantBase inner(innerGVar, true); + Glib::ustring addr = get_string_from_variant(inner); + if (g_ascii_strcasecmp(addr.c_str(), address.c_str()) == 0) { + return path; + } + } + } + } + } + } + return ""; +} + +bool BluezDeviceResolver::findGattPaths( + const Glib::VariantContainerBase &objectsBase, + const Glib::ustring &devicePath, + const std::string &serviceUuid, + const std::string &rxUuid, + const std::string &txUuid, + Glib::ustring &rxPath, + Glib::ustring &txPath +) { + struct CharInfo { + Glib::ustring uuid; + Glib::ustring servicePath; + }; + std::map characteristics; + std::map servicePathToUuid; + std::map servicePathToDevice; + + size_t nObjects = objectsBase.get_n_children(); + for (size_t i = 0; i < nObjects; ++i) { + Glib::VariantContainerBase objEntry; + objectsBase.get_child(objEntry, i); + + Glib::ustring path = get_string_from_variant(objEntry.get_child(0)); + + Glib::VariantContainerBase interfacesVar = Glib::VariantBase::cast_dynamic(objEntry.get_child(1)); + size_t nInterfaces = interfacesVar.get_n_children(); + for (size_t j = 0; j < nInterfaces; ++j) { + Glib::VariantContainerBase intEntry; + interfacesVar.get_child(intEntry, j); + + Glib::ustring interfaceName = get_string_from_variant(intEntry.get_child(0)); + + if (interfaceName == cGattCharacteristicInterface) { + Glib::VariantContainerBase propertiesVar = Glib::VariantBase::cast_dynamic(intEntry.get_child(1)); + size_t nProps = propertiesVar.get_n_children(); + CharInfo info; + for (size_t k = 0; k < nProps; ++k) { + Glib::VariantContainerBase propEntry; + propertiesVar.get_child(propEntry, k); + + Glib::ustring propName = get_string_from_variant(propEntry.get_child(0)); + + if (propName == cUuidProp) { + info.uuid = getStringProperty(propEntry.get_child(1)); + } else if (propName == cServiceProp) { + info.servicePath = getStringProperty(propEntry.get_child(1)); + } + } + characteristics[path] = info; + } else if (interfaceName == cGattServiceInterface) { + Glib::VariantContainerBase propertiesVar = Glib::VariantBase::cast_dynamic(intEntry.get_child(1)); + size_t nProps = propertiesVar.get_n_children(); + Glib::ustring uuid; + Glib::ustring devPath; + for (size_t k = 0; k < nProps; ++k) { + Glib::VariantContainerBase propEntry; + propertiesVar.get_child(propEntry, k); + + Glib::ustring propName = get_string_from_variant(propEntry.get_child(0)); + + if (propName == cUuidProp) { + uuid = getStringProperty(propEntry.get_child(1)); + } else if (propName == cDeviceProp) { + devPath = getStringProperty(propEntry.get_child(1)); + } + } + servicePathToUuid[path] = uuid; + servicePathToDevice[path] = devPath; + } + } + } + + rxPath.clear(); + txPath.clear(); + for (const auto& [path, info] : characteristics) { + Glib::ustring servicePath = info.servicePath; + if (servicePathToDevice[servicePath] == devicePath) { + Glib::ustring serviceUuid_found = servicePathToUuid[servicePath]; + if (g_ascii_strcasecmp(serviceUuid_found.c_str(), serviceUuid.c_str()) == 0) { + if (g_ascii_strcasecmp(info.uuid.c_str(), rxUuid.c_str()) == 0) { + rxPath = path; + } + if (g_ascii_strcasecmp(info.uuid.c_str(), txUuid.c_str()) == 0) { + txPath = path; + } + } + } + } + + return !rxPath.empty() && !txPath.empty(); +} diff --git a/sw/restatdesk/com/ble/bluez/bluez_device_resolver.h b/sw/restatdesk/com/ble/bluez/bluez_device_resolver.h new file mode 100644 index 0000000..0df49a1 --- /dev/null +++ b/sw/restatdesk/com/ble/bluez/bluez_device_resolver.h @@ -0,0 +1,51 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// bluez_device_resolver.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class BluezDeviceResolver + /// @brief Utility class to parse and resolve BlueZ D-Bus object paths. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class BluezDeviceResolver { + public: + BluezDeviceResolver() = delete; + ~BluezDeviceResolver() = delete; + + static Glib::ustring findDevicePath( + const Glib::VariantContainerBase &objectsBase, + const std::string &address + ); + + static bool findGattPaths( + const Glib::VariantContainerBase &objectsBase, + const Glib::ustring &devicePath, + const std::string &serviceUuid, + const std::string &rxUuid, + const std::string &txUuid, + Glib::ustring &rxPath, + Glib::ustring &txPath + ); + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/ble/configurator/.editorconfig b/sw/restatdesk/com/ble/configurator/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/ble/configurator/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/ble/configurator/ble_com_configurator.cc b/sw/restatdesk/com/ble/configurator/ble_com_configurator.cc new file mode 100644 index 0000000..faf3bba --- /dev/null +++ b/sw/restatdesk/com/ble/configurator/ble_com_configurator.cc @@ -0,0 +1,54 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_com_configurator.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + BleComConfigurator::BleComConfigurator(IBle *ble) : m_ble(ble) {} + + bool BleComConfigurator::configure( + const Model::IModel &model, ICom *comChannel + ) { + if (m_ble == nullptr || comChannel == nullptr) { + return false; + } + + auto addrKey = model.toString(Model::ModelBleKey::Address); + auto serviceKey = model.toString(Model::ModelBleKey::ServiceUuid); + auto rxKey = model.toString(Model::ModelBleKey::RxUuid); + auto txKey = model.toString(Model::ModelBleKey::TxUuid); + + std::string addr = model.getEntity(addrKey); + std::string service = model.getEntity(serviceKey); + std::string rx = model.getEntity(rxKey); + std::string tx = model.getEntity(txKey); + + m_ble->setBleAddress(addr); + m_ble->setServiceUuid(service); + m_ble->setRxUuid(rx); + m_ble->setTxUuid(tx); + + return comChannel->open(); + } +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/ble/configurator/ble_com_configurator.h b/sw/restatdesk/com/ble/configurator/ble_com_configurator.h new file mode 100644 index 0000000..ecc0fae --- /dev/null +++ b/sw/restatdesk/com/ble/configurator/ble_com_configurator.h @@ -0,0 +1,53 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_com_configurator.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace Electux::App::Com { + class IBle; + class ICom; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class BleComConfigurator + /// @brief Configures BLE communication parameters using the model. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class BleComConfigurator : public IComConfigurator { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Constructs a new BleComConfigurator object. + /// @param ble Pointer to the IBle interface representing the BLE channel. + //////////////////////////////////////////////////////////////////////////////////////////////// + explicit BleComConfigurator(IBle *ble); + + ~BleComConfigurator() override = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the BLE connection. + /// @param model Reference to the configuration model. + /// @param comChannel Pointer to the communication channel interface. + /// @return true if configuration was successful, else false. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool configure(const Model::IModel &model, ICom *comChannel) override; + + private: + IBle *m_ble; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/ble/ible.h b/sw/restatdesk/com/ble/ible.h new file mode 100644 index 0000000..58b89c0 --- /dev/null +++ b/sw/restatdesk/com/ble/ible.h @@ -0,0 +1,57 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ible.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IBle + /// @brief Interface for BLE communication configuration parameters. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IBle { + public: + virtual ~IBle() = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the target MAC address or name for the BLE device. + /// @param address The device address or name. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setBleAddress(const std::string &address) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the target Service UUID. + /// @param uuid The Service UUID. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setServiceUuid(const std::string &uuid) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the target RX Characteristic UUID. + /// @param uuid The RX Characteristic UUID. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setRxUuid(const std::string &uuid) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the target TX Characteristic UUID. + /// @param uuid The TX Characteristic UUID. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setTxUuid(const std::string &uuid) = 0; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/com_factory.cc b/sw/restatdesk/com/com_factory.cc new file mode 100644 index 0000000..d65b258 --- /dev/null +++ b/sw/restatdesk/com/com_factory.cc @@ -0,0 +1,53 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// com_factory.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + std::unique_ptr createSerialCom(bool verbose) { + return std::make_unique(verbose); + } + + std::unique_ptr createTcpCom(bool verbose) { + return std::make_unique(verbose); + } + + std::unique_ptr createBleCom(bool verbose) { + return std::make_unique(verbose); + } + + std::unique_ptr createSwitchableCom( + bool verbose, + std::unique_ptr serialCom, + std::unique_ptr tcpCom, + std::unique_ptr bleCom + ) { + return std::make_unique( + verbose, + std::move(serialCom), + std::move(tcpCom), + std::move(bleCom) + ); + } +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/com_factory.h b/sw/restatdesk/com/com_factory.h new file mode 100644 index 0000000..bc8eb3c --- /dev/null +++ b/sw/restatdesk/com/com_factory.h @@ -0,0 +1,35 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// com_factory.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Com { + std::unique_ptr createSerialCom(bool verbose = false); + std::unique_ptr createTcpCom(bool verbose = false); + std::unique_ptr createBleCom(bool verbose = false); + std::unique_ptr createSwitchableCom( + bool verbose, + std::unique_ptr serialCom, + std::unique_ptr tcpCom, + std::unique_ptr bleCom + ); +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/com_types.h b/sw/restatdesk/com/com_types.h new file mode 100644 index 0000000..0540313 --- /dev/null +++ b/sw/restatdesk/com/com_types.h @@ -0,0 +1,79 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// com_types.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Com { + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Enumeration of communication types. + //////////////////////////////////////////////////////////////////////////////////////////////// + enum class ComType : size_t { Serial = 0, Tcp, Ble, Count }; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Structure containing information about a communication type. + //////////////////////////////////////////////////////////////////////////////////////////////// + struct ComTypeInfo { + ComType type; + std::string_view configKey; + std::string_view displayName; + }; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Array of communication type descriptors. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline constexpr std::array< + ComTypeInfo, static_cast(ComType::Count)> + cComTypeDescriptors{ + {{ComType::Serial, "serial", "Serial Port"}, + {ComType::Tcp, "tcp", "TCP/IP Connection"}, + {ComType::Ble, "ble", "BLE Connection"}} + }; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a ComType to its configuration key string. + /// @param type The ComType to convert. + /// @return The configuration key string for the given ComType. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline constexpr std::string_view toConfigString(ComType type) { + for (const auto &desc : cComTypeDescriptors) { + if (desc.type == type) + return desc.configKey; + } + return cComTypeDescriptors[0].configKey; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a configuration key string to its ComType. + /// @param key The configuration key string to convert. + /// @return The ComType for the given configuration key. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline constexpr ComType fromConfigString(std::string_view key) { + for (const auto &desc : cComTypeDescriptors) { + if (desc.configKey == key) + return desc.type; + } + return ComType::Serial; + } + +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/configurator_factory.cc b/sw/restatdesk/com/configurator_factory.cc new file mode 100644 index 0000000..0e461d9 --- /dev/null +++ b/sw/restatdesk/com/configurator_factory.cc @@ -0,0 +1,61 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// configurator_factory.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + std::unique_ptr createSerialConfigurator(ICom* com) { + auto* concrete = dynamic_cast(com); + return concrete ? std::make_unique(concrete) : nullptr; + } + + std::unique_ptr createTcpConfigurator(ICom* com) { + auto* concrete = dynamic_cast(com); + return concrete ? std::make_unique(concrete) : nullptr; + } + + std::unique_ptr createBleConfigurator(ICom* com) { + auto* concrete = dynamic_cast(com); + return concrete ? std::make_unique(concrete) : nullptr; + } + + std::unique_ptr createSwitchableConfigurator( + ICom* com, + std::unique_ptr serialConfigurator, + std::unique_ptr tcpConfigurator, + std::unique_ptr bleConfigurator + ) { + auto* concrete = dynamic_cast(com); + return concrete ? std::make_unique( + concrete, + std::move(serialConfigurator), + std::move(tcpConfigurator), + std::move(bleConfigurator) + ) : nullptr; + } +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/configurator_factory.h b/sw/restatdesk/com/configurator_factory.h new file mode 100644 index 0000000..7beaa08 --- /dev/null +++ b/sw/restatdesk/com/configurator_factory.h @@ -0,0 +1,36 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// configurator_factory.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Com { + std::unique_ptr createSerialConfigurator(ICom* com); + std::unique_ptr createTcpConfigurator(ICom* com); + std::unique_ptr createBleConfigurator(ICom* com); + std::unique_ptr createSwitchableConfigurator( + ICom* com, + std::unique_ptr serialConfigurator, + std::unique_ptr tcpConfigurator, + std::unique_ptr bleConfigurator + ); +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/icom.h b/sw/restatdesk/com/icom.h new file mode 100644 index 0000000..8819a8a --- /dev/null +++ b/sw/restatdesk/com/icom.h @@ -0,0 +1,86 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// icom.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Com +/// @brief Namespace for application communication components +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ICom + /// @brief Interface for communication implementations. + /// + /// Defines the contract for managing com port lifecycle (open/close), + /// configuration and data exchange (read/write). + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ICom { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Virtual destructor for the ICom interface. + /// Ensures proper resource cleanup in derived communication classes. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline virtual ~ICom() noexcept = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Opens the communication channel. + /// @return True if the channel was successfully opened, false + /// otherwise. Implementation should handle the system call to acquire + /// the device. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool open() = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Closes the communication channel. + /// @return True if the channel was successfully closed, false + /// otherwise. Implementation should ensure buffers are flushed and + /// resources are properly released. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool close() = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Checks if the communication channel is currently open. + /// @return True if the channel is open, false otherwise. + /// Implementation should query the underlying serial port state. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool isOpen() const = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Reads data from the communication channel. + /// @param data Vector buffer where the received bytes will be stored. + /// @param len The number of bytes to read before returning. + /// Implementation should block until 'len' bytes are received or a + /// timeout occurs, and handle any necessary buffering or error + /// conditions. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void read(std::vector &data, size_t len) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Writes data to the communication channel. + /// @param data Vector containing the sequence of bytes to be + /// transmitted. Implementation should handle the system call to send + /// data through the device and ensure that all bytes are transmitted + /// successfully, or handle any errors that may occur during + /// transmission. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void write(const std::vector &data) = 0; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/icom_configurator.h b/sw/restatdesk/com/icom_configurator.h new file mode 100644 index 0000000..965a755 --- /dev/null +++ b/sw/restatdesk/com/icom_configurator.h @@ -0,0 +1,51 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// icom_configurator.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +namespace Electux::App::Model { + class IModel; +} + +namespace Electux::App::Com { + class ICom; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IComConfigurator + /// @brief Interface for protocol-independent configuration of communication + /// channels. + /// + /// This class abstracts the parameters configuration for any communication + /// mechanism (Serial, TCP, etc.) from the AppController. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IComConfigurator { + public: + virtual ~IComConfigurator() = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the communication channel using parameters from + /// the model. + /// @param model Reference to the configuration model. + /// @param comChannel Pointer to the communication channel interface. + /// @return true if configuration was successful, else false. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool + configure(const Model::IModel &model, ICom *comChannel) = 0; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/serial/.editorconfig b/sw/restatdesk/com/serial/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/serial/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/serial/configurator/.editorconfig b/sw/restatdesk/com/serial/configurator/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/serial/configurator/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/serial/configurator/serial_com_configurator.cc b/sw/restatdesk/com/serial/configurator/serial_com_configurator.cc new file mode 100644 index 0000000..fd828d3 --- /dev/null +++ b/sw/restatdesk/com/serial/configurator/serial_com_configurator.cc @@ -0,0 +1,74 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_com_configurator.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + SerialComConfigurator::SerialComConfigurator(ISerial *serial) + : m_serial(serial) {} + + bool SerialComConfigurator::configure( + const Model::IModel &model, ICom *comChannel + ) { + if (m_serial == nullptr || comChannel == nullptr) { + return false; + } + + Com::SerialParams params; + params.device = + model.getEntity(model.toString(Model::ModelSerialKey::Device)); + + uint32_t baudIdx = static_cast(std::stoul( + model.getEntity(model.toString(Model::ModelSerialKey::Baud)) + )); + params.baud = Com::SerialUtils::uintToBaud(baudIdx); + + uint32_t dataIdx = static_cast(std::stoul( + model.getEntity(model.toString(Model::ModelSerialKey::Data)) + )); + params.data = Com::SerialUtils::uintToDataBits(dataIdx); + + uint32_t parityIdx = static_cast(std::stoul( + model.getEntity(model.toString(Model::ModelSerialKey::Parity)) + )); + params.parity = Com::SerialUtils::uintToParity(parityIdx); + + uint32_t stopIdx = static_cast(std::stoul( + model.getEntity(model.toString(Model::ModelSerialKey::Stop)) + )); + params.stop = Com::SerialUtils::uintToStopBits(stopIdx); + + uint32_t flowIdx = static_cast(std::stoul( + model.getEntity(model.toString(Model::ModelSerialKey::Flow)) + )); + params.flow = Com::SerialUtils::uintToFlowControl(flowIdx); + + m_serial->setDevice(params.device); + if (comChannel->open()) { + return m_serial->setup(params); + } + return false; + } +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/serial/configurator/serial_com_configurator.h b/sw/restatdesk/com/serial/configurator/serial_com_configurator.h new file mode 100644 index 0000000..11f6bf4 --- /dev/null +++ b/sw/restatdesk/com/serial/configurator/serial_com_configurator.h @@ -0,0 +1,54 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_com_configurator.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace Electux::App::Com { + class ISerial; + class ICom; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SerialComConfigurator + /// @brief Configures serial communication parameters using the model. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SerialComConfigurator : public IComConfigurator { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Constructs a new SerialComConfigurator object. + /// @param serial Pointer to the ISerial interface representing the + /// serial channel. + //////////////////////////////////////////////////////////////////////////////////////////////// + explicit SerialComConfigurator(ISerial *serial); + + ~SerialComConfigurator() override = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the serial port. + /// @param model Reference to the configuration model. + /// @param comChannel Pointer to the communication channel interface. + /// @return true if configuration was successful, else false. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool configure(const Model::IModel &model, ICom *comChannel) override; + + private: + ISerial *m_serial; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/serial/iserial.h b/sw/restatdesk/com/serial/iserial.h new file mode 100644 index 0000000..6923d13 --- /dev/null +++ b/sw/restatdesk/com/serial/iserial.h @@ -0,0 +1,119 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// iserial.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Com +/// @brief Namespace for application communication components +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @struct SerialParams + /// @brief Configuration structure for serial port parameters. + /// + /// This structure aggregates all necessary settings required to initialize + /// and configure a serial communication session. + //////////////////////////////////////////////////////////////////////////////////////////////////// + struct SerialParams { + std::string device; ///< Path to the serial port device + BaudRate baud; ///< Transmission speed (Baud rate) + CharacterSize data; ///< Number of data bits per character + Parity parity; ///< Parity error-checking scheme + StopBits stop; ///< Number of stop bits to indicate end + FlowControl flow; ///< Hardware or software flow control method + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ISerial + /// @brief Interface for serial communication implementations. + /// + /// Defines the contract for configuring serial port parameters and + /// provides utility methods to convert between LibSerial enums and + /// generic numeric types for easier configuration handling. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ISerial { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Virtual destructor for the ISerial interface. + /// Ensures proper resource cleanup in derived serial communication + /// classes. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline virtual ~ISerial() noexcept = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the serial port with specific parameters. + /// @param params Reference to SerialParams structure (configuration). + /// @return True if setup was successful, false otherwise. + /// Implementation should apply the provided settings to the underlying + /// serial port, returning success status based on the outcome. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool setup(const SerialParams ¶ms) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the serial port device file path. + /// @param device Path to the serial port device. + /// Implementation should apply the provided settings to the underlying + /// serial port. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setDevice(const std::string &device) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the baud rate for the serial port. + /// @param baudRate The desired baud rate. + /// Implementation should call the underlying serial port method to + /// apply the baud rate setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setBaudRate(BaudRate baudRate) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the character size for the serial port. + /// @param characterSize The desired character size. + /// Implementation should call the underlying serial port method to + /// apply the character size setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setCharacterSize(CharacterSize characterSize) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the parity mode for the serial port. + /// @param parity The desired parity mode. + /// Implementation should call the underlying serial port method to + /// apply the parity setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setParity(Parity parity) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the number of stop bits for the serial port. + /// @param stopBits The desired number of stop bits. + /// Implementation should call the underlying serial port method to + /// apply the stop bits setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setStopBits(StopBits stopBits) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the flow control mode for the serial port. + /// @param flowControl The desired flow control mode. + /// Implementation should call the underlying serial port method to + /// apply the flow control setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setFlowControl(FlowControl flowControl) = 0; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/serial/serial_com.cc b/sw/restatdesk/com/serial/serial_com.cc new file mode 100644 index 0000000..9e38ece --- /dev/null +++ b/sw/restatdesk/com/serial/serial_com.cc @@ -0,0 +1,301 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_com.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include + +using namespace Electux::App::Com; + +namespace { + constexpr std::string_view cConstructorMsg{"SerialCom constructor called."}; + constexpr std::string_view cDestructorMsg{"SerialCom destructor called."}; + constexpr std::string_view cCloseErrorMsg{"Close error: Serial port was not closed properly."}; + constexpr std::string_view cExceptionCloseErrorMsg{"Exception in destructor during close(): "}; + constexpr std::string_view cUnknownExceptionMsg{"Unknown exception in SerialCom destructor."}; + constexpr std::string_view cOpenEmptyDeviceError{"Open error: Device path is empty!"}; + constexpr std::string_view cOpenSuccessMsg{"Serial port opened successfully."}; + constexpr std::string_view cOpenExceptionError{"Open error: "}; + constexpr std::string_view cCloseSuccessMsg{"Serial port closed successfully."}; + constexpr std::string_view cReadError{"Read error: Serial port closed."}; + constexpr std::string_view cWriteError{"Write error: Serial port closed."}; + constexpr std::string_view cSetupNotOpenError{"Setup error: Serial port not open."}; + constexpr std::string_view cSetupEmptyDeviceError{"Setup error: Device path is empty!"}; + constexpr std::string_view cSetupExceptionError{"Setup error: "}; +} // namespace + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Constructs a SerialCom object with the given serial port adapter. +/// @param port A unique pointer to an ILibSerialPort implementation. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +SerialCom::SerialCom(bool verbose) + : m_serialPort(std::make_unique()), m_verbose(verbose) { + if (m_verbose) { + std::cout << cConstructorMsg << std::endl; + } +} + +SerialCom::SerialCom(std::unique_ptr port, bool verbose) + : m_serialPort( + port ? std::move(port) : std::make_unique() + ), + m_verbose(verbose) { + if (m_verbose) { + std::cout << cConstructorMsg << std::endl; + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Destructor for the SerialCom class. Ensures the serial port is +/// closed. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +SerialCom::~SerialCom() noexcept { + try { + if (isOpen()) { + if (!close()) { + std::cerr << cCloseErrorMsg + << std::endl; + } + } + } catch (const std::exception &e) { + // Log the error but DO NOT rethrow + std::cerr << cExceptionCloseErrorMsg << e.what() + << std::endl; + } catch (...) { + std::cerr << cUnknownExceptionMsg << std::endl; + } + + if (m_verbose) { + std::cout << cDestructorMsg << std::endl; + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Opens the serial port. +/// @return True if the port was successfully opened, false otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool SerialCom::open() { + if (m_device.empty()) { + std::cerr << cOpenEmptyDeviceError << std::endl; + return false; + } + + if (!isOpen()) { + try { + m_serialPort->Open(m_device); + if (m_verbose) { + std::cout << cOpenSuccessMsg << std::endl; + } + return true; + } catch (const std::exception &e) { + std::cerr << cOpenExceptionError << e.what() << std::endl; + } catch (...) { + std::cerr << cOpenExceptionError << "Unknown error during open." << std::endl; + } + } + + return false; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Closes the serial port. +/// @return True if the port was successfully closed, false otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool SerialCom::close() { + if (isOpen()) { + try { + m_serialPort->Close(); + } catch (...) { + } + if (m_verbose) { + std::cout << cCloseSuccessMsg << std::endl; + } + return true; + } + + return false; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Checks if the serial port is open. +/// @return True if the port is open, false otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool SerialCom::isOpen() const { + bool open = m_serialPort->IsOpen(); + // std::cout << "Serial port is " << (open ? "open." : "closed.") << + // std::endl; + return open; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Reads data from the serial port. +/// @param data A vector to store the read data. +/// @param len The number of bytes to read. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::read(std::vector &data, size_t len) { + if (!isOpen()) { + std::cerr << cReadError << std::endl; + return; + } + + try { + m_serialPort->Read(data, len); + } catch (const LibSerial::ReadTimeout &) { + // Normal timeout when no data is received, do not close the port. + } catch (const std::exception &e) { + if (m_verbose) { + std::cerr << cReadError << ": " << e.what() << std::endl; + } + try { + m_serialPort->Close(); + } catch (...) { + } + } catch (...) { + if (m_verbose) { + std::cerr << cReadError << ": Unknown exception occurred (possibly I/O error)." << std::endl; + } + try { + m_serialPort->Close(); + } catch (...) { + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Writes data to the serial port. +/// @param data A vector containing the data to write. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::write(const std::vector &data) { + if (!isOpen()) { + std::cerr << cWriteError << std::endl; + return; + } + + try { + m_serialPort->Write(data); + } catch (const std::exception &e) { + std::cerr << cWriteError << ": " << e.what() << std::endl; + try { + m_serialPort->Close(); + } catch (...) { + } + } catch (...) { + std::cerr << cWriteError << ": Unknown exception occurred during write." << std::endl; + try { + m_serialPort->Close(); + } catch (...) { + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Configures the serial port device file path. +/// @param device Path to the serial port device. +//////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::setDevice(const std::string &device) { m_device = device; } + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the baud rate for the serial port. +/// @param baudRate The desired baud rate. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::setBaudRate(BaudRate baudRate) { + try { + m_serialPort->SetBaudRate(baudRate); + } catch (...) { + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the character size for the serial port. +/// @param characterSize The desired character size. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::setCharacterSize(CharacterSize characterSize) { + try { + m_serialPort->SetCharacterSize(characterSize); + } catch (...) { + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the parity mode for the serial port. +/// @param parity The desired parity mode. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::setParity(Parity parity) { + try { + m_serialPort->SetParity(parity); + } catch (...) { + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the number of stop bits for the serial port. +/// @param stopBits The desired number of stop bits. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::setStopBits(StopBits stopBits) { + try { + m_serialPort->SetStopBits(stopBits); + } catch (...) { + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the flow control mode for the serial port. +/// @param flowControl The desired flow control mode. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void SerialCom::setFlowControl(FlowControl flowControl) { + try { + m_serialPort->SetFlowControl(flowControl); + } catch (...) { + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Configures the serial port with specific parameters. +/// @param params Reference to SerialParams structure (configuration). +/// @return True if setup was successful, false otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool SerialCom::setup(const SerialParams ¶ms) { + if (!isOpen()) { + std::cerr << cSetupNotOpenError << std::endl; + return false; + } + + if (params.device.empty()) { + std::cerr << cSetupEmptyDeviceError << std::endl; + return false; + } + + try { + setBaudRate(params.baud); + setCharacterSize(params.data); + setParity(params.parity); + setStopBits(params.stop); + setFlowControl(params.flow); + m_device = params.device; + return true; + + } catch (const std::exception &e) { + std::cerr << cSetupExceptionError << e.what() << std::endl; + return false; + } catch (...) { + std::cerr << cSetupExceptionError << "Unknown error during setup." << std::endl; + return false; + } +} diff --git a/sw/restatdesk/com/serial/serial_com.h b/sw/restatdesk/com/serial/serial_com.h new file mode 100644 index 0000000..5be72a7 --- /dev/null +++ b/sw/restatdesk/com/serial/serial_com.h @@ -0,0 +1,143 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_com.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Com +/// @brief Namespace for application communication components +namespace Electux::App::Com { + class ILibSerialPort; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SerialCom + /// @brief Implementation of serial communication using LibSerial. + /// + /// This class implements the ICom interface to provide concrete serial + /// port operations, including hardware configuration and data I/O. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SerialCom : public ICom, public ISerial { + public: + explicit SerialCom(bool verbose = false); + explicit SerialCom( + std::unique_ptr port, bool verbose = false + ); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Destructor for SerialCom. + /// Ensures the serial port is closed and resources are released. + //////////////////////////////////////////////////////////////////////////////////////////////// + ~SerialCom() noexcept; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Opens the serial communication channel. + /// @return True if the channel was successfully opened, false + /// otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool open() final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Closes the serial communication channel. + /// @return True if the channel was successfully closed, false + /// otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool close() final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Checks if the communication channel is currently open. + /// @return True if the channel is open, false otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool isOpen() const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Reads data from the serial communication channel. + /// @param data Vector buffer to store the received bytes. + /// @param len The number of bytes to read before returning. + //////////////////////////////////////////////////////////////////////////////////////////////// + void read(std::vector &data, size_t len) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Writes data to the serial communication channel. + /// @param data Vector containing the sequence of bytes to transmit. + //////////////////////////////////////////////////////////////////////////////////////////////// + void write(const std::vector &data) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the serial port with specific parameters. + /// @param params Reference to SerialParams structure (configuration). + /// @return True if setup was successful, false otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool setup(const SerialParams ¶ms) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the serial port device file path. + /// @param device Path to the serial port device. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setDevice(const std::string &device) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the baud rate for the serial port. + /// @param baudRate The desired baud rate. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setBaudRate(BaudRate baudRate) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the character size for the serial port. + /// @param characterSize The desired character size. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setCharacterSize(CharacterSize characterSize) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the parity mode for the serial port. + /// @param parity The desired parity mode. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setParity(Parity parity) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the number of stop bits for the serial port. + /// @param stopBits The desired number of stop bits. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setStopBits(StopBits stopBits) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the flow control mode for the serial port. + /// @param flowControl The desired flow control mode. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setFlowControl(FlowControl flowControl) final; + + private: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Unique pointer to the ILibSerialPort implementation for + /// serial port operations. + /// @{ + /// @brief Adapter for serial port abstraction + std::unique_ptr m_serialPort{nullptr}; + /// @brief Path to the serial port device (e.g., "/dev/ttyS0"). + std::string m_device{}; + /// @brief Verbose mode for debugging. + bool m_verbose{false}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/serial/serial_com_params.h b/sw/restatdesk/com/serial/serial_com_params.h new file mode 100644 index 0000000..ec447e9 --- /dev/null +++ b/sw/restatdesk/com/serial/serial_com_params.h @@ -0,0 +1,119 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_com_params.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Com::SerialComConstants +/// @brief Namespace for serial communication constants and definitions +namespace Electux::App::Com::SerialComConstants { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Baud Rate Parameters + /// @{ + + /// @brief Supported baud rate string representations + constexpr std::string_view cComBaudRates[]{"110", "300", "600", + "1200", "2400", "4800", + "9600", "19200", "38400", + "57600", "115200", "230400"}; + + constexpr const uint32_t cComBaud110 = 0; ///< Index for 110 baud + constexpr const uint32_t cComBaud300 = 1; ///< Index for 300 baud + constexpr const uint32_t cComBaud600 = 2; ///< Index for 600 baud + constexpr const uint32_t cComBaud1200 = 3; ///< Index for 1200 baud + constexpr const uint32_t cComBaud2400 = 4; ///< Index for 2400 baud + constexpr const uint32_t cComBaud4800 = 5; ///< Index for 4800 baud + constexpr const uint32_t cComBaud9600 = 6; ///< Index for 9600 baud + constexpr const uint32_t cComBaud19200 = 7; ///< Index for 19200 baud + constexpr const uint32_t cComBaud38400 = 8; ///< Index for 38400 baud + constexpr const uint32_t cComBaud57600 = 9; ///< Index for 57600 baud + constexpr const uint32_t cComBaud115200 = 10; ///< Index for 115200 baud + constexpr const uint32_t cComBaud230400 = 11; ///< Index for 230400 baud + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Data Bits Parameters + /// @{ + + /// @brief Supported data bits string representations + constexpr std::string_view cComDataBits[]{"5", "6", "7", "8"}; + + constexpr const uint32_t cComDataBits5 = 0; ///< Index for 5 data bits + constexpr const uint32_t cComDataBits6 = 1; ///< Index for 6 data bits + constexpr const uint32_t cComDataBits7 = 2; ///< Index for 7 data bits + constexpr const uint32_t cComDataBits8 = 3; ///< Index for 8 data bits + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Parity Parameters + /// @{ + + /// @brief Supported parity mode string representations + constexpr std::string_view cComParities[]{"Even", "Odd", "None"}; + + constexpr const uint32_t cComParityEven = 0; ///< Index for even parity + constexpr const uint32_t cComParityOdd = 1; ///< Index for odd parity + constexpr const uint32_t cComParityNone = 2; ///< Index for no parity + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Stop Bits Parameters + /// @{ + + /// @brief Supported stop bits string representations + constexpr std::string_view cComStopBits[]{"1", "2"}; + + constexpr const uint32_t cComStopBits1 = 0; ///< Index for 1 stop bit + constexpr const uint32_t cComStopBits2 = 1; ///< Index for 2 stop bits + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Flow Control Parameters + /// @{ + + /// @brief Supported flow control string representations + constexpr std::string_view cComFlowControls[]{ + "None", "Hardware", "Software" + }; + + constexpr const uint32_t cComFlowControlNone = + 0; ///< Index for no flow control + constexpr const uint32_t cComFlowControlHw = + 1; ///< Index for hardware flow control + constexpr const uint32_t cComFlowControlSw = + 2; ///< Index for software flow control + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Error Indicators + /// @{ + + /// @brief Value used to indicate an invalid or unsupported parameter + constexpr const uint32_t cComInvalidParameter = 127; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace Electux::App::Com::SerialComConstants diff --git a/sw/restatdesk/com/serial/serial_utils.cc b/sw/restatdesk/com/serial/serial_utils.cc new file mode 100644 index 0000000..e9e1b24 --- /dev/null +++ b/sw/restatdesk/com/serial/serial_utils.cc @@ -0,0 +1,189 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_utils.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +using namespace Electux::App::Com; +using namespace Electux::App::Com::SerialComConstants; + +namespace Electux::App::Com::SerialUtils { + uint32_t baudToUint(const BaudRate baud) { + switch (baud) { + case BaudRate::BAUD_110: + return cComBaud110; + case BaudRate::BAUD_300: + return cComBaud300; + case BaudRate::BAUD_600: + return cComBaud600; + case BaudRate::BAUD_1200: + return cComBaud1200; + case BaudRate::BAUD_2400: + return cComBaud2400; + case BaudRate::BAUD_4800: + return cComBaud4800; + case BaudRate::BAUD_9600: + return cComBaud9600; + case BaudRate::BAUD_19200: + return cComBaud19200; + case BaudRate::BAUD_38400: + return cComBaud38400; + case BaudRate::BAUD_57600: + return cComBaud57600; + case BaudRate::BAUD_115200: + return cComBaud115200; + case BaudRate::BAUD_230400: + return cComBaud230400; + default: + return cComInvalidParameter; + } + } + + BaudRate uintToBaud(const uint32_t baud) { + switch (baud) { + case cComBaud110: + return BaudRate::BAUD_110; + case cComBaud300: + return BaudRate::BAUD_300; + case cComBaud600: + return BaudRate::BAUD_600; + case cComBaud1200: + return BaudRate::BAUD_1200; + case cComBaud2400: + return BaudRate::BAUD_2400; + case cComBaud4800: + return BaudRate::BAUD_4800; + case cComBaud9600: + return BaudRate::BAUD_9600; + case cComBaud19200: + return BaudRate::BAUD_19200; + case cComBaud38400: + return BaudRate::BAUD_38400; + case cComBaud57600: + return BaudRate::BAUD_57600; + case cComBaud115200: + return BaudRate::BAUD_115200; + case cComBaud230400: + return BaudRate::BAUD_230400; + } + return BaudRate::BAUD_INVALID; + } + + uint32_t dataBitsToUint(const CharacterSize data) { + switch (data) { + case CharacterSize::CHAR_SIZE_5: + return cComDataBits5; + case CharacterSize::CHAR_SIZE_6: + return cComDataBits6; + case CharacterSize::CHAR_SIZE_7: + return cComDataBits7; + case CharacterSize::CHAR_SIZE_8: + return cComDataBits8; + default: + return cComInvalidParameter; + } + } + + CharacterSize uintToDataBits(const uint32_t data) { + switch (data) { + case cComDataBits5: + return CharacterSize::CHAR_SIZE_5; + case cComDataBits6: + return CharacterSize::CHAR_SIZE_6; + case cComDataBits7: + return CharacterSize::CHAR_SIZE_7; + case cComDataBits8: + return CharacterSize::CHAR_SIZE_8; + } + return CharacterSize::CHAR_SIZE_INVALID; + } + + uint32_t parityToUint(const Parity parity) { + switch (parity) { + case Parity::PARITY_EVEN: + return cComParityEven; + case Parity::PARITY_ODD: + return cComParityOdd; + case Parity::PARITY_NONE: + return cComParityNone; + default: + return cComInvalidParameter; + } + } + + Parity uintToParity(const uint32_t parity) { + switch (parity) { + case cComParityEven: + return Parity::PARITY_EVEN; + case cComParityOdd: + return Parity::PARITY_ODD; + case cComParityNone: + return Parity::PARITY_NONE; + } + return Parity::PARITY_INVALID; + } + + uint32_t stopBitsToUint(const StopBits stop) { + switch (stop) { + case StopBits::STOP_BITS_1: + return cComStopBits1; + case StopBits::STOP_BITS_2: + return cComStopBits2; + default: + return cComInvalidParameter; + } + } + + StopBits uintToStopBits(const uint32_t stop) { + switch (stop) { + case cComStopBits1: + return StopBits::STOP_BITS_1; + case cComStopBits2: + return StopBits::STOP_BITS_2; + } + return StopBits::STOP_BITS_INVALID; + } + + uint32_t flowControlToUint(const FlowControl flow) { + switch (flow) { + case FlowControl::FLOW_CONTROL_NONE: + return cComFlowControlNone; + case FlowControl::FLOW_CONTROL_HARDWARE: + return cComFlowControlHw; + case FlowControl::FLOW_CONTROL_SOFTWARE: + return cComFlowControlSw; + default: + return cComInvalidParameter; + } + } + + FlowControl uintToFlowControl(const uint32_t flow) { + switch (flow) { + case cComFlowControlNone: + return FlowControl::FLOW_CONTROL_NONE; + case cComFlowControlHw: + return FlowControl::FLOW_CONTROL_HARDWARE; + case cComFlowControlSw: + return FlowControl::FLOW_CONTROL_SOFTWARE; + default: + return FlowControl::FLOW_CONTROL_INVALID; + } + } +} // namespace Electux::App::Com::SerialUtils diff --git a/sw/restatdesk/com/serial/serial_utils.h b/sw/restatdesk/com/serial/serial_utils.h new file mode 100644 index 0000000..583287a --- /dev/null +++ b/sw/restatdesk/com/serial/serial_utils.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_utils.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Com::SerialUtils { + uint32_t baudToUint(const BaudRate baud); + BaudRate uintToBaud(const uint32_t baud); + + uint32_t dataBitsToUint(const CharacterSize data); + CharacterSize uintToDataBits(const uint32_t data); + + uint32_t parityToUint(const Parity parity); + Parity uintToParity(const uint32_t parity); + + uint32_t stopBitsToUint(const StopBits stop); + StopBits uintToStopBits(const uint32_t stop); + + uint32_t flowControlToUint(const FlowControl flow); + FlowControl uintToFlowControl(const uint32_t flow); +} // namespace Electux::App::Com::SerialUtils diff --git a/sw/restatdesk/com/serial/serialw/.editorconfig b/sw/restatdesk/com/serial/serialw/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/serial/serialw/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/serial/serialw/SerialPortConstants.h b/sw/restatdesk/com/serial/serialw/SerialPortConstants.h new file mode 100644 index 0000000..5671e6a --- /dev/null +++ b/sw/restatdesk/com/serial/serialw/SerialPortConstants.h @@ -0,0 +1,35 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// SerialPortConstants.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace LibSerial { + class ReadTimeout : public std::runtime_error { + public: + explicit ReadTimeout(const std::string &message) + : std::runtime_error(message) {} + }; + + class NotOpen : public std::runtime_error { + public: + explicit NotOpen(const std::string &message) + : std::runtime_error(message) {} + }; +} // namespace LibSerial diff --git a/sw/restatdesk/com/serial/serialw/ilib.h b/sw/restatdesk/com/serial/serialw/ilib.h new file mode 100644 index 0000000..197eee7 --- /dev/null +++ b/sw/restatdesk/com/serial/serialw/ilib.h @@ -0,0 +1,169 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ilib.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Com +/// @brief Namespace for application communication components +namespace Electux::App::Com +{ + enum class BaudRate : uint32_t + { + BAUD_INVALID = 0, + BAUD_110, + BAUD_300, + BAUD_600, + BAUD_1200, + BAUD_2400, + BAUD_4800, + BAUD_9600, + BAUD_19200, + BAUD_38400, + BAUD_57600, + BAUD_115200, + BAUD_230400 + }; + + enum class CharacterSize : uint8_t + { + CHAR_SIZE_INVALID = 0, + CHAR_SIZE_5, + CHAR_SIZE_6, + CHAR_SIZE_7, + CHAR_SIZE_8 + }; + + enum class Parity : uint8_t + { + PARITY_INVALID = 0, + PARITY_NONE, + PARITY_ODD, + PARITY_EVEN + }; + + enum class StopBits : uint8_t + { + STOP_BITS_INVALID = 0, + STOP_BITS_1, + STOP_BITS_2 + }; + + enum class FlowControl : uint8_t + { + FLOW_CONTROL_INVALID = 0, + FLOW_CONTROL_NONE, + FLOW_CONTROL_SOFTWARE, + FLOW_CONTROL_HARDWARE + }; + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ILibSerialPort + /// @brief Interface wrapper around LibSerial::SerialPort for testability. + /// + /// This interface abstracts the LibSerial::SerialPort class, enabling dependency injection and + /// mocking for unit testing. It provides methods to configure and interact with a serial port. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ILibSerialPort + { + public: + virtual ~ILibSerialPort() = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Opens the serial port device. + /// @param device The path to the serial port device (e.g., "/dev/ttyS0"). + /// @throws std::runtime_error if the device cannot be opened. + /// Implementation should call the underlying LibSerial method to open the port and handle + /// any exceptions that may arise during the process. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void Open(const std::string& device) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Closes the serial port device. + /// Ensures that the port is properly closed and resources are released. + /// Implementation should call the underlying LibSerial method to close the port and handle + /// any exceptions that may arise during the process. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void Close() = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Checks if the serial port is currently open. + /// @return True if the port is open, false otherwise. + /// Implementation should call the underlying LibSerial method to check the port status and + /// return the appropriate boolean value. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool IsOpen() const = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Reads data from the serial port. + /// @param data A vector to store the received bytes. + /// @param len The number of bytes to read. + /// @throws std::runtime_error if the port is not open or a read error occurs. + /// Implementation should call the underlying LibSerial method to read data. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void Read(std::vector& data, size_t len) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Writes data to the serial port. + /// @param data A vector containing the bytes to transmit. + /// @throws std::runtime_error if the port is not open or a write error occurs. + /// Implementation should call the underlying LibSerial method to write data. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void Write(const std::vector& data) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the baud rate for the serial port. + /// @param baudRate The desired baud rate (e.g., BaudRate::BAUD_9600). + /// Implementation should call the underlying LibSerial method to apply baud rate settings. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void SetBaudRate(BaudRate baudRate) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the character size for the serial port. + /// @param characterSize The desired character size (e.g., CharacterSize::CHAR_SIZE_8). + /// Implementation should call the underlying LibSerial method to apply the character size. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void SetCharacterSize(CharacterSize characterSize) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the parity mode for the serial port. + /// @param parity The desired parity mode (e.g., Parity::PARITY_NONE). + /// Implementation should call the underlying LibSerial method to apply the parity setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void SetParity(Parity parity) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the number of stop bits for the serial port. + /// @param stopBits The desired number of stop bits (e.g., StopBits::STOP_BITS_1). + /// Implementation should call the underlying LibSerial method to apply the stop bits setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void SetStopBits(StopBits stopBits) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the flow control mode for the serial port. + /// @param flowControl The desired flow control mode (e.g., FlowControl::FLOW_CONTROL_NONE). + /// Implementation should call the underlying LibSerial method to apply the flow control setting. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void SetFlowControl(FlowControl flowControl) = 0; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/serial/serialw/serial_lib_wrapper.cc b/sw/restatdesk/com/serial/serialw/serial_lib_wrapper.cc new file mode 100644 index 0000000..92376ba --- /dev/null +++ b/sw/restatdesk/com/serial/serialw/serial_lib_wrapper.cc @@ -0,0 +1,418 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_lib_wrapper.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Electux::App::Com; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Constructs a LibSerialPortWrapper object. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +LibSerialPortWrapper::LibSerialPortWrapper() : m_fd(-1) {} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Destroys the LibSerialPortWrapper object. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +LibSerialPortWrapper::~LibSerialPortWrapper() { Close(); } + +void LibSerialPortWrapper::checkOpen() const { + if (m_fd < 0) { + throw LibSerial::NotOpen("Port not open."); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Opens the serial port with the specified device. +/// @param device The name of the device to open. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::Open(const std::string &device) { + Close(); + m_device = device; + m_fd = open(device.c_str(), O_RDWR | O_NOCTTY | O_CLOEXEC); + if (m_fd < 0) { + throw std::runtime_error( + "Failed to open device: " + device + " (" + + std::string(std::strerror(errno)) + ")" + ); + } + + struct termios tty; + std::memset(&tty, 0, sizeof(tty)); + if (tcgetattr(m_fd, &tty) != 0) { + int err = errno; + close(m_fd); + m_fd = -1; + throw std::runtime_error( + "tcgetattr failed: " + std::string(std::strerror(err)) + ); + } + + // Configure as raw serial port (binary mode) + tty.c_cflag |= (CLOCAL | CREAD); + tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + tty.c_oflag &= ~OPOST; + tty.c_iflag &= + ~(IXON | IXOFF | IXANY | IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | + IGNCR | ICRNL); + + // Blocking read settings: return when at least 1 byte is available + tty.c_cc[VMIN] = 1; + tty.c_cc[VTIME] = 0; + + if (tcsetattr(m_fd, TCSANOW, &tty) != 0) { + int err = errno; + close(m_fd); + m_fd = -1; + throw std::runtime_error( + "tcsetattr failed: " + std::string(std::strerror(err)) + ); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Closes the serial port. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::Close() { + if (m_fd >= 0) { + close(m_fd); + m_fd = -1; + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Checks if the serial port is open. +/// @return True if the serial port is open, false otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool LibSerialPortWrapper::IsOpen() const { + if (m_fd < 0) { + return false; + } + + if (!m_device.empty() && !std::filesystem::exists(m_device)) { + return false; + } + + struct pollfd pfd; + pfd.fd = m_fd; + pfd.events = POLLIN | POLLERR | POLLHUP; + pfd.revents = 0; + int ret = poll(&pfd, 1, 0); + + if (ret > 0 && (pfd.revents & (POLLERR | POLLHUP | POLLNVAL))) { + return false; + } + + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Reads data from the serial port. +/// @param data A vector to store the read data. +/// @param len The number of bytes to read. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::Read(std::vector &data, size_t len) { + checkOpen(); + data.clear(); + data.resize(len); + size_t total_read = 0; + + while (total_read < len) { + if (!m_device.empty() && !std::filesystem::exists(m_device)) { + throw std::runtime_error("Device disconnected (file deleted)."); + } + + struct pollfd pfd; + pfd.fd = m_fd; + pfd.events = POLLIN | POLLERR | POLLHUP; + pfd.revents = 0; + + int ret = poll(&pfd, 1, 500); // 500ms timeout + if (ret == 0) { + throw LibSerial::ReadTimeout("Timeout waiting for data."); + } else if (ret < 0) { + if (errno == EINTR) + continue; + throw std::runtime_error( + "Read error (poll failed): " + std::string(std::strerror(errno)) + ); + } + + if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) { + throw std::runtime_error("Connection lost (device disconnected)."); + } + + ssize_t n = read(m_fd, data.data() + total_read, len - total_read); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + continue; + throw std::runtime_error( + "Read error: " + std::string(std::strerror(errno)) + ); + } else if (n == 0) { + throw std::runtime_error("Connection lost (EOF)."); + } + total_read += static_cast(n); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Writes data to the serial port. +/// @param data The data to write. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::Write(const std::vector &data) { + checkOpen(); + size_t total_written = 0; + + while (total_written < data.size()) { + ssize_t n = write( + m_fd, data.data() + total_written, data.size() - total_written + ); + + if (n < 0) { + if (errno == EINTR) + continue; + + throw std::runtime_error( + "Write error: " + std::string(std::strerror(errno)) + ); + } + + total_written += static_cast(n); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the baud rate of the serial port. +/// @param baudRate The baud rate to set. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::SetBaudRate(BaudRate baudRate) { + checkOpen(); + speed_t speed = B9600; + switch (baudRate) { + case BaudRate::BAUD_110: + speed = B110; + break; + case BaudRate::BAUD_300: + speed = B300; + break; + case BaudRate::BAUD_600: + speed = B600; + break; + case BaudRate::BAUD_1200: + speed = B1200; + break; + case BaudRate::BAUD_2400: + speed = B2400; + break; + case BaudRate::BAUD_4800: + speed = B4800; + break; + case BaudRate::BAUD_9600: + speed = B9600; + break; + case BaudRate::BAUD_19200: + speed = B19200; + break; + case BaudRate::BAUD_38400: + speed = B38400; + break; + case BaudRate::BAUD_57600: + speed = B57600; + break; + case BaudRate::BAUD_115200: + speed = B115200; + break; + case BaudRate::BAUD_230400: + speed = B230400; + break; + default: + throw std::invalid_argument("Invalid baud rate."); + } + + struct termios tty; + if (tcgetattr(m_fd, &tty) != 0) { + throw std::runtime_error( + "tcgetattr failed: " + std::string(std::strerror(errno)) + ); + } + cfsetospeed(&tty, speed); + cfsetispeed(&tty, speed); + if (tcsetattr(m_fd, TCSANOW, &tty) != 0) { + throw std::runtime_error( + "tcsetattr failed: " + std::string(std::strerror(errno)) + ); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the character size of the serial port. +/// @param characterSize The character size to set. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::SetCharacterSize(CharacterSize characterSize) { + checkOpen(); + tcflag_t size = CS8; + + switch (characterSize) { + case CharacterSize::CHAR_SIZE_5: + size = CS5; + break; + case CharacterSize::CHAR_SIZE_6: + size = CS6; + break; + case CharacterSize::CHAR_SIZE_7: + size = CS7; + break; + case CharacterSize::CHAR_SIZE_8: + size = CS8; + break; + default: + throw std::invalid_argument("Invalid character size."); + } + + struct termios tty; + if (tcgetattr(m_fd, &tty) != 0) { + throw std::runtime_error( + "tcgetattr failed: " + std::string(std::strerror(errno)) + ); + } + tty.c_cflag &= ~CSIZE; + tty.c_cflag |= size; + if (tcsetattr(m_fd, TCSANOW, &tty) != 0) { + throw std::runtime_error( + "tcsetattr failed: " + std::string(std::strerror(errno)) + ); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the parity of the serial port. +/// @param parity The parity to set. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::SetParity(Parity parity) { + checkOpen(); + struct termios tty; + if (tcgetattr(m_fd, &tty) != 0) { + throw std::runtime_error( + "tcgetattr failed: " + std::string(std::strerror(errno)) + ); + } + + switch (parity) { + case Parity::PARITY_NONE: + tty.c_cflag &= ~PARENB; + break; + case Parity::PARITY_ODD: + tty.c_cflag |= PARENB; + tty.c_cflag |= PARODD; + break; + case Parity::PARITY_EVEN: + tty.c_cflag |= PARENB; + tty.c_cflag &= ~PARODD; + break; + default: + throw std::invalid_argument("Invalid parity."); + } + + if (tcsetattr(m_fd, TCSANOW, &tty) != 0) { + throw std::runtime_error( + "tcsetattr failed: " + std::string(std::strerror(errno)) + ); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the stop bits of the serial port. +/// @param stopBits The stop bits to set. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::SetStopBits(StopBits stopBits) { + checkOpen(); + struct termios tty; + + if (tcgetattr(m_fd, &tty) != 0) { + throw std::runtime_error( + "tcgetattr failed: " + std::string(std::strerror(errno)) + ); + } + + switch (stopBits) { + case StopBits::STOP_BITS_1: + tty.c_cflag &= ~CSTOPB; + break; + case StopBits::STOP_BITS_2: + tty.c_cflag |= CSTOPB; + break; + default: + throw std::invalid_argument("Invalid stop bits."); + } + + if (tcsetattr(m_fd, TCSANOW, &tty) != 0) { + throw std::runtime_error( + "tcsetattr failed: " + std::string(std::strerror(errno)) + ); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the flow control of the serial port. +/// @param flowControl The flow control to set. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void LibSerialPortWrapper::SetFlowControl(FlowControl flowControl) { + checkOpen(); + struct termios tty; + + if (tcgetattr(m_fd, &tty) != 0) { + throw std::runtime_error( + "tcgetattr failed: " + std::string(std::strerror(errno)) + ); + } + + switch (flowControl) { + case FlowControl::FLOW_CONTROL_NONE: + tty.c_cflag &= ~CRTSCTS; + tty.c_iflag &= ~(IXON | IXOFF | IXANY); + break; + case FlowControl::FLOW_CONTROL_SOFTWARE: + tty.c_cflag &= ~CRTSCTS; + tty.c_iflag |= (IXON | IXOFF | IXANY); + break; + case FlowControl::FLOW_CONTROL_HARDWARE: + tty.c_cflag |= CRTSCTS; + tty.c_iflag &= ~(IXON | IXOFF | IXANY); + break; + default: + throw std::invalid_argument("Invalid flow control."); + } + + if (tcsetattr(m_fd, TCSANOW, &tty) != 0) { + throw std::runtime_error( + "tcsetattr failed: " + std::string(std::strerror(errno)) + ); + } +} diff --git a/sw/restatdesk/com/serial/serialw/serial_lib_wrapper.h b/sw/restatdesk/com/serial/serialw/serial_lib_wrapper.h new file mode 100644 index 0000000..0e156a9 --- /dev/null +++ b/sw/restatdesk/com/serial/serialw/serial_lib_wrapper.h @@ -0,0 +1,121 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_lib_wrapper.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Com +/// @brief Namespace for application communication components +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class LibSerialPortWrapper + /// @brief Wrapper class for LibSerial::SerialPort implementing + /// ILibSerialPort. + /// + /// This class provides an abstraction layer over the LibSerial::SerialPort + /// library, enabling easier integration and testing. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class LibSerialPortWrapper : public ILibSerialPort { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Constructs a new LibSerialPortWrapper object. + //////////////////////////////////////////////////////////////////////////////////////////////// + LibSerialPortWrapper(); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Destroys the LibSerialPortWrapper object. + //////////////////////////////////////////////////////////////////////////////////////////////// + ~LibSerialPortWrapper() override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Opens the serial port with the specified device. + /// @param device The name of the device to open. + //////////////////////////////////////////////////////////////////////////////////////////////// + void Open(const std::string &device) override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Closes the serial port. + //////////////////////////////////////////////////////////////////////////////////////////////// + void Close() override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Checks if the serial port is open. + /// @return True if the serial port is open, false otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool IsOpen() const override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Reads data from the serial port. + /// @param data A vector to store the read data. + /// @param len The number of bytes to read. + //////////////////////////////////////////////////////////////////////////////////////////////// + void Read(std::vector &data, size_t len) override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Writes data to the serial port. + /// @param data The data to write. + //////////////////////////////////////////////////////////////////////////////////////////////// + void Write(const std::vector &data) override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the baud rate of the serial port. + /// @param baudRate The baud rate to set. + //////////////////////////////////////////////////////////////////////////////////////////////// + void SetBaudRate(BaudRate baudRate) override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the character size of the serial port. + /// @param characterSize The character size to set. + //////////////////////////////////////////////////////////////////////////////////////////////// + void SetCharacterSize(CharacterSize characterSize) override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the parity of the serial port. + /// @param parity The parity to set. + //////////////////////////////////////////////////////////////////////////////////////////////// + void SetParity(Parity parity) override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the stop bits of the serial port. + /// @param stopBits The stop bits to set. + //////////////////////////////////////////////////////////////////////////////////////////////// + void SetStopBits(StopBits stopBits) override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the flow control of the serial port. + /// @param flowControl The flow control to set. + //////////////////////////////////////////////////////////////////////////////////////////////// + void SetFlowControl(FlowControl flowControl) override; + + private: + void checkOpen() const; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief POSIX file descriptor for the serial port. + //////////////////////////////////////////////////////////////////////////////////////////////// + int m_fd{-1}; + std::string m_device{}; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/switchable_com.cc b/sw/restatdesk/com/switchable_com.cc new file mode 100644 index 0000000..67c8df3 --- /dev/null +++ b/sw/restatdesk/com/switchable_com.cc @@ -0,0 +1,111 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// switchable_com.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Com { + namespace { + constexpr std::string_view cTcpSwitchMsg{"Switched communication channel to TCP/IP."}; + constexpr std::string_view cBleSwitchMsg{"Switched communication channel to BLE."}; + constexpr std::string_view cSerialSwitchMsg{"Switched communication channel to Serial Port."}; + } // namespace + SwitchableCom::SwitchableCom( + bool verbose, + std::unique_ptr serialCom, + std::unique_ptr tcpCom, + std::unique_ptr bleCom + ) + : m_verbose(verbose), + m_serialCom(std::move(serialCom)), + m_tcpCom(std::move(tcpCom)), + m_bleCom(std::move(bleCom)), + m_activeCom(m_serialCom.get()) {} + + bool SwitchableCom::open() { + if (m_activeCom) { + return m_activeCom->open(); + } + return false; + } + + bool SwitchableCom::close() { + if (m_activeCom) { + return m_activeCom->close(); + } + return false; + } + + bool SwitchableCom::isOpen() const { + if (m_activeCom) { + return m_activeCom->isOpen(); + } + return false; + } + + void SwitchableCom::read(std::vector &data, size_t len) { + if (m_activeCom) { + m_activeCom->read(data, len); + } + } + + void SwitchableCom::write(const std::vector &data) { + if (m_activeCom) { + m_activeCom->write(data); + } + } + + void SwitchableCom::setComType(const std::string &type) { + if (type == toConfigString(ComType::Tcp)) { + if (m_activeCom != m_tcpCom.get()) { + close(); + m_activeCom = m_tcpCom.get(); + if (m_verbose) { + std::cout << cTcpSwitchMsg << std::endl; + } + } + } else if (type == toConfigString(ComType::Ble)) { + if (m_activeCom != m_bleCom.get()) { + close(); + m_activeCom = m_bleCom.get(); + if (m_verbose) { + std::cout << cBleSwitchMsg << std::endl; + } + } + } else { + if (m_activeCom != m_serialCom.get()) { + close(); + m_activeCom = m_serialCom.get(); + if (m_verbose) { + std::cout << cSerialSwitchMsg << std::endl; + } + } + } + } + + ICom *SwitchableCom::getActiveCom() const { return m_activeCom; } + + ICom *SwitchableCom::getSerialCom() const { return m_serialCom.get(); } + + ICom *SwitchableCom::getTcpCom() const { return m_tcpCom.get(); } + + ICom *SwitchableCom::getBleCom() const { return m_bleCom.get(); } +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/switchable_com.h b/sw/restatdesk/com/switchable_com.h new file mode 100644 index 0000000..1482cc6 --- /dev/null +++ b/sw/restatdesk/com/switchable_com.h @@ -0,0 +1,70 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// switchable_com.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Com { + class SerialCom; + class TcpCom; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SwitchableCom + /// @brief Proxy/Decorator implementing ICom that switches between Serial + /// and TCP at runtime. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SwitchableCom : public ICom { + public: + SwitchableCom( + bool verbose, + std::unique_ptr serialCom, + std::unique_ptr tcpCom, + std::unique_ptr bleCom + ); + ~SwitchableCom() override = default; + + SwitchableCom(const SwitchableCom &) = delete; + SwitchableCom &operator=(const SwitchableCom &) = delete; + + // ICom overrides + bool open() override; + bool close() override; + bool isOpen() const override; + void read(std::vector &data, size_t len) override; + void write(const std::vector &data) override; + + // Active channel control + void setComType(const std::string &type); + ICom *getActiveCom() const; + + ICom *getSerialCom() const; + ICom *getTcpCom() const; + ICom *getBleCom() const; + + private: + bool m_verbose; + std::unique_ptr m_serialCom; + std::unique_ptr m_tcpCom; + std::unique_ptr m_bleCom; + ICom *m_activeCom; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/switchable_com_configurator.cc b/sw/restatdesk/com/switchable_com_configurator.cc new file mode 100644 index 0000000..a535df9 --- /dev/null +++ b/sw/restatdesk/com/switchable_com_configurator.cc @@ -0,0 +1,63 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// switchable_com_configurator.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + SwitchableComConfigurator::SwitchableComConfigurator( + SwitchableCom *switchableCom, + std::unique_ptr serialConfigurator, + std::unique_ptr tcpConfigurator, + std::unique_ptr bleConfigurator + ) + : m_switchableCom(switchableCom), + m_serialConfigurator(std::move(serialConfigurator)), + m_tcpConfigurator(std::move(tcpConfigurator)), + m_bleConfigurator(std::move(bleConfigurator)) {} + + bool SwitchableComConfigurator::configure( + const Model::IModel &model, ICom *comChannel + ) { + (void)comChannel; // Suppress unused parameter warning + + auto comTypeKey = model.toString(Model::ModelGeneralKey::ComType); + std::string comType = model.getEntity(comTypeKey); + + m_switchableCom->setComType(comType); + + if (comType == toConfigString(ComType::Tcp)) { + return m_tcpConfigurator->configure( + model, m_switchableCom->getTcpCom() + ); + } else if (comType == toConfigString(ComType::Ble)) { + return m_bleConfigurator->configure( + model, m_switchableCom->getBleCom() + ); + } else { + return m_serialConfigurator->configure( + model, m_switchableCom->getSerialCom() + ); + } + } +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/switchable_com_configurator.h b/sw/restatdesk/com/switchable_com_configurator.h new file mode 100644 index 0000000..c7741c6 --- /dev/null +++ b/sw/restatdesk/com/switchable_com_configurator.h @@ -0,0 +1,52 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// switchable_com_configurator.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Com { + class SwitchableCom; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SwitchableComConfigurator + /// @brief Proxy implementing IComConfigurator that delegates configuration + /// to active channel configurator. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SwitchableComConfigurator : public IComConfigurator { + public: + SwitchableComConfigurator( + SwitchableCom *switchableCom, + std::unique_ptr serialConfigurator, + std::unique_ptr tcpConfigurator, + std::unique_ptr bleConfigurator + ); + + ~SwitchableComConfigurator() override = default; + + bool configure(const Model::IModel &model, ICom *comChannel) override; + + private: + SwitchableCom *m_switchableCom; + std::unique_ptr m_serialConfigurator; + std::unique_ptr m_tcpConfigurator; + std::unique_ptr m_bleConfigurator; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/tcp/.editorconfig b/sw/restatdesk/com/tcp/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/tcp/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/tcp/configurator/.editorconfig b/sw/restatdesk/com/tcp/configurator/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/com/tcp/configurator/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/com/tcp/configurator/tcp_com_configurator.cc b/sw/restatdesk/com/tcp/configurator/tcp_com_configurator.cc new file mode 100644 index 0000000..ea14a41 --- /dev/null +++ b/sw/restatdesk/com/tcp/configurator/tcp_com_configurator.cc @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// tcp_com_configurator.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +namespace Electux::App::Com { + TcpComConfigurator::TcpComConfigurator(ITcp *tcp) : m_tcp(tcp) {} + + bool TcpComConfigurator::configure( + const Model::IModel &model, ICom *comChannel + ) { + if (m_tcp == nullptr || comChannel == nullptr) { + return false; + } + + auto ipKey = model.toString(Model::ModelGeneralKey::TcpIp); + auto portKey = model.toString(Model::ModelGeneralKey::TcpPort); + + std::string ip = model.getEntity(ipKey); + uint16_t port = + static_cast(std::stoul(model.getEntity(portKey))); + + m_tcp->setIpAddress(ip); + m_tcp->setPort(port); + + return comChannel->open(); + } +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/tcp/configurator/tcp_com_configurator.h b/sw/restatdesk/com/tcp/configurator/tcp_com_configurator.h new file mode 100644 index 0000000..d9ba9c0 --- /dev/null +++ b/sw/restatdesk/com/tcp/configurator/tcp_com_configurator.h @@ -0,0 +1,54 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// tcp_com_configurator.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace Electux::App::Com { + class ITcp; + class ICom; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class TcpComConfigurator + /// @brief Configures TCP/IP communication parameters using the model. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class TcpComConfigurator : public IComConfigurator { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Constructs a new TcpComConfigurator object. + /// @param tcp Pointer to the ITcp interface representing the TCP + /// channel. + //////////////////////////////////////////////////////////////////////////////////////////////// + explicit TcpComConfigurator(ITcp *tcp); + + ~TcpComConfigurator() override = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Configures the TCP/IP connection. + /// @param model Reference to the configuration model. + /// @param comChannel Pointer to the communication channel interface. + /// @return true if configuration was successful, else false. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool configure(const Model::IModel &model, ICom *comChannel) override; + + private: + ITcp *m_tcp; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/tcp/itcp.h b/sw/restatdesk/com/tcp/itcp.h new file mode 100644 index 0000000..b5bc050 --- /dev/null +++ b/sw/restatdesk/com/tcp/itcp.h @@ -0,0 +1,46 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// itcp.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ITcp + /// @brief Interface for TCP communication configuration parameters. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ITcp { + public: + virtual ~ITcp() = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the target IP Address for the TCP connection. + /// @param ip The IP address. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setIpAddress(const std::string &ip) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the target port number for the TCP connection. + /// @param port The port number. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setPort(uint16_t port) = 0; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/com/tcp/tcp_com.cc b/sw/restatdesk/com/tcp/tcp_com.cc new file mode 100644 index 0000000..54c7851 --- /dev/null +++ b/sw/restatdesk/com/tcp/tcp_com.cc @@ -0,0 +1,152 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// tcp_com.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include + +using namespace Electux::App::Com; + +namespace { + constexpr std::string_view cDefaultIp{"127.0.0.1"}; + constexpr std::string_view cTcpComConstructorMsg{"TcpCom constructor called."}; + constexpr std::string_view cTcpComDestructorMsg{"TcpCom destructor called."}; + constexpr std::string_view cTcpOpenSocketError{"TcpCom open error: Failed to create socket."}; + constexpr std::string_view cTcpOpenAddrError{"TcpCom open error: Invalid address or Address not supported."}; + constexpr std::string_view cTcpOpenConnError{"TcpCom open error: Connection Failed."}; + constexpr std::string_view cTcpCloseMsg{"TcpCom connection closed."}; + constexpr std::string_view cTcpReadError{"TcpCom read: Connection lost or read error."}; + constexpr std::string_view cTcpWriteError{"TcpCom write: Connection lost or write error."}; + constexpr std::string_view cTcpWriteNotOpenError{"TcpCom write error: Connection is not open."}; + constexpr uint16_t cDefaultPort{5000}; +} // namespace + +TcpCom::TcpCom(bool verbose) : m_ip(cDefaultIp), m_port(cDefaultPort), m_socketFd(-1), m_verbose(verbose) { + if (m_verbose) { + std::cout << cTcpComConstructorMsg << std::endl; + } +} + +TcpCom::~TcpCom() noexcept { + close(); + if (m_verbose) { + std::cout << cTcpComDestructorMsg << std::endl; + } +} + +bool TcpCom::open() { + if (isOpen()) { + return true; + } + + m_socketFd = ::socket(AF_INET, SOCK_STREAM, 0); + if (m_socketFd < 0) { + std::cerr << cTcpOpenSocketError << std::endl; + return false; + } + + struct sockaddr_in serv_addr{}; + std::memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_port = htons(m_port); + + if (::inet_pton(AF_INET, m_ip.c_str(), &serv_addr.sin_addr) <= 0) { + std::cerr << cTcpOpenAddrError << std::endl; + ::close(m_socketFd); + m_socketFd = -1; + return false; + } + + if (::connect( + m_socketFd, reinterpret_cast(&serv_addr), sizeof(serv_addr) + ) < 0) { + std::cerr << cTcpOpenConnError << std::endl; + ::close(m_socketFd); + m_socketFd = -1; + return false; + } + + if (m_verbose) { + std::cout << "TcpCom connected successfully to " << m_ip << ":" << m_port + << std::endl; + } + return true; +} + +bool TcpCom::close() { + if (isOpen()) { + ::close(m_socketFd); + m_socketFd = -1; + if (m_verbose) { + std::cout << cTcpCloseMsg << std::endl; + } + return true; + } + return false; +} + +bool TcpCom::isOpen() const { return m_socketFd != -1; } + +void TcpCom::read(std::vector &data, size_t len) { + if (!isOpen()) { + return; + } + + data.resize(len); + size_t totalRead = 0; + while (totalRead < len) { + ssize_t bytesRead = + ::recv(m_socketFd, &data.at(totalRead), len - totalRead, 0); + if (bytesRead <= 0) { + std::cerr << cTcpReadError << std::endl; + close(); + break; + } + totalRead += static_cast(bytesRead); + } +} + +void TcpCom::write(const std::vector &data) { + if (!isOpen()) { + std::cerr << cTcpWriteNotOpenError << std::endl; + return; + } + + size_t totalSent = 0; + while (totalSent < data.size()) { + ssize_t bytesSent = ::send( + m_socketFd, &data.at(totalSent), data.size() - totalSent, 0 + ); + if (bytesSent <= 0) { + std::cerr << cTcpWriteError << std::endl; + close(); + break; + } + totalSent += static_cast(bytesSent); + } +} + +void TcpCom::setIpAddress(const std::string &ip) { m_ip = ip; } + +void TcpCom::setPort(uint16_t port) { m_port = port; } diff --git a/sw/restatdesk/com/tcp/tcp_com.h b/sw/restatdesk/com/tcp/tcp_com.h new file mode 100644 index 0000000..c24c178 --- /dev/null +++ b/sw/restatdesk/com/tcp/tcp_com.h @@ -0,0 +1,57 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// tcp_com.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::Com { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class TcpCom + /// @brief Implementation of TCP/IP communication using raw BSD sockets. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class TcpCom : public ICom, public ITcp { + public: + explicit TcpCom(bool verbose = false); + ~TcpCom() noexcept override; + + TcpCom(const TcpCom &) = delete; + TcpCom &operator=(const TcpCom &) = delete; + + // ICom overrides + bool open() override; + bool close() override; + bool isOpen() const override; + void read(std::vector &data, size_t len) override; + void write(const std::vector &data) override; + + // ITcp overrides + void setIpAddress(const std::string &ip) override; + void setPort(uint16_t port) override; + + private: + std::string m_ip; + uint16_t m_port; + int m_socketFd; + bool m_verbose; + }; +} // namespace Electux::App::Com diff --git a/sw/restatdesk/command/.editorconfig b/sw/restatdesk/command/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/command/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/command/command_factory.cc b/sw/restatdesk/command/command_factory.cc new file mode 100644 index 0000000..1fc20f6 --- /dev/null +++ b/sw/restatdesk/command/command_factory.cc @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// command_factory.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Command { + std::unique_ptr createCommandFormatter() { + return std::make_unique(); + } + + std::unique_ptr createResponseProcessor() { + return std::make_unique(); + } +} // namespace Electux::App::Command diff --git a/sw/restatdesk/command/command_factory.h b/sw/restatdesk/command/command_factory.h new file mode 100644 index 0000000..821f0cf --- /dev/null +++ b/sw/restatdesk/command/command_factory.h @@ -0,0 +1,29 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// command_factory.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Command { + std::unique_ptr createCommandFormatter(); + std::unique_ptr createResponseProcessor(); +} // namespace Electux::App::Command diff --git a/sw/restatdesk/command/formatter/.editorconfig b/sw/restatdesk/command/formatter/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/command/formatter/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/command/formatter/command_formatter.cc b/sw/restatdesk/command/formatter/command_formatter.cc new file mode 100644 index 0000000..539a26e --- /dev/null +++ b/sw/restatdesk/command/formatter/command_formatter.cc @@ -0,0 +1,136 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// command_formatter.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +using namespace Electux::App::Command; + +namespace { + constexpr std::string_view cCmdChOff{""}; + constexpr std::string_view cCmdChToggle{""}; + constexpr std::string_view cCmdChTmr{""}; + constexpr std::string_view cCmdAllOff{""}; + constexpr std::string_view cCmdAllOn{""}; + constexpr std::string_view cCmdAllMaskPrefix{""}; + constexpr std::string_view cCmdChStat{""}; + constexpr std::string_view cCmdAllStat{""}; + constexpr std::string_view cCmdSysReset{""}; + constexpr std::string_view cCmdSysId{""}; + constexpr std::string_view cCmdSysVersion{""}; + constexpr std::string_view cOnVal{"on"}; + constexpr std::string_view cOffVal{"off"}; + constexpr std::string_view cBitOne{"1"}; + constexpr std::string_view cBitZero{"0"}; +} // namespace + +std::string CommandFormatter::getCommandState( + size_t channelIdx, const Model::Channel::ChannelState &state +) const { + if (!state.enabled) { + return std::format(cCmdChOff.data(), channelIdx + 1); + } + + if (state.mode == Model::Channel::ChannelMode::Toggle) { + return std::format( + cCmdChToggle.data(), channelIdx + 1, state.toggle ? cOnVal : cOffVal + ); + } + + if (state.mode == Model::Channel::ChannelMode::Timer) { + if (state.timerEnabled) { + return std::format(cCmdChTmr.data(), channelIdx + 1, state.timer); + } else { + return std::format(cCmdChOff.data(), channelIdx + 1); + } + } + + return ""; +} + +std::string CommandFormatter::getCommandPlan( + const std::vector &states +) const { + std::string cmd = "rs#all#plan"; + bool empty = true; + for (size_t i = 0; i < states.size(); ++i) { + const auto &state = states[i]; + if (state.enabled) { + empty = false; + cmd += std::format("#ch#{}", i + 1); + if (state.mode == Model::Channel::ChannelMode::Toggle) { + cmd += state.toggle ? "#on" : "#off"; + } else if (state.mode == Model::Channel::ChannelMode::Timer) { + cmd += std::format( + "#{}#{}", + state.timerEnabled ? "tmron" : "tmroff", + state.timer + ); + } else { + cmd += "#off"; + } + } + } + if (empty) { + return ""; + } + cmd += "#end"; + return std::format("<{}>", cmd); +} + +std::string CommandFormatter::getCommandOffAllChannels() const { + return std::string(cCmdAllOff); +} + +std::string CommandFormatter::getCommandOnAllChannels() const { + return std::string(cCmdAllOn); +} + +std::string CommandFormatter::getCommandMaskChannels( + const std::vector &states +) const { + std::string command = std::string(cCmdAllMaskPrefix); + for (const auto &state : states) { + command += (state.enabled and state.toggle ? cBitOne : cBitZero); + } + command += cCmdAllMaskSuffix; + return command; +} + +std::string CommandFormatter::getCommandStatus(size_t channelIdx) const { + return std::format(cCmdChStat.data(), channelIdx + 1); +} + +std::string CommandFormatter::getCommandStatusAllChannels() const { + return std::string(cCmdAllStat); +} + +std::string CommandFormatter::getCommandReset() const { + return std::string(cCmdSysReset); +} + +std::string CommandFormatter::getCommandBoardId() const { + return std::string(cCmdSysId); +} + +std::string CommandFormatter::getCommandVersion() const { + return std::string(cCmdSysVersion); +} diff --git a/sw/restatdesk/command/formatter/command_formatter.h b/sw/restatdesk/command/formatter/command_formatter.h new file mode 100644 index 0000000..b9808b0 --- /dev/null +++ b/sw/restatdesk/command/formatter/command_formatter.h @@ -0,0 +1,55 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// command_formatter.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace Electux::App::Command { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class CommandFormatter + /// @brief Implements ICommandFormatter to serialize relay channel state + /// into command strings. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class CommandFormatter : public ICommandFormatter { + public: + CommandFormatter() = default; + virtual ~CommandFormatter() override = default; + + CommandFormatter(const CommandFormatter &) = delete; + CommandFormatter &operator=(const CommandFormatter &) = delete; + + virtual std::string getCommandState( + size_t channelIdx, const Model::Channel::ChannelState &state + ) const override; + virtual std::string getCommandPlan( + const std::vector &states + ) const override; + virtual std::string getCommandOffAllChannels() const override; + virtual std::string getCommandOnAllChannels() const override; + virtual std::string getCommandMaskChannels( + const std::vector &states + ) const override; + virtual std::string getCommandStatusAllChannels() const override; + virtual std::string getCommandStatus(size_t channelIdx) const override; + virtual std::string getCommandReset() const override; + virtual std::string getCommandBoardId() const override; + virtual std::string getCommandVersion() const override; + }; +} // namespace Electux::App::Command diff --git a/sw/restatdesk/command/formatter/icommand_formatter.h b/sw/restatdesk/command/formatter/icommand_formatter.h new file mode 100644 index 0000000..d7b7747 --- /dev/null +++ b/sw/restatdesk/command/formatter/icommand_formatter.h @@ -0,0 +1,53 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// icommand_formatter.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Command { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ICommandFormatter + /// @brief Interface defining the contract for parsing relay channel state + /// into protocol strings. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ICommandFormatter { + public: + virtual ~ICommandFormatter() = default; + + virtual std::string getCommandState( + size_t channelIdx, const Model::Channel::ChannelState &state + ) const = 0; + virtual std::string getCommandPlan( + const std::vector &states + ) const = 0; + virtual std::string getCommandOffAllChannels() const = 0; + virtual std::string getCommandOnAllChannels() const = 0; + virtual std::string getCommandMaskChannels( + const std::vector &states + ) const = 0; + virtual std::string getCommandStatus(size_t channelIdx) const = 0; + virtual std::string getCommandStatusAllChannels() const = 0; + virtual std::string getCommandReset() const = 0; + virtual std::string getCommandBoardId() const = 0; + virtual std::string getCommandVersion() const = 0; + }; +} // namespace Electux::App::Command diff --git a/sw/restatdesk/command/processor/.editorconfig b/sw/restatdesk/command/processor/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/command/processor/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/command/processor/iresponse_processor.h b/sw/restatdesk/command/processor/iresponse_processor.h new file mode 100644 index 0000000..84b6fee --- /dev/null +++ b/sw/restatdesk/command/processor/iresponse_processor.h @@ -0,0 +1,39 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// iresponse_processor.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Command { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IResponseProcessor + /// @brief Interface defining the contract for parsing raw incoming data streams into response payloads. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IResponseProcessor { + public: + virtual ~IResponseProcessor() = default; + + /// @brief Processes incoming raw data, buffering as needed, and extracts complete response payloads. + /// @param data String containing a chunk of raw incoming data. + /// @return Vector of extracted payload strings. + virtual std::vector process(const std::string &data) = 0; + }; +} // namespace Electux::App::Command diff --git a/sw/restatdesk/command/processor/response_processor.cc b/sw/restatdesk/command/processor/response_processor.cc new file mode 100644 index 0000000..5ef7ead --- /dev/null +++ b/sw/restatdesk/command/processor/response_processor.cc @@ -0,0 +1,69 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// response_processor.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include + +using namespace Electux::App::Command; + +namespace { + constexpr std::string_view cStartMarker{""}; +} // namespace + +std::vector ResponseProcessor::process(const std::string &data) { + m_buffer += data; + std::vector payloads; + + while (true) { + size_t startPos = m_buffer.find(cStartMarker); + + if (startPos == std::string::npos) { + size_t lastLessThan = m_buffer.rfind('<'); + + if (lastLessThan != std::string::npos) { + m_buffer = m_buffer.substr(lastLessThan); + } else { + m_buffer.clear(); + } + + break; + } + + size_t endPos = m_buffer.find(cEndMarker, startPos); + + if (endPos == std::string::npos) { + if (startPos > 0) { + m_buffer = m_buffer.substr(startPos); + } + + break; + } + + size_t payloadStart = startPos + cStartMarker.length(); + size_t payloadLen = endPos - payloadStart; + + std::string payload = m_buffer.substr(payloadStart, payloadLen); + payloads.push_back(payload); + + m_buffer = m_buffer.substr(endPos + cEndMarker.length()); + } + + return payloads; +} diff --git a/sw/restatdesk/command/processor/response_processor.h b/sw/restatdesk/command/processor/response_processor.h new file mode 100644 index 0000000..b26df6c --- /dev/null +++ b/sw/restatdesk/command/processor/response_processor.h @@ -0,0 +1,44 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// response_processor.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Command { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ResponseProcessor + /// @brief Implementation of IResponseProcessor that parses serial response messages. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ResponseProcessor : public IResponseProcessor { + public: + ResponseProcessor() = default; + virtual ~ResponseProcessor() override = default; + + ResponseProcessor(const ResponseProcessor &) = delete; + ResponseProcessor &operator=(const ResponseProcessor &) = delete; + + std::vector process(const std::string &data) override; + + private: + std::string m_buffer; + }; +} // namespace Electux::App::Command diff --git a/sw/restatdesk/config/.editorconfig b/sw/restatdesk/config/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/config/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/config/config_factory.cc b/sw/restatdesk/config/config_factory.cc new file mode 100644 index 0000000..4611f12 --- /dev/null +++ b/sw/restatdesk/config/config_factory.cc @@ -0,0 +1,32 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// config_factory.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Config { + std::unique_ptr createConfigManager( + std::unique_ptr config, + bool verbose + ) { + return std::make_unique(std::move(config), "", verbose); + } +} // namespace Electux::App::Config diff --git a/sw/restatdesk/config/config_factory.h b/sw/restatdesk/config/config_factory.h new file mode 100644 index 0000000..f49e595 --- /dev/null +++ b/sw/restatdesk/config/config_factory.h @@ -0,0 +1,34 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// config_factory.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Model { + class IModel; +} + +namespace Electux::App::Config { + std::unique_ptr createConfigManager( + std::unique_ptr config, + bool verbose = false + ); +} // namespace Electux::App::Config diff --git a/sw/restatdesk/config/config_manager.cc b/sw/restatdesk/config/config_manager.cc new file mode 100644 index 0000000..d88d290 --- /dev/null +++ b/sw/restatdesk/config/config_manager.cc @@ -0,0 +1,217 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// config_manager.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Internal Configuration Constants + /// @{ + // Default values for Control Model + constexpr std::string_view cConfigFile{".restat/config"}; + // Delimiter for key-value pairs in the config file + constexpr char cConfigAssignDelimiter{'='}; + // Character indicating a comment line in the config file + constexpr char cConfigCommentChar{'#'}; + // Console messages + constexpr std::string_view cUnableToCreateFileMsg{"Unable to create file: "}; + constexpr std::string_view cInitConfigPathMsg{"Initialized configuration file path: "}; + constexpr std::string_view cInitErrorMsg{"Error during ConfigManager initialization: "}; + constexpr std::string_view cLoadingConfigMsg{"Loading configuration..."}; + constexpr std::string_view cUnableToOpenFileMsg{"Unable to open file: "}; + constexpr std::string_view cUnknownKeyWarningMsg{"Warning: Unknown configuration key: "}; + constexpr std::string_view cLoadConfigDoneMsg{"Load configuration done."}; + constexpr std::string_view cStoringConfigMsg{"Storing configuration..."}; + constexpr std::string_view cStoreConfigDoneMsg{"Store configuration done."}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace + +using namespace Electux::App::Config; +using namespace Electux::App::Model; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Constructor that initializes the config path. +/// @param configFileName The path/name of the configuration file. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +ConfigManager::ConfigManager( + std::unique_ptr config, + const std::string &configFileName, + bool verbose +) : m_verbose(verbose), m_config(std::move(config)) { + m_fileName = + configFileName.empty() + ? Glib::build_filename(Glib::get_home_dir(), cConfigFile.data()) + : configFileName; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief ConfigManager destructor. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +ConfigManager::~ConfigManager() = default; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Initializes the configuration manager. +/// Performs file system checks, directory creation, and initial load. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void ConfigManager::init() { + populateDefaults(); + + auto dirPath = Glib::path_get_dirname(m_fileName); + + try { + if (!std::filesystem::exists(dirPath)) { + std::filesystem::create_directories(dirPath); + } + + if (!std::filesystem::exists(m_fileName)) { + { + std::ofstream file(m_fileName); + if (!file) { + throw std::ios_base::failure( + std::string(cUnableToCreateFileMsg) + m_fileName + ); + } + + // File closes here when going out of scope, releasing the + // handle before store() + } + defaultConfigStore(); + } + + if (m_verbose) { + std::cout << cInitConfigPathMsg << m_fileName + << std::endl; + } + load(); + } catch (const std::exception &e) { + std::cerr << cInitErrorMsg << e.what() + << std::endl; + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Parses the configuration file line by line. +/// +/// Skips comments and empty lines. Validates keys against models. +/// @return true if the configuration was successfully loaded, else false. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool ConfigManager::load() { + std::ifstream file(m_fileName); + if (m_verbose) { + std::cout << cLoadingConfigMsg << std::endl; + } + + if (!file.is_open()) { + std::cerr << cUnableToOpenFileMsg << m_fileName << std::endl; + return false; + } + + std::string line; + while (std::getline(file, line)) { + // Skip empty lines and comments + if (line.empty() || line[0] == cConfigCommentChar) { + continue; + } + + std::istringstream iss(line); + std::string key, value; + + if (std::getline(iss, key, cConfigAssignDelimiter) && + std::getline(iss, value)) { + // Trim whitespace + key.erase(0, key.find_first_not_of(" \t\n\r")); + key.erase(key.find_last_not_of(" \t\n\r") + 1); + value.erase(0, value.find_first_not_of(" \t\n\r")); + value.erase(value.find_last_not_of(" \t\n\r") + 1); + + // Map keys to specific models + if (m_config->validateKey(key)) { + if (!m_config->update(key, value)) { + m_config->add(key, value); + } + } else { + std::cerr << cUnknownKeyWarningMsg << key + << std::endl; + continue; + } + } + } + + file.close(); + if (m_verbose) { + std::cout << cLoadConfigDoneMsg << std::endl; + } + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Serializes all models and writes them to the configuration file. +/// @return true if the configuration was successfully stored, else false. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool ConfigManager::store(bool forceVerbose) { + std::ofstream file(m_fileName); + bool shouldPrint = forceVerbose && m_verbose; + if (shouldPrint) { + std::cout << cStoringConfigMsg << std::endl; + } + + if (!file.is_open()) { + std::cerr << cUnableToOpenFileMsg << m_fileName << std::endl; + return false; + } + + // Internal helper lambda for writing model entries + auto writeModel = [&](const auto &model) { + for (const auto &[key, value] : model.getAllEntries()) { + file << key << cConfigAssignDelimiter << value << "\n"; + } + }; + + writeModel(*m_config); + + file.close(); + if (shouldPrint) { + std::cout << cStoreConfigDoneMsg << std::endl; + } + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the control configuration. +/// @param config Reference to the Model configuration object. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void ConfigManager::setConfig(const Electux::App::Model::IModel &config) { + m_config = config.clone(); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Gets the current control configuration. +/// @return A constant reference to the Model configuration. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +const Electux::App::Model::IModel &ConfigManager::getConfig() const { + return *m_config; +} diff --git a/sw/restatdesk/config/config_manager.h b/sw/restatdesk/config/config_manager.h new file mode 100644 index 0000000..faa9ca7 --- /dev/null +++ b/sw/restatdesk/config/config_manager.h @@ -0,0 +1,111 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// config_manager.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Model { + class Model; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Config +/// @brief Namespace for application configuration management +namespace Electux::App::Config { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ConfigManager + /// @brief Implementation of the IConfig interface for configuration + /// management. + /// + /// This class manages the loading, storing, and access of various + /// application configuration modules including Control, Serial, and + /// Logging. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ConfigManager : public IConfig { + public: + explicit ConfigManager( + std::unique_ptr config, + const std::string &configFileName = "", + bool verbose = false + ); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief ConfigManager destructor. + //////////////////////////////////////////////////////////////////////////////////////////////// + ~ConfigManager() override; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Initializes the configuration manager. + /// Performs file system checks, directory creation, and initial load. + //////////////////////////////////////////////////////////////////////////////////////////////// + void init() final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Loads the configuration from the specified file. + /// @return true if the configuration was successfully loaded, else + /// false. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool load() final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Stores the current configuration to the specified file. + /// @return true if the configuration was successfully stored, else + /// false. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool store(bool verbose = false) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the log configuration. + /// @param config Reference to the Model configuration object. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setConfig(const Model &config) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets the current log configuration. + /// @return A constant reference to the Model configuration. + //////////////////////////////////////////////////////////////////////////////////////////////// + const Model &getConfig() const final; + + protected: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Populates models with default values and stores them to a + /// file. + /// + /// This method is typically called when no configuration file is found + /// or when a factory reset of the configuration is required. + //////////////////////////////////////////////////////////////////////////////////////////////// + void defaultConfigStore(); + void populateDefaults(); + + private: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Path to the configuration file. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::string m_fileName{}; + + bool m_verbose{false}; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Model data instance. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::unique_ptr m_config; + }; +} // namespace Electux::App::Config diff --git a/sw/restatdesk/config/config_manager_utils.cc b/sw/restatdesk/config/config_manager_utils.cc new file mode 100644 index 0000000..2ab485a --- /dev/null +++ b/sw/restatdesk/config/config_manager_utils.cc @@ -0,0 +1,133 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// config_manager_utils.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Internal Configuration Constants + /// @{ + // Default values for Control Model + constexpr std::string_view cConfigDefaultControlEnable{ + "false false false false false false false false" + }; + constexpr std::string_view cConfigDefaultControlMode{ + "0 0 0 0 0 0 0 0" + }; + constexpr std::string_view cConfigDefaultControlToggle{ + "false false false false false false false false" + }; + constexpr std::string_view cConfigDefaultControlTimer{"0 0 0 0 0 0 0 0"}; + constexpr std::string_view cConfigDefaultControlTimerEnable{ + "false false false false false false false false" + }; + // Default values for Serial Model + constexpr std::string_view cConfigDefaultSerialDevice{"/dev/ttyUSB0"}; + constexpr std::string_view cConfigDefaultSerialBaud{"10"}; + constexpr std::string_view cConfigDefaultSerialData{"3"}; + constexpr std::string_view cConfigDefaultSerialParity{"2"}; + constexpr std::string_view cConfigDefaultSerialStop{"0"}; + constexpr std::string_view cConfigDefaultSerialFlow{"0"}; + // Default values for Log Model + constexpr std::string_view cConfigDefaultLogFilePath{"/tmp/restatdesk.log" + }; + constexpr std::string_view cConfigDefaultLogLevel{"2"}; + // Default values for General Model + constexpr std::string_view cConfigDefaultGeneralComType{"serial"}; + constexpr std::string_view cConfigDefaultGeneralTcpIp{"127.0.0.1"}; + constexpr std::string_view cConfigDefaultGeneralTcpPort{"5000"}; + // Default values for BLE Model + constexpr std::string_view cConfigDefaultBleAddress{"00:00:00:00:00:00"}; + constexpr std::string_view cConfigDefaultBleServiceUuid{"0000ffe0-0000-1000-8000-00805f9b34fb"}; + constexpr std::string_view cConfigDefaultBleRxUuid{"0000ffe1-0000-1000-8000-00805f9b34fb"}; + constexpr std::string_view cConfigDefaultBleTxUuid{"0000ffe1-0000-1000-8000-00805f9b34fb"}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace + +using namespace Electux::App::Config; +using namespace Electux::App::Model; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Populates models with hardcoded defaults and persists them. +/// +/// This method is typically called when no configuration file is found +/// or when a factory reset of the configuration is required. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void ConfigManager::defaultConfigStore() { + populateDefaults(); + store(); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Populates models with default values. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void ConfigManager::populateDefaults() { + // Set default control configuration + const auto enableKey = m_config->toString(ModelControlKey::Enable); + m_config->add(enableKey, cConfigDefaultControlEnable.data()); + const auto modeKey = m_config->toString(ModelControlKey::Mode); + m_config->add(modeKey, cConfigDefaultControlMode.data()); + const auto toggleKey = m_config->toString(ModelControlKey::Toggle); + m_config->add(toggleKey, cConfigDefaultControlToggle.data()); + const auto timerKey = m_config->toString(ModelControlKey::Timer); + m_config->add(timerKey, cConfigDefaultControlTimer.data()); + const auto timerEnableKey = + m_config->toString(ModelControlKey::TimerEnable); + m_config->add(timerEnableKey, cConfigDefaultControlTimerEnable.data()); + + // Set default serial configuration + const auto deviceKey = m_config->toString(ModelSerialKey::Device); + m_config->add(deviceKey, cConfigDefaultSerialDevice.data()); + const auto baudKey = m_config->toString(ModelSerialKey::Baud); + m_config->add(baudKey, cConfigDefaultSerialBaud.data()); + const auto dataKey = m_config->toString(ModelSerialKey::Data); + m_config->add(dataKey, cConfigDefaultSerialData.data()); + const auto parityKey = m_config->toString(ModelSerialKey::Parity); + m_config->add(parityKey, cConfigDefaultSerialParity.data()); + const auto stopKey = m_config->toString(ModelSerialKey::Stop); + m_config->add(stopKey, cConfigDefaultSerialStop.data()); + const auto flowKey = m_config->toString(ModelSerialKey::Flow); + m_config->add(flowKey, cConfigDefaultSerialFlow.data()); + + // Set default log configuration + const auto filePathKey = m_config->toString(ModelLogKey::FilePath); + m_config->add(filePathKey, cConfigDefaultLogFilePath.data()); + const auto logLevelKey = m_config->toString(ModelLogKey::LogLevel); + m_config->add(logLevelKey, cConfigDefaultLogLevel.data()); + + // Set default general configuration + const auto comTypeKey = m_config->toString(ModelGeneralKey::ComType); + m_config->add(comTypeKey, cConfigDefaultGeneralComType.data()); + const auto tcpIpKey = m_config->toString(ModelGeneralKey::TcpIp); + m_config->add(tcpIpKey, cConfigDefaultGeneralTcpIp.data()); + const auto tcpPortKey = m_config->toString(ModelGeneralKey::TcpPort); + m_config->add(tcpPortKey, cConfigDefaultGeneralTcpPort.data()); + + // Set default BLE configuration + const auto bleAddrKey = m_config->toString(ModelBleKey::Address); + m_config->add(bleAddrKey, cConfigDefaultBleAddress.data()); + const auto bleServiceKey = m_config->toString(ModelBleKey::ServiceUuid); + m_config->add(bleServiceKey, cConfigDefaultBleServiceUuid.data()); + const auto bleRxKey = m_config->toString(ModelBleKey::RxUuid); + m_config->add(bleRxKey, cConfigDefaultBleRxUuid.data()); + const auto bleTxKey = m_config->toString(ModelBleKey::TxUuid); + m_config->add(bleTxKey, cConfigDefaultBleTxUuid.data()); +} diff --git a/sw/restatdesk/config/iconfig.h b/sw/restatdesk/config/iconfig.h new file mode 100644 index 0000000..e217be7 --- /dev/null +++ b/sw/restatdesk/config/iconfig.h @@ -0,0 +1,91 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// iconfig.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Model +/// @brief Namespace for application data model and entities +namespace Electux::App::Model { + class IModel; +} // namespace Electux::App::Model + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Config +/// @brief Namespace for application configuration management +namespace Electux::App::Config { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IConfig + /// @brief Interface for configuration mechanism. + /// + /// This interface defines the core operations for loading and storing + /// configuration data, allowing for different storage implementations + /// (e.g., file system, database, etc.). + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IConfig { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using Model = Electux::App::Model::IModel; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Virtual destructor for the IConfig interface. + /// Ensures proper destruction of derived class objects. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline virtual ~IConfig() noexcept = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Initializes the configuration manager. + /// Performs file system checks, directory creation, and initial load. + /// Implementations should handle the specifics of the init mechanism, + /// such as file paths, database connections, etc. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void init() = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Loads configuration data from a source. + /// @return true if the configuration was successfully loaded, else + /// false. Implementations should handle the specifics of the loading + /// mechanism. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool load() = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Stores current configuration data to a destination. + /// @return true if the configuration was successfully stored, else + /// false. Implementations should handle the specifics of the storing + /// mechanism, such as file paths, database connections, etc. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool store(bool verbose = false) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the log configuration. + /// @param config Reference to the Model configuration object. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setConfig(const Model &config) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets the current log configuration. + /// @return A constant reference to the Model configuration. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual const Model &getConfig() const = 0; + }; +} // namespace Electux::App::Config diff --git a/sw/restatdesk/iapp_controller.h b/sw/restatdesk/iapp_controller.h new file mode 100644 index 0000000..b7d9182 --- /dev/null +++ b/sw/restatdesk/iapp_controller.h @@ -0,0 +1,58 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// iapp_controller.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App { + namespace Model { + class IModel; + class SettingsSetup; + } // namespace Model + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IAppController + /// @brief Interface defining the contract for the application business + /// logic coordinator. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IAppController { + public: + virtual ~IAppController() = default; + + virtual void startup() = 0; + virtual void shutdown() = 0; + + virtual const Model::IModel &getModel() const = 0; + + virtual void onSetupChanged(const Model::SettingsSetup &setup) = 0; + + virtual void executePlan() = 0; + + virtual sigc::signal signal_data_received() = 0; + + virtual void turnOnAllChannels() = 0; + virtual void turnOffAllChannels() = 0; + virtual void requestAllChannelsStatus() = 0; + virtual void resetSystem() = 0; + virtual void requestBoardId() = 0; + virtual void requestVersion() = 0; + }; +} // namespace Electux::App diff --git a/sw/restatdesk/log/.editorconfig b/sw/restatdesk/log/.editorconfig new file mode 100644 index 0000000..72716a4 --- /dev/null +++ b/sw/restatdesk/log/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 diff --git a/sw/restatdesk/log/ilog.h b/sw/restatdesk/log/ilog.h new file mode 100644 index 0000000..2822e53 --- /dev/null +++ b/sw/restatdesk/log/ilog.h @@ -0,0 +1,99 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ilog.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Logger +/// @brief Namespace for application logging components +namespace Electux::App::Logger { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @enum LogLevel + /// @brief Defines the severity levels for log messages. + //////////////////////////////////////////////////////////////////////////////////////////////////// + enum class LogLevel : uint8_t { + Error = 0, ///< Critical errors or failures + Warning, ///< Non-critical issues or warnings + Info ///< General informational messages + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ILog + /// @brief Interface for logging implementations. + /// + /// This interface defines the standard operations for a logger, including + /// level filtering, managing the logging sink connection, and writing logs. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ILog { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Virtual destructor for the ILog interface. + /// Ensures proper cleanup of derived logger implementations. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual ~ILog() noexcept = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Specific to File Logger: Sets the destination file path. + /// @param output The absolute or relative path to the log file. + /// Implementation should handle the specifics of output such as file + /// path. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setOutputFile(const std::string &output) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the filtering log level. + /// @param level The log level to set for filtering messages. + /// Implementation should handle the specifics of setting filtering + /// messages. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void setLevel(LogLevel level) = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets the current filtering log level. + /// @return The current log level used for filtering messages. + /// Implementation should handle the specifics of getting filtering + /// messages. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual LogLevel getLevel() const = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Opens the logging sink (e.g., file, socket, console). + /// @return true if the sink was successfully opened, otherwise false. + /// Implementation should handle the specifics of opening log file. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool open() = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Closes the logging sink. + /// @return true if the sink was successfully closed, otherwise false. + /// Implementation should handle the specifics of closing log file. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual bool close() = 0; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Logs a message to the active sink. + /// @param message The string content to be logged. + /// @param level The severity level of the log message. + /// Implementation should handle the specifics of logging messages. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual void log(const std::string &message, LogLevel level) = 0; + }; +} // namespace Electux::App::Logger diff --git a/sw/restatdesk/log/log.cc b/sw/restatdesk/log/log.cc new file mode 100644 index 0000000..ba27f15 --- /dev/null +++ b/sw/restatdesk/log/log.cc @@ -0,0 +1,170 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Logger +/// @brief Namespace for application logging components +namespace Electux::App::Logger { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Internal Formatting Constants + /// @{ + static constexpr std::string_view TAG_ERROR = + "[ERROR] "; ///< Tag for error messages + static constexpr std::string_view TAG_WARN = + "[WARN] "; ///< Tag for warning messages + static constexpr std::string_view TAG_INFO = + "[INFO] "; ///< Tag for info messages + static constexpr const char *cTimestampFormat = "%Y-%m-%dT%H:%M:%S"; + static constexpr const char *cOutputNotSetError = + "Output file path is not set. Cannot open log stream."; + static constexpr const char *cCloseStreamError = + "Failed to close log stream for file: "; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace Electux::App::Logger + +using namespace Electux::App::Logger; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Destructor for the Log class. +/// Calls close() to ensure the file stream is flushed and closed safely. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +Log::~Log() { close(); } + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the destination file path for the logger. +/// @param output The path to the log file. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void Log::setOutputFile(const std::string &output) { m_outputFile = output; } + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Sets the filtering log level. +/// @param level The log level to set (Error, Warning, or Info). +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void Log::setLevel(LogLevel level) { m_level = level; } + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Gets the current filtering log level. +/// @return The current LogLevel enum value. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +LogLevel Log::getLevel() const { return m_level; } + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Opens the log file stream. +/// Uses std::ios::app to append to existing file content. +/// @return true if the stream is ready for writing, false otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool Log::open() { + std::lock_guard lk(m_mutex); + + // If already open, return true + if (m_stream.is_open()) { + return true; + } + + // Validate that an output file path has been set + if (m_outputFile.empty()) { + std::cerr << cOutputNotSetError << std::endl; + return false; + } + + m_stream.open(m_outputFile, std::ios::out | std::ios::app); + return m_stream.is_open(); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Closes the log file stream. +/// @return true if the stream was open or closed and is now closed, false +/// otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +bool Log::close() { + std::lock_guard lk(m_mutex); + + if (!m_stream.is_open()) { + // Stream is already closed, consider this a successful close operation + return true; + } + + // Attempt to close the stream + m_stream.close(); + + if (m_stream.fail()) { + // If closing failed, clear the error state to allow future operations + m_stream.clear(); + // Log the error to stderr for debugging purposes + std::cerr << cCloseStreamError << m_outputFile << std::endl; + return false; + } + + // Successfully closed the stream + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Formats and writes a log entry. +/// +/// Processes the message by: +/// 1. Checking if the stream is open. +/// 2. Filtering based on the current log level. +/// 3. Generating a ISO 8601 timestamp (YYYY-MM-DDTHH:MM:SS). +/// 4. Appending the appropriate severity tag. +/// 5. Flushing the stream to ensure data is written to disk immediately. +/// +/// @param message The text content to log. +/// @param level The severity of the entry. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +void Log::log(const std::string &message, LogLevel level) { + std::lock_guard lk(m_mutex); + + if (!m_stream.is_open()) { + return; + } + + if (static_cast(level) > static_cast(m_level)) { + return; + } + + auto now = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + localtime_r(&t, &tm); + + m_stream << std::put_time(&tm, cTimestampFormat) << " "; + + switch (level) { + case LogLevel::Error: + m_stream << TAG_ERROR; + break; + case LogLevel::Warning: + m_stream << TAG_WARN; + break; + case LogLevel::Info: + m_stream << TAG_INFO; + break; + } + + m_stream << message << std::endl; + m_stream.flush(); +} diff --git a/sw/restatdesk/log/log.h b/sw/restatdesk/log/log.h new file mode 100644 index 0000000..7394320 --- /dev/null +++ b/sw/restatdesk/log/log.h @@ -0,0 +1,109 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Logger +/// @brief Namespace for application logging components +namespace Electux::App::Logger { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class Log + /// @brief A file-based implementation of the ILog interface. + /// + /// This class provides thread-safe logging to a physical file on disk. + /// It supports log level filtering and automatic timestamping of entries. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class Log : public ILog { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Default constructor for the Log class. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline Log() noexcept = default; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Destructor for the Log class. + /// Ensures that the log file stream is properly closed before + /// destruction. + //////////////////////////////////////////////////////////////////////////////////////////////// + ~Log() noexcept; + + // Deleted copy constructor and assignment operator to prevent + // duplicates + Log(const Log &) = delete; + Log &operator=(const Log &) = delete; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the filtering log level. + /// @param level The log level to set for filtering messages. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setLevel(LogLevel level) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets the current filtering log level. + /// @return The current log level used for filtering messages. + //////////////////////////////////////////////////////////////////////////////////////////////// + LogLevel getLevel() const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Opens the logging sink (file stream). + /// @return true if the file was successfully opened, else false. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool open() final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Closes the logging sink (file stream). + /// @return true if the stream was successfully closed, else false. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool close() final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Logs a message to the file with a timestamp and severity tag. + /// @param message The string content to log. + /// @param level The severity of the message. + /// @note This operation is thread-safe. + //////////////////////////////////////////////////////////////////////////////////////////////// + void log(const std::string &message, LogLevel level) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Specific to File Logger: Sets the destination file path. + /// @param output The absolute or relative path to the log file. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setOutputFile(const std::string &output) final; + + private: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Internal State and Thread Safety + /// @{ + /// @brief Current filtering log level. + LogLevel m_level{LogLevel::Info}; + /// @brief Path to the destination log file. + std::string m_outputFile{}; + /// @brief Output file stream for logging operations. + std::ofstream m_stream{}; + /// @brief Mutex to ensure thread-safe access to the file stream. + mutable std::mutex m_mutex{}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + }; +} // namespace Electux::App::Logger diff --git a/sw/restatdesk/log/log_factory.cc b/sw/restatdesk/log/log_factory.cc new file mode 100644 index 0000000..8134f8c --- /dev/null +++ b/sw/restatdesk/log/log_factory.cc @@ -0,0 +1,28 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log_factory.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace Electux::App::Logger { + std::unique_ptr createLogger() { + return std::make_unique(); + } +} // namespace Electux::App::Logger diff --git a/sw/restatdesk/log/log_factory.h b/sw/restatdesk/log/log_factory.h new file mode 100644 index 0000000..e5e8a88 --- /dev/null +++ b/sw/restatdesk/log/log_factory.h @@ -0,0 +1,27 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log_factory.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Logger { + std::unique_ptr createLogger(); +} // namespace Electux::App::Logger diff --git a/sw/restatdesk/log/log_level_params.h b/sw/restatdesk/log/log_level_params.h new file mode 100644 index 0000000..c7be715 --- /dev/null +++ b/sw/restatdesk/log/log_level_params.h @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log_level_params.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Logger::LogLevels +/// @brief Namespace for log level configuration parameters +namespace Electux::App::Logger::LogLevels { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Log Levels Definitions + /// @{ + /// @brief Array of string representations for log levels + constexpr std::string_view cLogLevels[]{"Error", "Warning", "Info"}; + /// @brief Constant index for the Error log level + constexpr const uint32_t clogLevelError = 0; + /// @brief Constant index for the Warning log level + constexpr const uint32_t clogLevelWarning = 1; + /// @brief Constant index for the Info log level + constexpr const uint32_t clogLevelInfo = 2; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace Electux::App::Logger::LogLevels diff --git a/sw/restatdesk/main.cc b/sw/restatdesk/main.cc new file mode 100644 index 0000000..948c3d8 --- /dev/null +++ b/sw/restatdesk/main.cc @@ -0,0 +1,47 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// main.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#include +#include + +using namespace Electux::App; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief The main entry point of the restatdesk application. +/// +/// This function initializes the entry application and starts the main +/// execution loop, returning the final exit status. +/// +/// @param argc [in] The number of command-line arguments. +/// @param argv [in] The array of command-line arguments. +/// @return The exit status of the application (0 for success). +//////////////////////////////////////////////////////////////////////////////////////////////////////// +int main(int argc, char *argv[]) { + bool verbose = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "-v" || std::string(argv[i]) == "--verbose") { + verbose = true; + break; + } + } + + auto app = EntryApplication::create(verbose); + const int status = app->run(argc, argv); + + return status; +} diff --git a/sw/restatdesk/model/.editorconfig b/sw/restatdesk/model/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/model/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/model/channel_state.h b/sw/restatdesk/model/channel_state.h new file mode 100644 index 0000000..2f020fc --- /dev/null +++ b/sw/restatdesk/model/channel_state.h @@ -0,0 +1,63 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// channel_state.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Model::Channel +/// @brief Namespace for channel-related configuration parameters and state +namespace Electux::App::Model::Channel { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief The total number of communication channels supported by the + /// system + //////////////////////////////////////////////////////////////////////////////////////////////////// + constexpr const ssize_t cNumOfChannels = 8; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Internal Home Slot Constants + /// @{ + constexpr std::string_view cEmptyString = ""; + constexpr std::string_view cSpaceString = " "; + constexpr char cSpaceDelimiter = ' '; + constexpr std::string_view cTrue = "true"; + constexpr std::string_view cFalse = "false"; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + struct ChannelState { + bool enabled{false}; + ChannelMode mode{ChannelMode::Unknown}; + bool toggle{false}; + int timer{0}; + bool timerEnabled{false}; + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a boolean value to its string representation. + /// @param value Boolean value to convert. + /// @return "true" if value is true, "false" otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////////// + constexpr std::string_view boolToString(bool value) { + return value ? cTrue : cFalse; + } +} // namespace Electux::App::Model::Channel diff --git a/sw/restatdesk/model/channel_types.h b/sw/restatdesk/model/channel_types.h new file mode 100644 index 0000000..d33decc --- /dev/null +++ b/sw/restatdesk/model/channel_types.h @@ -0,0 +1,83 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// channel_types.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Model::Channel { + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Enumeration of channel operational modes. + //////////////////////////////////////////////////////////////////////////////////////////////// + enum class ChannelMode : int { + Unknown = -1, + Toggle = 0, + Timer, + Count + }; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Structure containing information about a channel operational mode. + //////////////////////////////////////////////////////////////////////////////////////////////// + struct ChannelModeInfo { + ChannelMode mode; + std::string_view configKey; + std::string_view displayName; + }; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Array of channel mode descriptors. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline constexpr std::array< + ChannelModeInfo, static_cast(ChannelMode::Count)> + cChannelModeDescriptors{ + {{ChannelMode::Toggle, "toggle", "Toggle Mode"}, + {ChannelMode::Timer, "timer", "Timer Mode"}} + }; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a ChannelMode to its configuration key string. + /// @param mode The ChannelMode to convert. + /// @return The configuration key string for the given ChannelMode. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline constexpr std::string_view toConfigString(ChannelMode mode) { + for (const auto &desc : cChannelModeDescriptors) { + if (desc.mode == mode) + return desc.configKey; + } + return "unknown"; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a configuration key string to its ChannelMode. + /// @param key The configuration key string to convert. + /// @return The ChannelMode for the given configuration key. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline constexpr ChannelMode fromConfigString(std::string_view key) { + for (const auto &desc : cChannelModeDescriptors) { + if (desc.configKey == key) + return desc.mode; + } + return ChannelMode::Unknown; + } + +} // namespace Electux::App::Model::Channel diff --git a/sw/restatdesk/model/delegate/.editorconfig b/sw/restatdesk/model/delegate/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/model/delegate/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/model/delegate/ble/.editorconfig b/sw/restatdesk/model/delegate/ble/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/model/delegate/ble/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/model/delegate/ble/ble_model_delegate.cc b/sw/restatdesk/model/delegate/ble/ble_model_delegate.cc new file mode 100644 index 0000000..cf71ce7 --- /dev/null +++ b/sw/restatdesk/model/delegate/ble/ble_model_delegate.cc @@ -0,0 +1,61 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_model_delegate.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Model { + namespace { + constexpr std::string_view cBleAddress{"ble_address"}; + constexpr std::string_view cBleServiceUuid{"ble_service_uuid"}; + constexpr std::string_view cBleRxUuid{"ble_rx_uuid"}; + constexpr std::string_view cBleTxUuid{"ble_tx_uuid"}; + constexpr std::string_view cUnknown{"unknown"}; + } // namespace + + std::string_view BleModelDelegate::toString(ModelBleKey key) const { + switch (key) { + case ModelBleKey::Address: + return cBleAddress; + case ModelBleKey::ServiceUuid: + return cBleServiceUuid; + case ModelBleKey::RxUuid: + return cBleRxUuid; + case ModelBleKey::TxUuid: + return cBleTxUuid; + default: + return cUnknown; + } + } + + bool BleModelDelegate::validateKey(const std::string_view &key) const { + static const std::initializer_list validKeys = { + cBleAddress, cBleServiceUuid, cBleRxUuid, cBleTxUuid + }; + return std::any_of(validKeys.begin(), validKeys.end(), [&](auto k) { + return k == key; + }); + } + + std::unique_ptr BleModelDelegate::clone() const { + return std::make_unique(*this); + } +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/ble/ble_model_delegate.h b/sw/restatdesk/model/delegate/ble/ble_model_delegate.h new file mode 100644 index 0000000..754d949 --- /dev/null +++ b/sw/restatdesk/model/delegate/ble/ble_model_delegate.h @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class BleModelDelegate + /// @brief Handles BLE communication configuration keys and validation. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class BleModelDelegate : public IBleModelDelegate { + public: + BleModelDelegate() = default; + ~BleModelDelegate() override = default; + + std::string_view toString(ModelBleKey key) const override; + bool validateKey(const std::string_view &key) const override; + + std::unique_ptr clone() const override; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/ble/ible_model_delegate.h b/sw/restatdesk/model/delegate/ble/ible_model_delegate.h new file mode 100644 index 0000000..b5194cf --- /dev/null +++ b/sw/restatdesk/model/delegate/ble/ible_model_delegate.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ible_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IBleModelDelegate + /// @brief Interface for BLE settings delegates. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IBleModelDelegate { + public: + virtual ~IBleModelDelegate() = default; + + virtual std::string_view toString(ModelBleKey key) const = 0; + virtual bool validateKey(const std::string_view &key) const = 0; + + virtual std::unique_ptr clone() const = 0; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/control/.editorconfig b/sw/restatdesk/model/delegate/control/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/model/delegate/control/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/model/delegate/control/control_model_delegate.cc b/sw/restatdesk/model/delegate/control/control_model_delegate.cc new file mode 100644 index 0000000..708a734 --- /dev/null +++ b/sw/restatdesk/model/delegate/control/control_model_delegate.cc @@ -0,0 +1,173 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// control_model_delegate.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include + +namespace Electux::App::Model { + namespace { + constexpr std::string_view cEnable{"enable"}; + constexpr std::string_view cMode{"mode"}; + constexpr std::string_view cToggle{"toggle"}; + constexpr std::string_view cTimer{"timer"}; + constexpr std::string_view cTimerEnable{"timerEnable"}; + constexpr std::string_view cUnknown{"unknown"}; + constexpr std::string_view cTrueVal{"true"}; + constexpr std::string_view cFalseVal{"false"}; + constexpr std::string_view cModeToggleVal{"0"}; + constexpr std::string_view cModeTimerVal{"1"}; + constexpr std::string_view cModeToggle{"toggle"}; + constexpr std::string_view cModeTimer{"timer"}; + + std::vector split_to_vector(const std::string_view &input) { + std::vector elements; + std::stringstream ss{std::string(input)}; + std::string item; + while (ss >> item) { + elements.push_back(item); + } + return elements; + } + + std::string extract_param_value_by_index( + const std::string_view &input, size_t index + ) { + auto elements = split_to_vector(input); + if (index < elements.size()) { + return elements[index]; + } + return ""; + } + + std::string update_param_value_by_index( + const std::string_view &input, size_t index, + const std::string_view &newValue + ) { + auto elements = split_to_vector(input); + if (elements.size() < static_cast(Electux::App::Model::Channel::cNumOfChannels)) { + std::string defaultValue = + elements.empty() ? std::string(newValue) : elements.back(); + elements.resize( + static_cast(Electux::App::Model::Channel::cNumOfChannels), + defaultValue + ); + } + if (index < elements.size()) { + elements[index] = std::string(newValue); + } + std::string result; + for (size_t i = 0; i < elements.size(); ++i) { + result += elements[i] + (i < elements.size() - 1 ? " " : ""); + } + return result; + } + } // namespace + + std::string_view ControlModelDelegate::toString(ModelControlKey key) const { + switch (key) { + case ModelControlKey::Enable: + return cEnable; + case ModelControlKey::Mode: + return cMode; + case ModelControlKey::Toggle: + return cToggle; + case ModelControlKey::Timer: + return cTimer; + case ModelControlKey::TimerEnable: + return cTimerEnable; + default: + return cUnknown; + } + } + + bool ControlModelDelegate::validateKey(const std::string_view &key) const { + static const std::initializer_list validKeys = { + cEnable, cMode, cToggle, cTimer, cTimerEnable + }; + return std::any_of(validKeys.begin(), validKeys.end(), [&](auto k) { + return k == key; + }); + } + + ChannelState ControlModelDelegate::getChannelState(const Entities &entities, size_t index) const { + using Electux::App::Model::Channel::ChannelMode; + + auto getEntityStr = [&](ModelControlKey key) -> std::string { + auto keyStr = std::string(toString(key)); + auto it = entities.find(keyStr); + if (it != entities.end()) { + return it->second; + } + return ""; + }; + + ChannelState state; + + state.enabled = (extract_param_value_by_index(getEntityStr(ModelControlKey::Enable), index) == cTrueVal); + + auto modeStr = extract_param_value_by_index(getEntityStr(ModelControlKey::Mode), index); + if (modeStr.empty()) { + state.mode = ChannelMode::Unknown; + } else if (modeStr == cModeToggleVal || modeStr == cModeToggle) { + state.mode = ChannelMode::Toggle; + } else if (modeStr == cModeTimerVal || modeStr == cModeTimer) { + state.mode = ChannelMode::Timer; + } else { + state.mode = ChannelMode::Unknown; + } + + state.toggle = (extract_param_value_by_index(getEntityStr(ModelControlKey::Toggle), index) == cTrueVal); + + auto timerStr = extract_param_value_by_index(getEntityStr(ModelControlKey::Timer), index); + state.timer = timerStr.empty() ? 0 : std::stoi(timerStr); + + state.timerEnabled = (extract_param_value_by_index(getEntityStr(ModelControlKey::TimerEnable), index) == cTrueVal); + + return state; + } + + void ControlModelDelegate::setChannelState( + Entities &entities, size_t index, const ChannelState &state + ) const { + using Electux::App::Model::Channel::toConfigString; + + auto updateEntity = [&](ModelControlKey key, const std::string &newValue) { + auto keyStr = std::string(toString(key)); + auto it = entities.find(keyStr); + if (it != entities.end()) { + it->second = update_param_value_by_index(it->second, index, newValue); + } + }; + + updateEntity(ModelControlKey::Enable, state.enabled ? std::string(cTrueVal) : std::string(cFalseVal)); + updateEntity(ModelControlKey::Mode, std::string(toConfigString(state.mode))); + updateEntity(ModelControlKey::Toggle, state.toggle ? std::string(cTrueVal) : std::string(cFalseVal)); + updateEntity(ModelControlKey::Timer, std::to_string(state.timer)); + updateEntity(ModelControlKey::TimerEnable, state.timerEnabled ? std::string(cTrueVal) : std::string(cFalseVal)); + } + + std::unique_ptr ControlModelDelegate::clone() const { + return std::make_unique(*this); + } +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/control/control_model_delegate.h b/sw/restatdesk/model/delegate/control/control_model_delegate.h new file mode 100644 index 0000000..c277e63 --- /dev/null +++ b/sw/restatdesk/model/delegate/control/control_model_delegate.h @@ -0,0 +1,45 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// control_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ControlModelDelegate + /// @brief Handles control and channel configuration keys, validation, and states. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ControlModelDelegate : public IControlModelDelegate { + public: + ControlModelDelegate() = default; + ~ControlModelDelegate() override = default; + + std::string_view toString(ModelControlKey key) const override; + bool validateKey(const std::string_view &key) const override; + + ChannelState getChannelState(const Entities &entities, size_t index) const override; + void setChannelState(Entities &entities, size_t index, const ChannelState &state) const override; + + std::unique_ptr clone() const override; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/control/icontrol_model_delegate.h b/sw/restatdesk/model/delegate/control/icontrol_model_delegate.h new file mode 100644 index 0000000..c982462 --- /dev/null +++ b/sw/restatdesk/model/delegate/control/icontrol_model_delegate.h @@ -0,0 +1,43 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// icontrol_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IControlModelDelegate + /// @brief Interface for control and channel settings delegates. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IControlModelDelegate { + public: + virtual ~IControlModelDelegate() = default; + + virtual std::string_view toString(ModelControlKey key) const = 0; + virtual bool validateKey(const std::string_view &key) const = 0; + + virtual ChannelState getChannelState(const Entities &entities, size_t index) const = 0; + virtual void setChannelState(Entities &entities, size_t index, const ChannelState &state) const = 0; + + virtual std::unique_ptr clone() const = 0; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/general/.editorconfig b/sw/restatdesk/model/delegate/general/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/model/delegate/general/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/model/delegate/general/general_model_delegate.cc b/sw/restatdesk/model/delegate/general/general_model_delegate.cc new file mode 100644 index 0000000..9ddb970 --- /dev/null +++ b/sw/restatdesk/model/delegate/general/general_model_delegate.cc @@ -0,0 +1,58 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// general_model_delegate.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Model { + namespace { + constexpr std::string_view cComType{"com_type"}; + constexpr std::string_view cTcpIp{"tcp_ip"}; + constexpr std::string_view cTcpPort{"tcp_port"}; + constexpr std::string_view cUnknown{"unknown"}; + } // namespace + + std::string_view GeneralModelDelegate::toString(ModelGeneralKey key) const { + switch (key) { + case ModelGeneralKey::ComType: + return cComType; + case ModelGeneralKey::TcpIp: + return cTcpIp; + case ModelGeneralKey::TcpPort: + return cTcpPort; + default: + return cUnknown; + } + } + + bool GeneralModelDelegate::validateKey(const std::string_view &key) const { + static const std::initializer_list validKeys = { + cComType, cTcpIp, cTcpPort + }; + return std::any_of(validKeys.begin(), validKeys.end(), [&](auto k) { + return k == key; + }); + } + + std::unique_ptr GeneralModelDelegate::clone() const { + return std::make_unique(*this); + } +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/general/general_model_delegate.h b/sw/restatdesk/model/delegate/general/general_model_delegate.h new file mode 100644 index 0000000..afa4277 --- /dev/null +++ b/sw/restatdesk/model/delegate/general/general_model_delegate.h @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// general_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class GeneralModelDelegate + /// @brief Handles general communication configuration keys and validation. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class GeneralModelDelegate : public IGeneralModelDelegate { + public: + GeneralModelDelegate() = default; + ~GeneralModelDelegate() override = default; + + std::string_view toString(ModelGeneralKey key) const override; + bool validateKey(const std::string_view &key) const override; + + std::unique_ptr clone() const override; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/general/igeneral_model_delegate.h b/sw/restatdesk/model/delegate/general/igeneral_model_delegate.h new file mode 100644 index 0000000..848874d --- /dev/null +++ b/sw/restatdesk/model/delegate/general/igeneral_model_delegate.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// igeneral_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IGeneralModelDelegate + /// @brief Interface for general/TCP settings delegates. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IGeneralModelDelegate { + public: + virtual ~IGeneralModelDelegate() = default; + + virtual std::string_view toString(ModelGeneralKey key) const = 0; + virtual bool validateKey(const std::string_view &key) const = 0; + + virtual std::unique_ptr clone() const = 0; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/log/.editorconfig b/sw/restatdesk/model/delegate/log/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/model/delegate/log/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/model/delegate/log/ilog_model_delegate.h b/sw/restatdesk/model/delegate/log/ilog_model_delegate.h new file mode 100644 index 0000000..64aa8f6 --- /dev/null +++ b/sw/restatdesk/model/delegate/log/ilog_model_delegate.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ilog_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ILogModelDelegate + /// @brief Interface for logging settings delegates. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ILogModelDelegate { + public: + virtual ~ILogModelDelegate() = default; + + virtual std::string_view toString(ModelLogKey key) const = 0; + virtual bool validateKey(const std::string_view &key) const = 0; + + virtual std::unique_ptr clone() const = 0; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/log/log_model_delegate.cc b/sw/restatdesk/model/delegate/log/log_model_delegate.cc new file mode 100644 index 0000000..15dc8d4 --- /dev/null +++ b/sw/restatdesk/model/delegate/log/log_model_delegate.cc @@ -0,0 +1,55 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log_model_delegate.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Model { + namespace { + constexpr std::string_view cLogLevel{"log_level"}; + constexpr std::string_view cFilePath{"log_file_path"}; + constexpr std::string_view cUnknown{"unknown"}; + } // namespace + + std::string_view LogModelDelegate::toString(ModelLogKey key) const { + switch (key) { + case ModelLogKey::LogLevel: + return cLogLevel; + case ModelLogKey::FilePath: + return cFilePath; + default: + return cUnknown; + } + } + + bool LogModelDelegate::validateKey(const std::string_view &key) const { + static const std::initializer_list validKeys = { + cLogLevel, cFilePath + }; + return std::any_of(validKeys.begin(), validKeys.end(), [&](auto k) { + return k == key; + }); + } + + std::unique_ptr LogModelDelegate::clone() const { + return std::make_unique(*this); + } +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/log/log_model_delegate.h b/sw/restatdesk/model/delegate/log/log_model_delegate.h new file mode 100644 index 0000000..1d87882 --- /dev/null +++ b/sw/restatdesk/model/delegate/log/log_model_delegate.h @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class LogModelDelegate + /// @brief Handles logging configuration keys and validation. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class LogModelDelegate : public ILogModelDelegate { + public: + LogModelDelegate() = default; + ~LogModelDelegate() override = default; + + std::string_view toString(ModelLogKey key) const override; + bool validateKey(const std::string_view &key) const override; + + std::unique_ptr clone() const override; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/serial/.editorconfig b/sw/restatdesk/model/delegate/serial/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/model/delegate/serial/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/model/delegate/serial/iserial_model_delegate.h b/sw/restatdesk/model/delegate/serial/iserial_model_delegate.h new file mode 100644 index 0000000..6aa09d1 --- /dev/null +++ b/sw/restatdesk/model/delegate/serial/iserial_model_delegate.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// iserial_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ISerialModelDelegate + /// @brief Interface for serial settings delegates. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ISerialModelDelegate { + public: + virtual ~ISerialModelDelegate() = default; + + virtual std::string_view toString(ModelSerialKey key) const = 0; + virtual bool validateKey(const std::string_view &key) const = 0; + + virtual std::unique_ptr clone() const = 0; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/serial/serial_model_delegate.cc b/sw/restatdesk/model/delegate/serial/serial_model_delegate.cc new file mode 100644 index 0000000..6a575b0 --- /dev/null +++ b/sw/restatdesk/model/delegate/serial/serial_model_delegate.cc @@ -0,0 +1,67 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_model_delegate.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Model { + namespace { + constexpr std::string_view cDevice{"device"}; + constexpr std::string_view cBaud{"baud"}; + constexpr std::string_view cData{"data"}; + constexpr std::string_view cParity{"parity"}; + constexpr std::string_view cStop{"stop"}; + constexpr std::string_view cFlow{"flow"}; + constexpr std::string_view cUnknown{"unknown"}; + } // namespace + + std::string_view SerialModelDelegate::toString(ModelSerialKey key) const { + switch (key) { + case ModelSerialKey::Device: + return cDevice; + case ModelSerialKey::Baud: + return cBaud; + case ModelSerialKey::Data: + return cData; + case ModelSerialKey::Parity: + return cParity; + case ModelSerialKey::Stop: + return cStop; + case ModelSerialKey::Flow: + return cFlow; + default: + return cUnknown; + } + } + + bool SerialModelDelegate::validateKey(const std::string_view &key) const { + static const std::initializer_list validKeys = { + cDevice, cBaud, cData, cParity, cStop, cFlow + }; + return std::any_of(validKeys.begin(), validKeys.end(), [&](auto k) { + return k == key; + }); + } + + std::unique_ptr SerialModelDelegate::clone() const { + return std::make_unique(*this); + } +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/delegate/serial/serial_model_delegate.h b/sw/restatdesk/model/delegate/serial/serial_model_delegate.h new file mode 100644 index 0000000..9e708ec --- /dev/null +++ b/sw/restatdesk/model/delegate/serial/serial_model_delegate.h @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_model_delegate.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SerialModelDelegate + /// @brief Handles serial communication configuration keys and validation. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SerialModelDelegate : public ISerialModelDelegate { + public: + SerialModelDelegate() = default; + ~SerialModelDelegate() override = default; + + std::string_view toString(ModelSerialKey key) const override; + bool validateKey(const std::string_view &key) const override; + + std::unique_ptr clone() const override; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/imodel.h b/sw/restatdesk/model/imodel.h new file mode 100644 index 0000000..04a8a8a --- /dev/null +++ b/sw/restatdesk/model/imodel.h @@ -0,0 +1,142 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// imodel.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Model +/// @brief Namespace for application data models and entities +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using Entities = std::map>; + using ChannelState = Electux::App::Model::Channel::ChannelState; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IModel + /// @brief Interface for application data models. + /// + /// Defines core operations for managing key-value pairs representing + /// configuration or state data within the application. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IEntityModel { + public: + virtual ~IEntityModel() = default; + + virtual bool + add(const std::string_view &key, const std::string_view &data) = 0; + + virtual bool validateKey(const std::string_view &key) const = 0; + + virtual const std::string &getEntity(const std::string_view &key + ) const = 0; + + virtual bool + update(const std::string_view &key, const std::string_view &data) = 0; + + virtual const Entities &get() const = 0; + + virtual Entities getAllEntries() const = 0; + + virtual void clear() = 0; + + virtual sigc::signal signal_changed() const = 0; + + virtual void emit_changed() const = 0; + }; + + class IControlModel { + public: + virtual ~IControlModel() = default; + + virtual ChannelState getChannelState(size_t index) const = 0; + + virtual void + setChannelState(size_t index, const ChannelState &state) = 0; + + virtual std::string_view toString(ModelControlKey key) const = 0; + }; + + class ISerialModel { + public: + virtual ~ISerialModel() = default; + + virtual std::string_view toString(ModelSerialKey key) const = 0; + }; + + class IBleModel { + public: + virtual ~IBleModel() = default; + + virtual std::string_view toString(ModelBleKey key) const = 0; + }; + + class ILogModel { + public: + virtual ~ILogModel() = default; + + virtual std::string_view toString(ModelLogKey key) const = 0; + }; + + class IGeneralModel { + public: + virtual ~IGeneralModel() = default; + + virtual std::string_view toString(ModelGeneralKey key) const = 0; + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IModel + /// @brief Interface for application data models, inheriting from segregated sub-interfaces. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IModel : public IEntityModel, + public IControlModel, + public ISerialModel, + public IBleModel, + public ILogModel, + public IGeneralModel { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Virtual destructor for the IModel interface. + //////////////////////////////////////////////////////////////////////////////////////////////// + inline ~IModel() noexcept override = default; + + using IControlModel::toString; + using ISerialModel::toString; + using IBleModel::toString; + using ILogModel::toString; + using IGeneralModel::toString; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Polymorphic deep copy of the model. + /// @return A unique_ptr containing the cloned IModel. + //////////////////////////////////////////////////////////////////////////////////////////////// + virtual std::unique_ptr clone() const = 0; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/model.cc b/sw/restatdesk/model/model.cc new file mode 100644 index 0000000..c35e8ac --- /dev/null +++ b/sw/restatdesk/model/model.cc @@ -0,0 +1,170 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// model.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace Electux::App::Model { + constexpr std::string_view cFallback{""}; +} // namespace Electux::App::Model + +using namespace Electux::App::Model; + +Model::Model( + std::unique_ptr controlDelegate, + std::unique_ptr serialDelegate, + std::unique_ptr generalDelegate, + std::unique_ptr bleDelegate, + std::unique_ptr logDelegate +) noexcept + : m_controlDelegate(std::move(controlDelegate)), + m_serialDelegate(std::move(serialDelegate)), + m_generalDelegate(std::move(generalDelegate)), + m_bleDelegate(std::move(bleDelegate)), + m_logDelegate(std::move(logDelegate)) {} + +Model::Model(const Model &other) + : m_entities(other.m_entities), + m_controlDelegate(other.m_controlDelegate ? other.m_controlDelegate->clone() : nullptr), + m_serialDelegate(other.m_serialDelegate ? other.m_serialDelegate->clone() : nullptr), + m_generalDelegate(other.m_generalDelegate ? other.m_generalDelegate->clone() : nullptr), + m_bleDelegate(other.m_bleDelegate ? other.m_bleDelegate->clone() : nullptr), + m_logDelegate(other.m_logDelegate ? other.m_logDelegate->clone() : nullptr) {} + +bool Model::add(const std::string_view &key, const std::string_view &data) { + if (m_entities.find(key) != m_entities.end()) { + return false; + } + auto [it, inserted] = + m_entities.emplace(std::string(key), std::string(data)); + return inserted; +} + +bool Model::validateKey(const std::string_view &key) const { + return (m_controlDelegate && m_controlDelegate->validateKey(key)) || + (m_serialDelegate && m_serialDelegate->validateKey(key)) || + (m_generalDelegate && m_generalDelegate->validateKey(key)) || + (m_bleDelegate && m_bleDelegate->validateKey(key)) || + (m_logDelegate && m_logDelegate->validateKey(key)); +} + +const std::string &Model::getEntity(const std::string_view &key) const { + auto it = m_entities.find(key); + if (it != m_entities.end()) { + return it->second; + } + static const std::string fallback{cFallback.data(), cFallback.size()}; + return fallback; +} + +const Entities &Model::get() const { return m_entities; } + +Entities Model::getAllEntries() const { + Entities entries; + + auto fill = [&](auto &&keys, const auto &delegate) { + if (!delegate) return; + for (const auto &key : keys) { + std::string keyStr{delegate->toString(key)}; + entries.emplace(std::move(keyStr), getEntity(keyStr)); + } + }; + + static const std::vector controlKeys = { + ModelControlKey::Enable, ModelControlKey::Mode, ModelControlKey::Toggle, + ModelControlKey::Timer, ModelControlKey::TimerEnable + }; + + static const std::vector logKeys = { + ModelLogKey::LogLevel, ModelLogKey::FilePath + }; + + static const std::vector serialKeys = { + ModelSerialKey::Device, ModelSerialKey::Baud, ModelSerialKey::Data, + ModelSerialKey::Parity, ModelSerialKey::Stop, ModelSerialKey::Flow + }; + + static const std::vector generalKeys = { + ModelGeneralKey::ComType, ModelGeneralKey::TcpIp, ModelGeneralKey::TcpPort + }; + + static const std::vector bleKeys = { + ModelBleKey::Address, ModelBleKey::ServiceUuid, + ModelBleKey::RxUuid, ModelBleKey::TxUuid + }; + + fill(controlKeys, m_controlDelegate); + fill(logKeys, m_logDelegate); + fill(serialKeys, m_serialDelegate); + fill(generalKeys, m_generalDelegate); + fill(bleKeys, m_bleDelegate); + + return entries; +} + +bool Model::update(const std::string_view &key, const std::string_view &data) { + auto it = m_entities.find(key); + if (it != m_entities.end()) { + it->second = data; + return true; + } + return false; +} + +void Model::clear() { m_entities.clear(); } + +std::string_view Model::toString(const ModelControlKey key) const { + return m_controlDelegate ? m_controlDelegate->toString(key) : ""; +} + +std::string_view Model::toString(const ModelLogKey key) const { + return m_logDelegate ? m_logDelegate->toString(key) : ""; +} + +std::string_view Model::toString(const ModelSerialKey key) const { + return m_serialDelegate ? m_serialDelegate->toString(key) : ""; +} + +std::string_view Model::toString(const ModelGeneralKey key) const { + return m_generalDelegate ? m_generalDelegate->toString(key) : ""; +} + +std::string_view Model::toString(const ModelBleKey key) const { + return m_bleDelegate ? m_bleDelegate->toString(key) : ""; +} + +ChannelState Model::getChannelState(size_t index) const { + return m_controlDelegate ? m_controlDelegate->getChannelState(m_entities, index) : ChannelState{}; +} + +void Model::setChannelState(size_t index, const ChannelState &state) { + if (m_controlDelegate) { + m_controlDelegate->setChannelState(m_entities, index, state); + } +} + +sigc::signal Model::signal_changed() const { return m_signalChanged; } + +void Model::emit_changed() const { m_signalChanged.emit(); } + +std::unique_ptr Model::clone() const { + return std::make_unique(*this); +} diff --git a/sw/restatdesk/model/model.h b/sw/restatdesk/model/model.h new file mode 100644 index 0000000..c0046d1 --- /dev/null +++ b/sw/restatdesk/model/model.h @@ -0,0 +1,196 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// model.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Model +/// @brief Namespace for application data models and entities +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class Model + /// @brief Concrete implementation of the IModel interface. + /// + /// Provides a standard container for managing application entities using + /// an internal map-based storage mechanism. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class Model : public IModel { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Model constructor with Dependency Injection. + //////////////////////////////////////////////////////////////////////////////////////////////// + Model( + std::unique_ptr controlDelegate, + std::unique_ptr serialDelegate, + std::unique_ptr generalDelegate, + std::unique_ptr bleDelegate, + std::unique_ptr logDelegate + ) noexcept; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Model copy constructor to support deep cloning. + //////////////////////////////////////////////////////////////////////////////////////////////// + Model(const Model &other); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Adds an entity to the model. + /// @param key Represents the model entity key to be added. + /// @param data Represents the model entity data to be added. + /// @return true if the entity was successfully added, false otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool + add(const std::string_view &key, const std::string_view &data) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Validates if a string key is a valid serial configuration + /// key. + /// @param key Represents the string key to be validated. + /// @return true if the key is valid, false otherwise. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool validateKey(const std::string_view &key) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets an entity value by its key. + /// @param key Represents the model entity key. + /// @return Reference to the string entity selected by key. + //////////////////////////////////////////////////////////////////////////////////////////////// + const std::string &getEntity(const std::string_view &key) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets all model entities. + /// @return Constant reference to the map of strings {key: data}. + //////////////////////////////////////////////////////////////////////////////////////////////// + const Entities &get() const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets a copy of all serial model entries. + /// @return A map containing all serial configuration entries {key: + /// data}. + //////////////////////////////////////////////////////////////////////////////////////////////// + Entities getAllEntries() const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Updates an entity value by its key. + /// @param key Represents the model entity key. + /// @param data Represents the new value for the entity. + /// @return true if the entity was updated, false if the key does not + /// exist. + //////////////////////////////////////////////////////////////////////////////////////////////// + bool + update(const std::string_view &key, const std::string_view &data) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Clears all model entities. + //////////////////////////////////////////////////////////////////////////////////////////////// + void clear() final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Gets the state of a specific channel. + /// @param index The index of the channel. + /// @return The ChannelState representation of the channel status. + //////////////////////////////////////////////////////////////////////////////////////////////// + ChannelState getChannelState(size_t index) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Sets the state of a specific channel. + /// @param index The index of the channel. + /// @param state The new ChannelState value. + //////////////////////////////////////////////////////////////////////////////////////////////// + void setChannelState(size_t index, const ChannelState &state) final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a ModelSerialKey enum value to its string + /// representation. + /// @param key Represents the ModelSerialKey enum value. + /// @return A string_view containing the key name. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::string_view toString(const ModelSerialKey key) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a ModelGeneralKey enum value to its string + /// representation. + /// @param key Represents the ModelGeneralKey enum value. + /// @return A string_view containing the key name. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::string_view toString(const ModelGeneralKey key) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a ModelBleKey enum value to its string + /// representation. + /// @param key Represents the ModelBleKey enum value. + /// @return A string_view containing the key name. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::string_view toString(const ModelBleKey key) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a ModelLogKey enum value to its string + /// representation. + /// @param key Represents the ModelLogKey enum value. + /// @return A string_view containing the key name. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::string_view toString(const ModelLogKey key) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Converts a ModelControlKey enum value to its string + /// representation. + /// @param key Represents the ModelControlKey enum value. + /// @return A string_view containing the key name. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::string_view toString(const ModelControlKey key) const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Returns a signal that is emitted when the model data changes. + /// @return A signal object that can be connected to a callback. + //////////////////////////////////////////////////////////////////////////////////////////////// + sigc::signal signal_changed() const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Emits the changed signal. + //////////////////////////////////////////////////////////////////////////////////////////////// + void emit_changed() const final; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Creates a deep copy of the model. + /// @return A unique_ptr to a new instance of the model. + //////////////////////////////////////////////////////////////////////////////////////////////// + std::unique_ptr clone() const final; + + private: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Internal storage for model entities in map format {key: + /// data}. + //////////////////////////////////////////////////////////////////////////////////////////////// + Entities m_entities{}; + mutable sigc::signal m_signalChanged{}; + + std::unique_ptr m_controlDelegate; + std::unique_ptr m_serialDelegate; + std::unique_ptr m_generalDelegate; + std::unique_ptr m_bleDelegate; + std::unique_ptr m_logDelegate; + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/model_factory.cc b/sw/restatdesk/model/model_factory.cc new file mode 100644 index 0000000..90c4565 --- /dev/null +++ b/sw/restatdesk/model/model_factory.cc @@ -0,0 +1,39 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// model_factory.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::Model { + std::unique_ptr createDefault() { + return std::make_unique( + std::make_unique(), + std::make_unique(), + std::make_unique(), + std::make_unique(), + std::make_unique() + ); + } +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/model_factory.h b/sw/restatdesk/model/model_factory.h new file mode 100644 index 0000000..607eff5 --- /dev/null +++ b/sw/restatdesk/model/model_factory.h @@ -0,0 +1,30 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// model_factory.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Creates a default model instance. + //////////////////////////////////////////////////////////////////////////////////////////////////// + std::unique_ptr createDefault(); +} // namespace Electux::App::Model diff --git a/sw/restatdesk/model/model_types.h b/sw/restatdesk/model/model_types.h new file mode 100644 index 0000000..5a2934d --- /dev/null +++ b/sw/restatdesk/model/model_types.h @@ -0,0 +1,80 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// model_types.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace Electux::App::Model { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @enum ModelControlKey + /// @brief Defines valid configuration keys for the control system. + //////////////////////////////////////////////////////////////////////////////////////////////////// + enum class ModelControlKey : uint8_t { + Enable = 0, ///< Key for enabling/disabling control features + Mode, ///< Key for setting the operational mode + Toggle, ///< Key for toggle-based control states + Timer, ///< Key for timer duration settings + TimerEnable ///< Key for enabling/disabling timer functionality + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @enum ModelLogKey + /// @brief Defines valid configuration keys for the logging system. + //////////////////////////////////////////////////////////////////////////////////////////////////// + enum class ModelLogKey : uint8_t { + FilePath = 0, ///< Key for the log file destination path + LogLevel ///< Key for the verbosity level setting + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @enum ModelSerialKey + /// @brief Defines valid configuration keys for serial communication. + //////////////////////////////////////////////////////////////////////////////////////////////////// + enum class ModelSerialKey : uint8_t { + Device = 0, ///< Key for serial device path (e.g., /dev/ttyUSB0) + Baud, ///< Key for baud rate setting + Data, ///< Key for data bits setting + Parity, ///< Key for parity setting + Stop, ///< Key for stop bits setting + Flow ///< Key for flow control setting + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @enum ModelGeneralKey + /// @brief Defines valid configuration keys for general settings + /// (communication mode, TCP). + //////////////////////////////////////////////////////////////////////////////////////////////////// + enum class ModelGeneralKey : uint8_t { + ComType = 0, ///< Key for communication type ("serial" or "tcp") + TcpIp, ///< Key for TCP IP Address + TcpPort ///< Key for TCP Port + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @enum ModelBleKey + /// @brief Defines valid configuration keys for BLE settings. + //////////////////////////////////////////////////////////////////////////////////////////////////// + enum class ModelBleKey : uint8_t { + Address = 0, ///< BLE device address or name + ServiceUuid, ///< BLE service UUID + RxUuid, ///< BLE RX characteristic UUID + TxUuid ///< BLE TX characteristic UUID + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/resources.gresource.xml b/sw/restatdesk/resources.gresource.xml new file mode 100644 index 0000000..12d757c --- /dev/null +++ b/sw/restatdesk/resources.gresource.xml @@ -0,0 +1,6 @@ + + + + style.css + + diff --git a/sw/restatdesk/restatdesk.code-workspace b/sw/restatdesk/restatdesk.code-workspace new file mode 100644 index 0000000..750f887 --- /dev/null +++ b/sw/restatdesk/restatdesk.code-workspace @@ -0,0 +1,90 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": { + "files.associations": { + "memory": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "array": "cpp", + "atomic": "cpp", + "bit": "cpp", + "*.tcc": "cpp", + "chrono": "cpp", + "compare": "cpp", + "concepts": "cpp", + "condition_variable": "cpp", + "cstdint": "cpp", + "deque": "cpp", + "list": "cpp", + "map": "cpp", + "set": "cpp", + "string": "cpp", + "unordered_map": "cpp", + "unordered_set": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "ratio": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "mutex": "cpp", + "new": "cpp", + "numbers": "cpp", + "ostream": "cpp", + "semaphore": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "stop_token": "cpp", + "streambuf": "cpp", + "thread": "cpp", + "cinttypes": "cpp", + "typeinfo": "cpp", + "valarray": "cpp", + "*.inc": "bitbake", + "complex": "cpp", + "cfenv": "cpp", + "codecvt": "cpp", + "fstream": "cpp", + "callback": "cpp", + "camera": "cpp" + }, + "files.exclude": { + "**/*.o": true, + "**/*.lss": true, + "**/core": true, + "**/resources.cc": true, + "**/build/": true, + "**/.built": true, + "**/.depend": true, + "**/Make.dep": true + } + } +} \ No newline at end of file diff --git a/sw/restatdesk/scripts/.editorconfig b/sw/restatdesk/scripts/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/scripts/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/scripts/ble/.editorconfig b/sw/restatdesk/scripts/ble/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/scripts/ble/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/scripts/ble/run-ble.py b/sw/restatdesk/scripts/ble/run-ble.py new file mode 100644 index 0000000..8f2bc33 --- /dev/null +++ b/sw/restatdesk/scripts/ble/run-ble.py @@ -0,0 +1,309 @@ +# -*- coding: UTF-8 -*- + +''' +Module + run-ble.py +Copyright + Copyright (C) 2026 Vladimir Roncevic + restat is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + restat 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 General Public License for more details. + You should have received a copy of the GNU General Public License along + with this program. If not, see . +Info + A D-Bus mock server script to simulate a BLE device for testing. +''' + +from __future__ import annotations + +from sys import stdin, exit as sys_exit, argv +from termios import tcgetattr, tcsetattr, TCSADRAIN +from tty import setcbreak +from select import select +from time import sleep, strftime +import argparse +import threading + +try: + import dbus + import dbus.service + import dbus.mainloop.glib + from gi.repository import GLib +except ImportError: + print("Error: Missing dependencies. Please install dbus-python and PyGObject:") + print(" sudo apt install python3-dbus python3-gi") + sys_exit(1) + +__author__ = 'Vladimir Roncevic' +__copyright__ = '(C) 2026, https://vroncevic.github.io/restat' +__credits__ = ['Vladimir Roncevic', 'Python Software Foundation'] +__license__ = 'https://github.com/vroncevic/restat/blob/dev/LICENSE' +__version__ = '1.0.0' +__maintainer__ = 'Vladimir Roncevic' +__email__ = 'elektron.ronca@gmail.com' +__status__ = 'Updated' + +# Default configuration values +DEFAULT_MAC = "00:11:22:33:44:55" +DEFAULT_SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb" +DEFAULT_RX_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb" +DEFAULT_TX_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb" + + +class DeviceObject(dbus.service.Object): + def __init__(self, bus, path, address): + super().__init__(bus, path) + self.path = path + self.address = address + self.connected = False + self.services_resolved = True + + @dbus.service.method('org.bluez.Device1', in_signature='', out_signature='') + def Connect(self): + print(f"[{strftime('%H:%M:%S')}] [Device] Connect called on {self.path}") + self.connected = True + self.PropertiesChanged('org.bluez.Device1', {'Connected': dbus.Boolean(True)}, []) + + @dbus.service.method('org.bluez.Device1', in_signature='', out_signature='') + def Disconnect(self): + print(f"[{strftime('%H:%M:%S')}] [Device] Disconnect called on {self.path}") + self.connected = False + self.PropertiesChanged('org.bluez.Device1', {'Connected': dbus.Boolean(False)}, []) + + @dbus.service.method('org.freedesktop.DBus.Properties', in_signature='ss', out_signature='v') + def Get(self, interface, prop): + if interface == 'org.bluez.Device1': + if prop == 'Address': + return dbus.String(self.address) + elif prop == 'Connected': + return dbus.Boolean(self.connected) + elif prop == 'ServicesResolved': + return dbus.Boolean(self.services_resolved) + raise dbus.exceptions.DBusException('org.freedesktop.DBus.Error.InvalidArgs') + + @dbus.service.method('org.freedesktop.DBus.Properties', in_signature='s', out_signature='a{sv}') + def GetAll(self, interface): + if interface == 'org.bluez.Device1': + return { + 'Address': dbus.String(self.address), + 'Connected': dbus.Boolean(self.connected), + 'ServicesResolved': dbus.Boolean(self.services_resolved) + } + return {} + + @dbus.service.signal('org.freedesktop.DBus.Properties', signature='sa{sv}as') + def PropertiesChanged(self, interface, changed, invalidated): + pass + + +class GattServiceObject(dbus.service.Object): + def __init__(self, bus, path, uuid, device_path): + super().__init__(bus, path) + self.path = path + self.uuid = uuid + self.device_path = device_path + + @dbus.service.method('org.freedesktop.DBus.Properties', in_signature='ss', out_signature='v') + def Get(self, interface, prop): + if interface == 'org.bluez.GattService1': + if prop == 'UUID': + return dbus.String(self.uuid) + elif prop == 'Device': + return dbus.ObjectPath(self.device_path) + raise dbus.exceptions.DBusException('org.freedesktop.DBus.Error.InvalidArgs') + + @dbus.service.method('org.freedesktop.DBus.Properties', in_signature='s', out_signature='a{sv}') + def GetAll(self, interface): + if interface == 'org.bluez.GattService1': + return { + 'UUID': dbus.String(self.uuid), + 'Device': dbus.ObjectPath(self.device_path) + } + return {} + + +class GattCharacteristicObject(dbus.service.Object): + def __init__(self, bus, path, uuid, service_path, is_rx=False): + super().__init__(bus, path) + self.path = path + self.uuid = uuid + self.service_path = service_path + self.is_rx = is_rx + self.notifying = False + self.value = [] + self.rx_partner = None + + @dbus.service.method('org.bluez.GattCharacteristic1', in_signature='', out_signature='') + def StartNotify(self): + print(f"[{strftime('%H:%M:%S')}] [Characteristic] StartNotify called on {self.path} (UUID: {self.uuid})") + self.notifying = True + self.PropertiesChanged('org.bluez.GattCharacteristic1', {'Notifying': dbus.Boolean(True)}, []) + + @dbus.service.method('org.bluez.GattCharacteristic1', in_signature='', out_signature='') + def StopNotify(self): + print(f"[{strftime('%H:%M:%S')}] [Characteristic] StopNotify called on {self.path} (UUID: {self.uuid})") + self.notifying = False + self.PropertiesChanged('org.bluez.GattCharacteristic1', {'Notifying': dbus.Boolean(False)}, []) + + @dbus.service.method('org.bluez.GattCharacteristic1', in_signature='aya{sv}', out_signature='') + def WriteValue(self, value, options): + data = [int(b) for b in value] + print(f"[{strftime('%H:%M:%S')}] [Characteristic] WriteValue received {len(data)} bytes: {data}") + + # If this is the TX characteristic and we have a paired RX partner, echo it back + if self.rx_partner and self.rx_partner.notifying: + def echo(): + sleep(0.05) + print(f"[{strftime('%H:%M:%S')}] [Characteristic] Echoing bytes back to RX path {self.rx_partner.path}") + self.rx_partner.value = value + self.rx_partner.PropertiesChanged('org.bluez.GattCharacteristic1', { + 'Value': dbus.Array(value, signature='y') + }, []) + threading.Thread(target=echo, daemon=True).start() + + @dbus.service.method('org.freedesktop.DBus.Properties', in_signature='ss', out_signature='v') + def Get(self, interface, prop): + if interface == 'org.bluez.GattCharacteristic1': + if prop == 'UUID': + return dbus.String(self.uuid) + elif prop == 'Service': + return dbus.ObjectPath(self.service_path) + elif prop == 'Value': + return dbus.Array(self.value, signature='y') + elif prop == 'Notifying': + return dbus.Boolean(self.notifying) + raise dbus.exceptions.DBusException('org.freedesktop.DBus.Error.InvalidArgs') + + @dbus.service.method('org.freedesktop.DBus.Properties', in_signature='s', out_signature='a{sv}') + def GetAll(self, interface): + if interface == 'org.bluez.GattCharacteristic1': + return { + 'UUID': dbus.String(self.uuid), + 'Service': dbus.ObjectPath(self.service_path), + 'Value': dbus.Array(self.value, signature='y'), + 'Notifying': dbus.Boolean(self.notifying) + } + return {} + + @dbus.service.signal('org.freedesktop.DBus.Properties', signature='sa{sv}as') + def PropertiesChanged(self, interface, changed, invalidated): + pass + + +class ObjectManager(dbus.service.Object): + def __init__(self, bus, path, objects_to_manage): + super().__init__(bus, path) + self.objects_to_manage = objects_to_manage + + @dbus.service.method('org.freedesktop.DBus.ObjectManager', in_signature='', out_signature='a{oa{sa{sv}}}') + def GetManagedObjects(self): + result = {} + for obj in self.objects_to_manage: + result[obj.path] = {} + if isinstance(obj, DeviceObject): + result[obj.path]['org.bluez.Device1'] = obj.GetAll('org.bluez.Device1') + elif isinstance(obj, GattServiceObject): + result[obj.path]['org.bluez.GattService1'] = obj.GetAll('org.bluez.GattService1') + elif isinstance(obj, GattCharacteristicObject): + result[obj.path]['org.bluez.GattCharacteristic1'] = obj.GetAll('org.bluez.GattCharacteristic1') + return result + + +def main() -> bool: + ''' + Run D-Bus mock server for BlueZ. + + :return: True if all OK, False otherwise. + :exceptions: None. + ''' + parser = argparse.ArgumentParser(description="BlueZ BLE D-Bus Mock Server for restatdesk") + parser.add_argument("--address", default=DEFAULT_MAC, help=f"MAC address to mock (default: {DEFAULT_MAC})") + parser.add_argument("--service", default=DEFAULT_SERVICE_UUID, help=f"GATT Service UUID (default: {DEFAULT_SERVICE_UUID})") + parser.add_argument("--rx", default=DEFAULT_RX_UUID, help=f"RX Characteristic UUID (default: {DEFAULT_RX_UUID})") + parser.add_argument("--tx", default=DEFAULT_TX_UUID, help=f"TX Characteristic UUID (default: {DEFAULT_TX_UUID})") + parser.add_argument("--session", action="store_true", help="Use D-Bus Session Bus instead of System Bus") + args = parser.parse_args() + + dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + + if args.session: + print("Connecting to D-Bus Session Bus...") + bus = dbus.SessionBus() + else: + print("Connecting to D-Bus System Bus...") + try: + bus = dbus.SystemBus() + except dbus.exceptions.DBusException as e: + print(f"Error: Could not connect to System Bus: {e}") + print("Please ensure dbus is running, or run the script as root / with sudo.") + return False + + try: + bus_name = dbus.service.BusName('org.bluez', bus) + except dbus.exceptions.DBusException as e: + print(f"Error: Could not acquire service name 'org.bluez': {e}") + if not args.session: + print("To acquire name on System Bus, you must run this script with 'sudo':") + print(f" sudo python3 {argv[0]}") + return False + + # Standard path naming matching BlueZ adapter hierarchy + dev_path = f"/org/bluez/hci0/dev_{args.address.replace(':', '_')}" + service_path = f"{dev_path}/service0001" + rx_char_path = f"{service_path}/char0002" + tx_char_path = f"{service_path}/char0003" + + print("Initializing mock objects...") + dev_obj = DeviceObject(bus, dev_path, args.address) + srv_obj = GattServiceObject(bus, service_path, args.service, dev_path) + rx_obj = GattCharacteristicObject(bus, rx_char_path, args.rx, service_path, is_rx=True) + tx_obj = GattCharacteristicObject(bus, tx_char_path, args.tx, service_path, is_rx=False) + + # Pair them for loopback echo behavior + tx_obj.rx_partner = rx_obj + + objects = [dev_obj, srv_obj, rx_obj, tx_obj] + obj_manager = ObjectManager(bus, '/', objects) + + print(f"\nBLE D-Bus Mock Server is running successfully!") + print(f"==================================================") + print(f"Address: {args.address}") + print(f"Service UUID: {args.service}") + print(f"RX Characteristic: {args.rx} ({rx_char_path})") + print(f"TX Characteristic: {args.tx} ({tx_char_path})") + print(f"==================================================") + print("Press any key to exit...") + + old_settings = tcgetattr(stdin) + try: + setcbreak(stdin.fileno()) + context = GLib.MainContext.default() + + while True: + # Process GLib pending events (needed for dbus callbacks) + context.iteration(False) + + # Check if any key is pressed to exit + if select([stdin], [], [], 0) == ([stdin], [], []): + stdin.read(1) + print("\nExit key pressed.") + break + + sleep(0.01) + + except KeyboardInterrupt: + print("\nInterrupted by user.") + + finally: + tcsetattr(stdin, TCSADRAIN, old_settings) + + return True + + +if __name__ == "__main__": + sys_exit(0 if main() else 1) diff --git a/sw/restatdesk/scripts/ble/run.sh b/sw/restatdesk/scripts/ble/run.sh new file mode 100755 index 0000000..62ab5c8 --- /dev/null +++ b/sw/restatdesk/scripts/ble/run.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# +# @brief Run BlueZ BLE mock server for testing +# @version ver.2.0 +# @date Sat Aug 22 14:06:00 PM CEST 2026 +# @company None, free software to use 2026 +# @author Vladimir Roncevic +# + +USE_SYSTEM=0 +for arg in "$@"; do + if [ "$arg" == "--system" ]; then + USE_SYSTEM=1 + fi +done + +if [ "$USE_SYSTEM" -eq 1 ]; then + # System Bus Mode (Requires root/sudo) + if [ "$EUID" -ne 0 ]; then + echo "Please run as root (using sudo) for System Bus mode:" + echo " sudo $0 --system" + exit 1 + fi + + # Determine if the bluetooth service was originally active + WAS_ACTIVE=0 + if systemctl is-active --quiet bluetooth; then + WAS_ACTIVE=1 + echo "Stopping system bluetooth service..." + systemctl stop bluetooth + fi + + # Always kill any remaining bluetoothd processes to ensure the D-Bus name is freed + if killall -0 bluetoothd 2>/dev/null; then + echo "Killing remaining bluetoothd processes..." + killall -9 bluetoothd 2>/dev/null + fi + + # Always mask to prevent D-Bus activation while the emulator is running + systemctl mask bluetooth + + # Function to clean up and restore bluetooth service on exit + cleanup() { + echo "" + echo "Unmasking bluetooth service..." + systemctl unmask bluetooth + if [ "$WAS_ACTIVE" -eq 1 ]; then + echo "Restoring system bluetooth service..." + systemctl start bluetooth + fi + exit 0 + } + + # Trap SIGINT, SIGTERM, and EXIT to run cleanup + trap cleanup INT TERM EXIT + + # Run the python BLE mock server on System Bus + python3 -u run-ble.py --address "00:11:22:33:44:55" +else + # Session Bus Mode (Default, No sudo needed!) + echo "Running BLE Mock Server on Session Bus (Recommended for testing)..." + python3 -u run-ble.py --session --address "00:11:22:33:44:55" +fi diff --git a/sw/restatdesk/scripts/checking_fw/check_fw.py b/sw/restatdesk/scripts/checking_fw/check_fw.py new file mode 100755 index 0000000..4055ffc --- /dev/null +++ b/sw/restatdesk/scripts/checking_fw/check_fw.py @@ -0,0 +1,109 @@ +# -*- coding: UTF-8 -*- + +''' +Module + check_fw.py +Copyright + Copyright (C) 2026 Vladimir Roncevic + restat is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + restat 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 General Public License for more details. + You should have received a copy of the GNU General Public License along + with this program. If not, see . +Info + A simple script for testing firmware on restat device. +''' + +from __future__ import annotations + +from serial import Serial +from sys import exit as sys_exit +from time import sleep + +__author__ = 'Vladimir Roncevic' +__copyright__ = '(C) 2026, https://vroncevic.github.io/restat' +__credits__ = ['Vladimir Roncevic', 'Python Software Foundation'] +__license__ = 'https://github.com/vroncevic/restat/blob/dev/LICENSE' +__version__ = '1.0.0' +__maintainer__ = 'Vladimir Roncevic' +__email__ = 'elektron.ronca@gmail.com' +__status__ = 'Updated' + + +DEVICE = '/dev/ttyACM0' +BAUD = 115200 + +def test_command(ser, cmd_str, expected_part): + full_cmd = f"<{cmd_str}>".encode('utf-8') + print(f" Sending: {cmd_str}") + ser.write(full_cmd) + + sleep(0.15) + waiting = ser.in_waiting + if waiting > 0: + raw_resp = ser.read(waiting) + resp_str = raw_resp.decode('utf-8', errors='replace').strip() + print(f" Received: {resp_str}") + if expected_part in resp_str: + print(" [OK] Response matched.") + return True + else: + print(f" [ERROR] Response did not contain expected: '{expected_part}'") + return False + else: + print(" [ERROR] No response received!") + return False + +def main() -> bool: + try: + serial_port = Serial(DEVICE, BAUD, timeout=1.0) + serial_port.reset_input_buffer() + print(f"Successfully connected to {DEVICE}") + except Exception as e: + print(f"Failed to open {DEVICE}: {e}") + print("Make sure the restat hardware is connected and desktop application is closed.") + return False + + print("\n--- Starting firmware test for all channels and modes ---") + + for ch in range(1, 9): + print(f"\n================ TESTING CHANNEL {ch} ================") + + # 1. Toggle Mode Test + print("\n[Mode 1: Toggle]") + test_command(serial_port, f"rs#ch#{ch}#on#end", f"channel {ch} on") + sleep(0.2) + test_command(serial_port, f"rs#ch#{ch}#off#end", f"channel {ch} off") + + # 2. Timer Mode Test + print("\n[Mode 2: Timer]") + test_command(serial_port, f"rs#ch#{ch}#tmr#5#end", f"timer started") + sleep(0.2) + test_command(serial_port, f"rs#ch#{ch}#off#end", f"channel {ch} off") + + # 3. Pulse Mode Test + print("\n[Mode 3: Pulse]") + test_command(serial_port, f"rs#ch#{ch}#pulse#2000#end", f"pulse started") + sleep(0.2) + # Turn off mid-pulse + test_command(serial_port, f"rs#ch#{ch}#off#end", f"channel {ch} off") + + # 4. Blink Mode Test + print("\n[Mode 4: Blink]") + test_command(serial_port, f"rs#ch#{ch}#blink#500#500#5#end", f"blink started") + sleep(0.2) + # Turn off mid-blink + test_command(serial_port, f"rs#ch#{ch}#off#end", f"channel {ch} off") + + serial_port.close() + print("\nTest completed.") + return True + + +if __name__ == '__main__': + sys_exit(0 if main() else 1) diff --git a/sw/restatdesk/scripts/deb/create_deb.py b/sw/restatdesk/scripts/deb/create_deb.py new file mode 100755 index 0000000..700b687 --- /dev/null +++ b/sw/restatdesk/scripts/deb/create_deb.py @@ -0,0 +1,240 @@ +# -*- coding: UTF-8 -*- + +''' +Module + create_deb.py +Copyright + Copyright (C) 2026 Vladimir Roncevic + restat is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + restat 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 General Public License for more details. + You should have received a copy of the GNU General Public License along + with this program. If not, see . +Info + A Python script for creating a Debian installation package (.deb) for restatdesk. +''' + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import sys +from typing import Final + +__author__: str = 'Vladimir Roncevic' +__copyright__: str = '(C) 2026, https://vroncevic.github.io/restat' +__credits__: list[str] = ['Vladimir Roncevic', 'Python Software Foundation'] +__license__: str = 'https://github.com/vroncevic/restat/blob/dev/LICENSE' +__version__: str = '1.0.0' +__maintainer__: str = 'Vladimir Roncevic' +__email__: str = 'elektron.ronca@gmail.com' +__status__: str = 'Updated' + +# Resolve paths dynamically relative to script location +SCRIPT_DIR: Final[str] = os.path.dirname(os.path.abspath(__file__)) +SW_DIR: Final[str] = os.path.abspath(os.path.join(SCRIPT_DIR, '..', '..')) +REPO_ROOT: Final[str] = os.path.abspath(os.path.join(SW_DIR, '..', '..')) + +BUILD_DIR: Final[str] = os.path.join(SW_DIR, 'build') +MAKEFILE_PATH: Final[str] = os.path.join(BUILD_DIR, 'Makefile') +BINARY_PATH: Final[str] = os.path.join(BUILD_DIR, 'restatdesk') +LOGO_PATH: Final[str] = os.path.join(REPO_ROOT, 'docs', 'restat_logo.png') +DEB_DIST_DIR: Final[str] = os.path.join(BUILD_DIR, 'deb_dist') + + +def get_version(makefile_path: str) -> str: + """ + Extract the version number from the Makefile. + + :param makefile_path: Absolute path to the Makefile. + :return: Version string, or '1.0.0' if not found or readable. + """ + try: + with open(makefile_path, 'r', encoding='utf-8') as f: + for line in f: + match = re.match(r'^\s*#\s*@version\s+(\S+)', line) + if match: + return match.group(1) + except OSError as e: + print(f"Warning: Could not read version from Makefile: {e}") + return '1.0.0' + + +def get_architecture() -> str: + """ + Query the package architecture of the host system. + + :return: Architecture string (e.g., 'amd64', 'arm64'). + """ + try: + result = subprocess.run( + ['dpkg', '--print-architecture'], + capture_output=True, + text=True, + check=True + ) + return result.stdout.strip() + except (subprocess.SubprocessError, FileNotFoundError): + print("Warning: dpkg not found or failed to run. Defaulting to 'amd64'.") + return 'amd64' + + +def create_control_file( + dest_path: str, + version: str, + arch: str +) -> None: + """ + Generate the DEBIAN/control file. + + :param dest_path: Absolute path to write the control file to. + :param version: Package version. + :param arch: Package architecture. + """ + content = f"""Package: restatdesk +Version: {version} +Section: utils +Priority: optional +Architecture: {arch} +Maintainer: Vladimir Roncevic +Depends: libgtkmm-4.0-1 | libgtkmm-4.0-1t64, libc6, libgcc-s1, libstdc++6 +Description: Desktop GUI application for restat hardware controller + A desktop GUI application built in C++ using gtkmm for orchestrating + and controlling restat hardware controllers (relays, LED, buzzer, etc.) + over Serial, TCP, and BLE interfaces. +""" + with open(dest_path, 'w', encoding='utf-8') as f: + f.write(content) + + +def create_desktop_entry(dest_path: str) -> None: + """ + Generate the desktop application launcher entry. + + :param dest_path: Absolute path to write the desktop file to. + """ + content = """[Desktop Entry] +Version=1.0 +Type=Application +Name=restat Desk +Comment=Desktop GUI for restat hardware controller +Exec=restatdesk +Icon=restatdesk +Terminal=false +Categories=Utility;Development; +""" + with open(dest_path, 'w', encoding='utf-8') as f: + f.write(content) + + +def main() -> int: + """ + Main entry point for creating the .deb installation package. + + :return: Exit status code (0 for success, 1 for failure). + """ + print("Starting Debian package creation for restatdesk...") + + # 1. Validation checks + if not os.path.exists(BINARY_PATH): + print(f"Error: Executable not found at '{BINARY_PATH}'.") + print("Please build the application first by running 'make release' or 'make' in sw/restatdesk/build/") + return 1 + + if not os.path.exists(LOGO_PATH): + print(f"Warning: Logo not found at '{LOGO_PATH}'. Package will be created without an application icon.") + + if not shutil.which('dpkg-deb'): + print("Error: 'dpkg-deb' utility is not installed. Debian packaging is not supported on this host.") + return 1 + + # 2. Package parameters + version = get_version(MAKEFILE_PATH) + arch = get_architecture() + package_name = f"restatdesk_{version}_{arch}" + tmp_pkg_dir = os.path.join(DEB_DIST_DIR, package_name) + + print(f"Target package: {package_name}.deb") + print(f"Version: {version}") + print(f"Architecture: {arch}") + + # 3. Create clean temporary directory structure + if os.path.exists(tmp_pkg_dir): + shutil.rmtree(tmp_pkg_dir) + + debian_dir = os.path.join(tmp_pkg_dir, "DEBIAN") + bin_dir = os.path.join(tmp_pkg_dir, "usr", "bin") + apps_dir = os.path.join(tmp_pkg_dir, "usr", "share", "applications") + pixmaps_dir = os.path.join(tmp_pkg_dir, "usr", "share", "pixmaps") + + os.makedirs(debian_dir, exist_ok=True) + os.makedirs(bin_dir, exist_ok=True) + os.makedirs(apps_dir, exist_ok=True) + os.makedirs(pixmaps_dir, exist_ok=True) + + # 4. Copy and process binary + pkg_binary_path = os.path.join(bin_dir, "restatdesk") + print(f"Copying binary to {pkg_binary_path}...") + shutil.copy2(BINARY_PATH, pkg_binary_path) + + # Strip binary to remove debugging symbols + if shutil.which('strip'): + print("Stripping debug symbols from packaged binary...") + try: + subprocess.run(['strip', pkg_binary_path], check=True) + except subprocess.SubprocessError as e: + print(f"Warning: Failed to strip binary: {e}") + else: + print("Warning: 'strip' utility not found. Packaging unstripped binary.") + + # Set binary permission to 755 (executable) + os.chmod(pkg_binary_path, 0o755) + + # 5. Copy logo/icon + if os.path.exists(LOGO_PATH): + pkg_icon_path = os.path.join(pixmaps_dir, "restatdesk.png") + print(f"Copying application icon to {pkg_icon_path}...") + shutil.copy2(LOGO_PATH, pkg_icon_path) + os.chmod(pkg_icon_path, 0o644) + + # 6. Generate control file and desktop entry + print("Generating DEBIAN/control file...") + create_control_file(os.path.join(debian_dir, "control"), version, arch) + os.chmod(os.path.join(debian_dir, "control"), 0o644) + + print("Generating desktop launcher...") + create_desktop_entry(os.path.join(apps_dir, "restatdesk.desktop")) + os.chmod(os.path.join(apps_dir, "restatdesk.desktop"), 0o644) + + # 7. Run dpkg-deb --build + os.makedirs(DEB_DIST_DIR, exist_ok=True) + deb_output_path = os.path.join(DEB_DIST_DIR, f"{package_name}.deb") + print(f"Building Debian package in {deb_output_path}...") + + try: + subprocess.run( + ['dpkg-deb', '--root-owner-group', '--build', tmp_pkg_dir, deb_output_path], + check=True + ) + print("Debian package built successfully!") + except subprocess.SubprocessError as e: + print(f"Error: dpkg-deb build failed: {e}") + return 1 + finally: + # Cleanup temporary files + print("Cleaning up temporary packaging directory...") + shutil.rmtree(tmp_pkg_dir) + + print(f"Finished. Package is available at: {deb_output_path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/sw/restatdesk/scripts/serial_port/.editorconfig b/sw/restatdesk/scripts/serial_port/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/scripts/serial_port/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/scripts/serial_port/run-serial-port.py b/sw/restatdesk/scripts/serial_port/run-serial-port.py new file mode 100644 index 0000000..361f663 --- /dev/null +++ b/sw/restatdesk/scripts/serial_port/run-serial-port.py @@ -0,0 +1,118 @@ +# -*- coding: UTF-8 -*- + +''' +Module + run-serial-port.py +Copyright + Copyright (C) 2026 Vladimir Roncevic + restat is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + restat 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 General Public License for more details. + You should have received a copy of the GNU General Public License along + with this program. If not, see . +Info + A simple script for demonstrating UART communication. +''' + +from __future__ import annotations + +from serial import Serial +from select import select +from sys import stdin, exit as sys_exit +from termios import tcgetattr, tcsetattr, TCSADRAIN +from tty import setcbreak +from time import sleep, strftime + +__author__ = 'Vladimir Roncevic' +__copyright__ = '(C) 2026, https://vroncevic.github.io/restat' +__credits__ = ['Vladimir Roncevic', 'Python Software Foundation'] +__license__ = 'https://github.com/vroncevic/restat/blob/dev/LICENSE' +__version__ = '1.0.0' +__maintainer__ = 'Vladimir Roncevic' +__email__ = 'elektron.ronca@gmail.com' +__status__ = 'Updated' + + +def main() -> bool: + ''' + Listen on serial port /tmp/ttyV1 for incoming data and print it to the console. + + :return: True if all OK, False otherwise. + :exceptions: None. + ''' + try: + serial_port = Serial('/tmp/ttyV1', 115200, timeout=0.1) + + except OSError as e: + print(f"Error opening serial port: {e}") + return False + + print("Listening on /tmp/ttyV1 (PTY slave)...") + print("Parameters: 115200, 8N1...") + print("Press any key to exit...") + + old_settings = tcgetattr(stdin) + buffer = bytearray() + + try: + setcbreak(stdin.fileno()) + + while True: + if select([stdin], [], [], 0) == ([stdin], [], []): + stdin.read(1) + print("\nExit key pressed.") + break + + waiting = serial_port.in_waiting + + if waiting > 0: + raw_data = serial_port.read(waiting) + buffer.extend(raw_data) + + print(f"[{strftime('%H:%M:%S')}] Received {len(raw_data)} bytes: {raw_data.hex(' ')} ({raw_data})") + + while b"<" in buffer and b">" in buffer: + start = buffer.find(b"<") + end = buffer.find(b">", start) + + if end == -1: + break + + msg = bytes(buffer[start:end + 1]) + del buffer[:end + 1] + + print(f" -> Parsed packet: {msg.decode('utf-8', errors='replace')}") + + if msg == b"": + response = b"" + serial_port.write(response) + print(f" <- Sent ID: {response}") + + elif msg == b"": + response = b"" + serial_port.write(response) + print(f" <- Sent Version: {response}") + + else: + serial_port.write(msg) + + sleep(0.01) + + except KeyboardInterrupt: + print("\nInterrupted by user.") + + finally: + tcsetattr(stdin, TCSADRAIN, old_settings) + + serial_port.close() + + return True + + +if __name__ == "__main__": + sys_exit(0 if main() else 1) diff --git a/sw/restatdesk/scripts/serial_port/run-virtual-port.sh b/sw/restatdesk/scripts/serial_port/run-virtual-port.sh new file mode 100755 index 0000000..266a032 --- /dev/null +++ b/sw/restatdesk/scripts/serial_port/run-virtual-port.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# +# @brief Run socat for virtual serial port +# @version ver.1.0 +# @date Sat Aug 22 10:19:45 AM CEST 2026 +# @company None, free software to use 2026 +# @author Vladimir Roncevic +# + +socat -d -d pty,raw,echo=0,link=/tmp/ttyV0 pty,raw,echo=0,link=/tmp/ttyV1 diff --git a/sw/restatdesk/scripts/static_analysis/.editorconfig b/sw/restatdesk/scripts/static_analysis/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/scripts/static_analysis/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/scripts/static_analysis/run-static-analysis.sh b/sw/restatdesk/scripts/static_analysis/run-static-analysis.sh new file mode 100755 index 0000000..595792b --- /dev/null +++ b/sw/restatdesk/scripts/static_analysis/run-static-analysis.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# +# @brief Run static analysis: build, cppcheck, clang-tidy. +# @version ver.1.0 +# @date Sat May 16 09:42:09 AM CEST 2026 +# @company None, free software to use 2026 +# @author Vladimir Roncevic +# + +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)" +cd "$ROOT_DIR" + +OUT_DIR="${ROOT_DIR}/build/static-analysis" +mkdir -p "$OUT_DIR" + +NPROC=$(nproc || echo 4) +PKGCFG="$(pkg-config --cflags-only-I gtkmm-4.0 libserial 2>/dev/null || true)" + +echo "[1/3] Building project (make -j${NPROC} -C build)" +make -j"${NPROC}" --directory=build + +echo "[2/3] Running cppcheck on ${NPROC} threads" +CPPOUT="$OUT_DIR/cppcheck.txt" + +cppcheck -j"${NPROC}" --enable=all --std=c++23 --inline-suppr \ + -i build -I. $PKGCFG . 2> "$CPPOUT" || true +echo "cppcheck output -> $CPPOUT" + +echo "[3/3] Running clang-tidy-18 in parallel" +CLANGOUT="$OUT_DIR/clang-tidy.txt" +echo "clang-tidy run started at $(date)" > "$CLANGOUT" + +find . -name '*.cc' -not -path "./build/*" -print0 | xargs -0 -n 1 -P "${NPROC}" -I {} \ + clang-tidy-18 {} -checks='-*,cppcoreguidelines-*' -- -std=gnu++23 -I. -I.. $PKGCFG >> "$CLANGOUT" 2>&1 || true + +echo "clang-tidy output -> $CLANGOUT" +echo "Done. Reports saved under $OUT_DIR" \ No newline at end of file diff --git a/sw/restatdesk/scripts/tcp_port/.editorconfig b/sw/restatdesk/scripts/tcp_port/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/scripts/tcp_port/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/scripts/tcp_port/run-tcp-server.py b/sw/restatdesk/scripts/tcp_port/run-tcp-server.py new file mode 100644 index 0000000..d36d240 --- /dev/null +++ b/sw/restatdesk/scripts/tcp_port/run-tcp-server.py @@ -0,0 +1,117 @@ +# -*- coding: UTF-8 -*- + +''' +Module + run-tcp-server.py +Copyright + Copyright (C) 2026 Vladimir Roncevic + restat is free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + restat 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 General Public License for more details. + You should have received a copy of the GNU General Public License along + with this program. If not, see . +Info + A simple script for demonstrating TCP/IP socket server communication. +''' + +from __future__ import annotations + +from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR +from select import select +from sys import stdin, exit as sys_exit +from termios import tcgetattr, tcsetattr, TCSADRAIN +from tty import setcbreak +from time import sleep, strftime + +__author__ = 'Vladimir Roncevic' +__copyright__ = '(C) 2026, https://vroncevic.github.io/restat' +__credits__ = ['Vladimir Roncevic', 'Python Software Foundation'] +__license__ = 'https://github.com/vroncevic/restat/blob/dev/LICENSE' +__version__ = '1.0.0' +__maintainer__ = 'Vladimir Roncevic' +__email__ = 'elektron.ronca@gmail.com' +__status__ = 'Updated' + + +def main() -> bool: + ''' + Listen on TCP port 5000 for incoming data and print it to the console. + + :return: True if all OK, False otherwise. + :exceptions: None. + ''' + HOST = '0.0.0.0' + PORT = 5000 + + try: + server_sock = socket(AF_INET, SOCK_STREAM) + server_sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) + server_sock.bind((HOST, PORT)) + server_sock.listen() + server_sock.setblocking(False) + + except OSError as e: + print(f"Error starting TCP server: {e}") + return False + + print(f"Starting TCP server on {HOST}:{PORT}...") + print("Press any key to exit...") + + old_settings = tcgetattr(stdin) + try: + setcbreak(stdin.fileno()) + + while True: + # Wait for stdin keypress or incoming TCP connection + readable, _, _ = select([stdin, server_sock], [], [], 0.1) + + if stdin in readable: + stdin.read(1) + print("\nExit key pressed.") + break + + if server_sock in readable: + conn, addr = server_sock.accept() + conn.setblocking(False) + print(f"\n[{strftime('%H:%M:%S')}] Client connected from: {addr}") + + with conn: + client_disconnected = False + while not client_disconnected: + # Wait for stdin keypress or client data + r, _, _ = select([stdin, conn], [], [], 0.1) + + if stdin in r: + stdin.read(1) + print("\nExit key pressed.") + return True + + if conn in r: + data = conn.recv(1024) + if not data: + print(f"[{strftime('%H:%M:%S')}] Client closed connection.") + client_disconnected = True + else: + print(f"[{strftime('%H:%M:%S')}] Received {len(data)} bytes:") + print(f" Hex: {data.hex(' ')}") + print(f" Raw: {data.decode('utf-8', errors='replace')}") + + sleep(0.01) + + except KeyboardInterrupt: + print("\nInterrupted by user.") + + finally: + tcsetattr(stdin, TCSADRAIN, old_settings) + server_sock.close() + + return True + + +if __name__ == "__main__": + sys_exit(0 if main() else 1) diff --git a/sw/restatdesk/style.css b/sw/restatdesk/style.css new file mode 100644 index 0000000..2564a20 --- /dev/null +++ b/sw/restatdesk/style.css @@ -0,0 +1,87 @@ +@define-color accent_bg_color #00FF00; +@define-color accent_color #00FF00; +@define-color theme_selected_bg_color #00FF00; +@define-color theme_selected_fg_color black; +@define-color progressbar_progress_color #00FF00; +@define-color progressbar_trough_color #222222; + +textview, textview text, textview.view { + background-color: black; + color: #00FF00; + font-family: monospace; +} + +progressbar { + background: transparent; + background-color: transparent; + background-image: none; + border: none; + box-shadow: none; +} + +progressbar trough, +progressbar .trough, +progressbar.horizontal trough, +progressbar.horizontal .trough { + background: #222222; + background-color: #222222; + background-image: none; + box-shadow: none; + border: 1px solid #444444; +} + +progressbar progress, +progressbar .progress, +progressbar.horizontal progress, +progressbar.horizontal .progress, +progressbar > trough > progress { + background: #00FF00; + background-color: #00FF00; + background-image: none; + box-shadow: none; + border-radius: 2px; +} + +checkbutton > check { + background-color: #222222; + border-color: #555555; + color: transparent; + background-image: none; + box-shadow: none; +} + +checkbutton:checked > check { + background-color: #00FF00; + color: black; + border-color: #00FF00; + background-image: none; + box-shadow: none; +} + +checkbutton:hover > check { + border-color: #00FF00; +} + +togglebutton:checked { + background-color: #00FF00; + color: black; + border-color: #00FF00; + background-image: none; + box-shadow: none; +} + +.led-lamp { + background-color: #222222; + border-radius: 7px; + border: 1px solid #555555; + min-width: 14px; + min-height: 14px; + background-image: none; + box-shadow: none; +} + +.led-lamp.on { + background-color: #00FF00; + box-shadow: 0 0 6px #00FF00; + border-color: #00FF00; +} diff --git a/sw/restatdesk/view/.editorconfig b/sw/restatdesk/view/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/about/.editorconfig b/sw/restatdesk/view/about/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/about/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/about/about.cc b/sw/restatdesk/view/about/about.cc new file mode 100644 index 0000000..bf236a1 --- /dev/null +++ b/sw/restatdesk/view/about/about.cc @@ -0,0 +1,71 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// about.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Application About Dialog Metadata + /// @{ + constexpr std::string_view cProgramName{"restatdesk"}; + constexpr std::string_view cProgramVersion{"1.0.0"}; + constexpr std::string_view cProgramCopyright{ + "Vladimir Roncevic " + }; + constexpr std::string_view cProgramComments{ + "This is restatdesk application." + }; + constexpr std::string_view cProgramLicense{"GPLv3"}; + constexpr std::string_view cProgramWebsite{ + "https://electux.github.io/restat" + }; + constexpr std::string_view cProgramWebsiteLabel{"electux.github.io/restat" + }; + constexpr std::string_view cProgramAuthors{"Vladimir Roncevic"}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace + +using namespace Electux::App::View::About; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief AppAbout constructor. +/// +/// Configures the Gtk::AboutDialog with application-specific information +/// including name, version, copyright, and developer credits. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +AppAbout::AppAbout() { + set_program_name(cProgramName.data()); + set_version(cProgramVersion.data()); + set_copyright(cProgramCopyright.data()); + set_comments(cProgramComments.data()); + set_license(cProgramLicense.data()); + set_website(cProgramWebsite.data()); + set_website_label(cProgramWebsiteLabel.data()); + + // Setup authors list + std::vector list_authors; + list_authors.push_back(cProgramAuthors.data()); + set_authors(list_authors); + + set_hide_on_close(true); +} + +void AppAbout::show() { set_visible(true); } diff --git a/sw/restatdesk/view/about/about.h b/sw/restatdesk/view/about/about.h new file mode 100644 index 0000000..703e6b7 --- /dev/null +++ b/sw/restatdesk/view/about/about.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// about.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::View::About { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class AppAbout + /// @brief About view dialog definition for the restatdesk application. + /// + /// Displays application metadata including version, copyright, license, + /// and contributor information using the standard Gtk::AboutDialog. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class AppAbout : public Gtk::AboutDialog, public IAboutView { + public: + explicit AppAbout(); + virtual ~AppAbout() override = default; + + void show() override; + }; +} // namespace Electux::App::View::About diff --git a/sw/restatdesk/view/about/iabout_view.h b/sw/restatdesk/view/about/iabout_view.h new file mode 100644 index 0000000..e56eb6c --- /dev/null +++ b/sw/restatdesk/view/about/iabout_view.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// iabout_view.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +namespace Electux::App::View::About { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IAboutView + /// @brief Interface defining the contract for the about/credits view. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IAboutView { + public: + virtual ~IAboutView() = default; + + virtual void show() = 0; + }; +} // namespace Electux::App::View::About diff --git a/sw/restatdesk/view/channel/.editorconfig b/sw/restatdesk/view/channel/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/channel/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/channel/channel_widget.cc b/sw/restatdesk/view/channel/channel_widget.cc new file mode 100644 index 0000000..acc382f --- /dev/null +++ b/sw/restatdesk/view/channel/channel_widget.cc @@ -0,0 +1,201 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// channel_widget.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#include +#include + +namespace { + constexpr std::string_view cChannelEnableLabel{"Enable Channel #"}; + constexpr int cBoxSpacing{5}; + constexpr int cWidgetMargin{10}; + constexpr int cTransitionDurationMs{100}; +} // namespace + +using namespace Electux::App::View; + +ChannelWidget::ChannelWidget(size_t index) + : Gtk::Frame(), m_index(index), + m_mainBox(Gtk::Orientation::VERTICAL, cBoxSpacing), + m_headerBox(Gtk::Orientation::HORIZONTAL, cBoxSpacing), + m_enableBtn(std::format("{} {}", cChannelEnableLabel.data(), index + 1)), + m_pageToggle(index), m_pageTimer(index) { + set_margin(cWidgetMargin); + m_mainBox.set_margin(cWidgetMargin); + m_mainBox.set_vexpand(true); + + m_led.set_size_request(14, 14); + m_led.set_valign(Gtk::Align::CENTER); + m_led.set_halign(Gtk::Align::END); + m_led.add_css_class("led-lamp"); + + m_enableBtn.set_hexpand(true); + m_headerBox.append(m_enableBtn); + m_headerBox.append(m_led); + m_mainBox.append(m_headerBox); + + m_enableBtn.signal_toggled().connect( + sigc::mem_fun(*this, &ChannelWidget::onEnableToggled) + ); + + // Dynamically populate mode combo box from descriptors + for (const auto &desc : Model::Channel::cChannelModeDescriptors) { + m_modeCombo.append(desc.displayName.data()); + } + m_modeCombo.set_active(0); + m_mainBox.append(m_modeCombo); + m_modeCombo.signal_changed().connect( + sigc::mem_fun(*this, &ChannelWidget::onModeChanged) + ); + + // Configure stack properties + m_stack.set_transition_type(Gtk::StackTransitionType::CROSSFADE); + m_stack.set_transition_duration(cTransitionDurationMs); + m_stack.set_hhomogeneous(true); + m_stack.set_vhomogeneous(true); + m_stack.set_vexpand(true); + + // Add concrete mode pages to stack using overloaded add(widget, name) + m_stack.add( + m_pageToggle, + std::string( + Model::Channel::toConfigString(Model::Channel::ChannelMode::Toggle) + ) + ); + m_stack.add( + m_pageTimer, + std::string( + Model::Channel::toConfigString(Model::Channel::ChannelMode::Timer) + ) + ); + m_mainBox.append(m_stack); + set_child(m_mainBox); + + // Connect state change signals from child pages + m_pageToggle.signal_changed().connect( + sigc::mem_fun(*this, &ChannelWidget::onChildPageChanged) + ); + m_pageTimer.signal_changed().connect( + sigc::mem_fun(*this, &ChannelWidget::onChildPageChanged) + ); + + + updateSensitivity(); +} + +void ChannelWidget::updateSensitivity() { + bool isEnabled = m_enableBtn.get_active(); + m_modeCombo.set_sensitive(isEnabled); + m_stack.set_sensitive(isEnabled); +} + +void ChannelWidget::updateState(const ChannelState &state) { + m_blockSignals = true; + m_enableBtn.set_active(state.enabled); + + int activeRow = -1; + for (size_t i = 0; i < Model::Channel::cChannelModeDescriptors.size(); + ++i) { + if (Model::Channel::cChannelModeDescriptors.at(i).mode == state.mode) { + activeRow = static_cast(i); + break; + } + } + m_modeCombo.set_active(activeRow >= 0 ? activeRow : 0); + + auto visibleChildName = Model::Channel::toConfigString(state.mode); + if (state.mode != Model::Channel::ChannelMode::Unknown) { + m_stack.set_visible_child(std::string(visibleChildName)); + } else { + m_stack.set_visible_child( + std::string( + Model::Channel::toConfigString( + Model::Channel::ChannelMode::Toggle + ) + ) + ); + } + + m_pageToggle.updateState(state); + m_pageTimer.updateState(state); + + + m_blockSignals = false; + updateSensitivity(); +} + +ChannelState ChannelWidget::getState() const { + ChannelState state; + state.enabled = m_enableBtn.get_active(); + + int activeRow = m_modeCombo.get_active_row_number(); + if (activeRow >= 0 && + activeRow < + static_cast(Model::Channel::cChannelModeDescriptors.size())) { + state.mode = Model::Channel::cChannelModeDescriptors + .at(static_cast(activeRow)) + .mode; + } else { + state.mode = Model::Channel::ChannelMode::Unknown; + } + + m_pageToggle.getState(state); + m_pageTimer.getState(state); + + + return state; +} + +void ChannelWidget::onEnableToggled() { + updateSensitivity(); + if (!m_blockSignals) { + m_signalChanged.emit(); + } +} + +void ChannelWidget::onModeChanged() { + int activeRow = m_modeCombo.get_active_row_number(); + if (activeRow >= 0 && + activeRow < + static_cast(Model::Channel::cChannelModeDescriptors.size())) { + auto mode = Model::Channel::cChannelModeDescriptors + .at(static_cast(activeRow)) + .mode; + auto visibleChildName = Model::Channel::toConfigString(mode); + m_stack.set_visible_child(std::string(visibleChildName)); + } + updateSensitivity(); + + if (!m_blockSignals) { + m_signalChanged.emit(); + } +} + +void ChannelWidget::onChildPageChanged() { + if (!m_blockSignals) { + m_signalChanged.emit(); + } +} + +void ChannelWidget::setLedState(bool on) { + if (on) { + m_led.add_css_class("on"); + } else { + m_led.remove_css_class("on"); + } +} diff --git a/sw/restatdesk/view/channel/channel_widget.h b/sw/restatdesk/view/channel/channel_widget.h new file mode 100644 index 0000000..41e4367 --- /dev/null +++ b/sw/restatdesk/view/channel/channel_widget.h @@ -0,0 +1,79 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// channel_widget.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::View { + using ChannelState = Electux::App::Model::Channel::ChannelState; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ChannelWidget + /// @brief A self-contained UI component managing a single communication channel's controls. + /// + /// This widget encapsulates all UI elements for a single channel, leveraging Gtk::Stack + /// to switch between mode-specific control panels dynamically. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ChannelWidget : public Gtk::Frame { + public: + explicit ChannelWidget(size_t index); + virtual ~ChannelWidget() override = default; + + ChannelWidget(const ChannelWidget &) = delete; + ChannelWidget &operator=(const ChannelWidget &) = delete; + ChannelWidget(ChannelWidget &&) = delete; + ChannelWidget &operator=(ChannelWidget &&) = delete; + + void updateState(const ChannelState &state); + ChannelState getState() const; + void setLedState(bool on); + + sigc::signal& signal_changed() { return m_signalChanged; } + + private: + void updateSensitivity(); + void onEnableToggled(); + void onModeChanged(); + void onChildPageChanged(); + + size_t m_index; + bool m_blockSignals{false}; + + Gtk::Box m_mainBox; + Gtk::Box m_headerBox; + Gtk::Box m_led; + Gtk::CheckButton m_enableBtn; + Gtk::ComboBoxText m_modeCombo; + + Gtk::Stack m_stack; + ToggleModePage m_pageToggle; + TimerModePage m_pageTimer; + + sigc::signal m_signalChanged; + }; +} // namespace Electux::App::View diff --git a/sw/restatdesk/view/channel/page/.editorconfig b/sw/restatdesk/view/channel/page/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/channel/page/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/channel/page/mode_page.h b/sw/restatdesk/view/channel/page/mode_page.h new file mode 100644 index 0000000..005512e --- /dev/null +++ b/sw/restatdesk/view/channel/page/mode_page.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// mode_page.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::View { + using ChannelState = Electux::App::Model::Channel::ChannelState; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ModePage + /// @brief Pure interface for mode-specific pages inside ChannelWidget's stack. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ModePage { + public: + virtual ~ModePage() = default; + + virtual void updateState(const ChannelState &state) = 0; + virtual void getState(ChannelState &state) const = 0; + virtual sigc::signal signal_changed() = 0; + }; +} // namespace Electux::App::View diff --git a/sw/restatdesk/view/channel/page/mode_page_timer.cc b/sw/restatdesk/view/channel/page/mode_page_timer.cc new file mode 100644 index 0000000..666c7e2 --- /dev/null +++ b/sw/restatdesk/view/channel/page/mode_page_timer.cc @@ -0,0 +1,93 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// mode_page_timer.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#include +#include + +namespace { + constexpr std::string_view cChannelTimerLabel{"Use timer #"}; + constexpr std::string_view cChannelTimerBtnStart{"Activate"}; + constexpr std::string_view cChannelTimerDesc{"Keep the channel active for a time."}; + constexpr int cBoxSpacing{5}; + constexpr int cMarginTopBottom{15}; + constexpr double cTimerMinSec{0.0}; + constexpr double cTimerMaxSec{3600.0}; + constexpr double cTimerStep{0.1}; + constexpr double cTimerPage{1.0}; +} // namespace + +using namespace Electux::App::View; + +TimerModePage::TimerModePage(size_t index) + : Gtk::Box(Gtk::Orientation::VERTICAL, cBoxSpacing), + m_index(index) { + m_timerLabel.set_label(std::format("{} {}", cChannelTimerLabel.data(), index)); + m_descLabel.set_label(cChannelTimerDesc.data()); + + append(m_timerLabel); + + m_timerSpin.set_range(cTimerMinSec, cTimerMaxSec); + m_timerSpin.set_increments(cTimerStep, cTimerPage); + m_timerSpin.set_digits(1); + append(m_timerSpin); + + m_descLabel.set_wrap(true); + m_descLabel.set_justify(Gtk::Justification::CENTER); + m_descLabel.set_margin_top(cMarginTopBottom); + m_descLabel.set_margin_bottom(cMarginTopBottom); + m_descLabel.set_vexpand(true); + m_descLabel.set_valign(Gtk::Align::END); + append(m_descLabel); + + m_timerToggleBtn.set_label(cChannelTimerBtnStart.data()); + append(m_timerToggleBtn); + + m_progressBar.set_fraction(0.0); + append(m_progressBar); + + m_timerSpin.signal_value_changed().connect( + sigc::mem_fun(*this, &TimerModePage::onTimerValueChanged) + ); + m_timerToggleBtn.signal_clicked().connect( + sigc::mem_fun(*this, &TimerModePage::onTimerToggleClicked) + ); +} + +void TimerModePage::updateState(const ChannelState &state) { + m_timerSpin.set_value(static_cast(state.timer) / 1000.0); + m_timerToggleBtn.set_active(state.timerEnabled); + m_timerToggleBtn.set_label(state.timerEnabled ? "Deactive" : "Activate"); + m_progressBar.set_fraction(state.timerEnabled ? 1.0 : 0.0); +} + +void TimerModePage::getState(ChannelState &state) const { + state.timer = static_cast(m_timerSpin.get_value() * 1000.0); + state.timerEnabled = m_timerToggleBtn.get_active(); +} + +void TimerModePage::onTimerValueChanged() { + m_signalChanged.emit(); +} + +void TimerModePage::onTimerToggleClicked() { + bool active = m_timerToggleBtn.get_active(); + m_timerToggleBtn.set_label(active ? "Deactive" : "Activate"); + m_progressBar.set_fraction(active ? 1.0 : 0.0); + m_signalChanged.emit(); +} diff --git a/sw/restatdesk/view/channel/page/mode_page_timer.h b/sw/restatdesk/view/channel/page/mode_page_timer.h new file mode 100644 index 0000000..94e5d42 --- /dev/null +++ b/sw/restatdesk/view/channel/page/mode_page_timer.h @@ -0,0 +1,63 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// mode_page_timer.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::View { + using ChannelState = Electux::App::Model::Channel::ChannelState; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class TimerModePage + /// @brief ModePage implementation for Timer Mode, inheriting from Gtk::Box. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class TimerModePage : public Gtk::Box { + public: + explicit TimerModePage(size_t index); + virtual ~TimerModePage() override = default; + + TimerModePage(const TimerModePage &) = delete; + TimerModePage &operator=(const TimerModePage &) = delete; + TimerModePage(TimerModePage &&) = delete; + TimerModePage &operator=(TimerModePage &&) = delete; + + void updateState(const ChannelState &state); + void getState(ChannelState &state) const; + sigc::signal& signal_changed() { return m_signalChanged; } + + private: + void onTimerValueChanged(); + void onTimerToggleClicked(); + + size_t m_index; + Gtk::Label m_timerLabel; + Gtk::SpinButton m_timerSpin; + Gtk::ToggleButton m_timerToggleBtn; + Gtk::ProgressBar m_progressBar; + Gtk::Label m_descLabel; + sigc::signal m_signalChanged; + }; +} // namespace Electux::App::View diff --git a/sw/restatdesk/view/channel/page/mode_page_toggle.cc b/sw/restatdesk/view/channel/page/mode_page_toggle.cc new file mode 100644 index 0000000..58072a2 --- /dev/null +++ b/sw/restatdesk/view/channel/page/mode_page_toggle.cc @@ -0,0 +1,71 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// mode_page_toggle.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#include +#include + +namespace { + constexpr std::string_view cChannelToggleBtnActivate{"Activate"}; + constexpr std::string_view cChannelToggleDesc{"Manually control the channel state."}; + constexpr int cBoxSpacing{5}; + constexpr int cMarginTopBottom{15}; +} // namespace + +using namespace Electux::App::View; + +ToggleModePage::ToggleModePage(size_t index) + : Gtk::Box(Gtk::Orientation::VERTICAL, cBoxSpacing), + m_index(index) { + m_descLabel.set_label(cChannelToggleDesc.data()); + + m_descLabel.set_wrap(true); + m_descLabel.set_justify(Gtk::Justification::CENTER); + m_descLabel.set_margin_top(cMarginTopBottom); + m_descLabel.set_margin_bottom(cMarginTopBottom); + m_descLabel.set_vexpand(true); + m_descLabel.set_valign(Gtk::Align::END); + append(m_descLabel); + + m_toggleBtn.set_label(cChannelToggleBtnActivate.data()); + append(m_toggleBtn); + + m_progressBar.set_fraction(0.0); + append(m_progressBar); + + m_toggleBtn.signal_clicked().connect( + sigc::mem_fun(*this, &ToggleModePage::onToggleClicked) + ); +} + +void ToggleModePage::updateState(const ChannelState &state) { + m_toggleBtn.set_active(state.toggle); + m_toggleBtn.set_label(state.toggle ? "Deactive" : "Activate"); + m_progressBar.set_fraction(state.toggle ? 1.0 : 0.0); +} + +void ToggleModePage::getState(ChannelState &state) const { + state.toggle = m_toggleBtn.get_active(); +} + +void ToggleModePage::onToggleClicked() { + bool active = m_toggleBtn.get_active(); + m_toggleBtn.set_label(active ? "Deactive" : "Activate"); + m_progressBar.set_fraction(active ? 1.0 : 0.0); + m_signalChanged.emit(); +} diff --git a/sw/restatdesk/view/channel/page/mode_page_toggle.h b/sw/restatdesk/view/channel/page/mode_page_toggle.h new file mode 100644 index 0000000..e63ceff --- /dev/null +++ b/sw/restatdesk/view/channel/page/mode_page_toggle.h @@ -0,0 +1,59 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// mode_page_toggle.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Electux::App::View { + using ChannelState = Electux::App::Model::Channel::ChannelState; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ToggleModePage + /// @brief ModePage implementation for Toggle Mode, inheriting from Gtk::Box. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ToggleModePage : public Gtk::Box { + public: + explicit ToggleModePage(size_t index); + virtual ~ToggleModePage() override = default; + + ToggleModePage(const ToggleModePage &) = delete; + ToggleModePage &operator=(const ToggleModePage &) = delete; + ToggleModePage(ToggleModePage &&) = delete; + ToggleModePage &operator=(ToggleModePage &&) = delete; + + void updateState(const ChannelState &state); + void getState(ChannelState &state) const; + sigc::signal& signal_changed() { return m_signalChanged; } + + private: + void onToggleClicked(); + + size_t m_index; + Gtk::ToggleButton m_toggleBtn; + Gtk::Label m_descLabel; + Gtk::ProgressBar m_progressBar; + sigc::signal m_signalChanged; + }; +} // namespace Electux::App::View diff --git a/sw/restatdesk/view/help/.editorconfig b/sw/restatdesk/view/help/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/help/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/help/help.cc b/sw/restatdesk/view/help/help.cc new file mode 100644 index 0000000..72eb788 --- /dev/null +++ b/sw/restatdesk/view/help/help.cc @@ -0,0 +1,48 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// help.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include + +namespace { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Application Help Window Widgets Parameters + /// @{ + constexpr std::string_view cHelpTitle{"restatdesk"}; + constexpr int cHelpWidth{600}; + constexpr int cHelpHeight{400}; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// +} // namespace + +using namespace Electux::App::View::Help; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief AppHelp constructor. +/// +/// Initializes the help window with predefined title and dimensions. +/// The window is set to be non-resizable and remains hidden when closed. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +AppHelp::AppHelp() { + set_title(cHelpTitle.data()); + set_default_size(cHelpWidth, cHelpHeight); + set_resizable(false); + set_hide_on_close(true); +} + +void AppHelp::show() { set_visible(true); } diff --git a/sw/restatdesk/view/help/help.h b/sw/restatdesk/view/help/help.h new file mode 100644 index 0000000..945a2c0 --- /dev/null +++ b/sw/restatdesk/view/help/help.h @@ -0,0 +1,40 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// help.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::View::Help { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class AppHelp + /// @brief Help view window definition for application documentation. + /// + /// This window provides users with access to local documentation or + /// help resources related to restatdesk functionality. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class AppHelp : public Gtk::Window, public IHelpView { + public: + explicit AppHelp(); + virtual ~AppHelp() override = default; + + void show() override; + }; +} // namespace Electux::App::View::Help diff --git a/sw/restatdesk/view/help/ihelp_view.h b/sw/restatdesk/view/help/ihelp_view.h new file mode 100644 index 0000000..69f6ba4 --- /dev/null +++ b/sw/restatdesk/view/help/ihelp_view.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ihelp_view.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +namespace Electux::App::View::Help { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IHelpView + /// @brief Interface defining the contract for the help documentation view. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IHelpView { + public: + virtual ~IHelpView() = default; + + virtual void show() = 0; + }; +} // namespace Electux::App::View::Help diff --git a/sw/restatdesk/view/home.cc b/sw/restatdesk/view/home.cc new file mode 100644 index 0000000..6d79124 --- /dev/null +++ b/sw/restatdesk/view/home.cc @@ -0,0 +1,336 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// home.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + constexpr std::string_view cHomeTitle{"restatdesk"}; + constexpr int cHomeWidth{600}; + constexpr int cHomeHeight{570}; + constexpr int cWidgetMargin{10}; + constexpr int cScrolledWindowHeight{250}; + + std::string formatPlanString(const std::string &data) { + size_t planPos = data.find("rs#all#plan#"); + if (planPos == std::string::npos) { + return data; + } + + std::string prefix = data.substr(0, planPos); + std::string plan = data.substr(planPos); + + if (prefix == "loading persisted plan: ") { + prefix = "Loading persisted plan:\n"; + } else if (prefix.empty()) { + prefix = "Applying plan:\n"; + } + + std::string formatted = prefix; + + std::vector tokens; + std::stringstream ss(plan); + std::string token; + while (std::getline(ss, token, '#')) { + if (!token.empty()) { + tokens.push_back(token); + } + } + + for (size_t i = 0; i < tokens.size(); ++i) { + if (tokens[i] == "ch" && i + 2 < tokens.size()) { + std::string chNum = tokens[i+1]; + std::string mode = tokens[i+2]; + formatted += std::format(" * Channel {}: ", chNum); + if (mode == "on") { + formatted += "ON\n"; + i += 2; + } else if (mode == "off") { + formatted += "OFF\n"; + i += 2; + } else if (mode == "tmron" && i + 3 < tokens.size()) { + std::string ms = tokens[i+3]; + formatted += std::format("Timer ON ({}ms)\n", ms); + i += 3; + } else if (mode == "tmroff" && i + 3 < tokens.size()) { + std::string ms = tokens[i+3]; + formatted += std::format("Timer OFF ({}ms)\n", ms); + i += 3; + } else { + formatted += mode + "\n"; + i += 2; + } + } + } + if (!formatted.empty() && formatted.back() == '\n') { + formatted.pop_back(); + } + return formatted; + } +} // namespace + +using namespace Electux::App::View; +using namespace Electux::App::Model; +using namespace Electux::App::Model::Channel; + +AppHome::AppHome() : m_btnExecutePlan("Execute Plan") { + set_title(cHomeTitle.data()); + set_default_size(cHomeWidth, cHomeHeight); + set_resizable(false); + set_show_menubar(true); + m_boxRoot.set_orientation(Gtk::Orientation::VERTICAL); + m_boxChannels.set_orientation(Gtk::Orientation::HORIZONTAL); + m_textView.set_editable(false); + m_textView.set_cursor_visible(false); + m_textView.set_wrap_mode(Gtk::WrapMode::CHAR); + m_textView.set_monospace(true); + m_textView.set_left_margin(cWidgetMargin); + m_textView.set_right_margin(cWidgetMargin); + m_textView.set_top_margin(cWidgetMargin); + m_textView.set_bottom_margin(cWidgetMargin); + + auto css_provider = Gtk::CssProvider::create(); + css_provider->load_from_resource("/electux/restatdesk/style.css"); + Gtk::StyleContext::add_provider_for_display( + Gdk::Display::get_default(), css_provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION + ); + + m_scrolled_window.set_child(m_textView); + m_scrolled_window.set_vexpand(true); + m_scrolled_window.set_hexpand(true); + m_scrolled_window.set_size_request(-1, cScrolledWindowHeight); + m_scrolled_window.set_margin_start(cWidgetMargin); + m_scrolled_window.set_margin_end(cWidgetMargin); + m_scrolled_window.set_margin_bottom(cWidgetMargin); + + m_dispatcher.connect( + sigc::mem_fun(*this, &AppHome::onDataReceivedDispatcher) + ); + + m_boxActions.set_orientation(Gtk::Orientation::HORIZONTAL); + m_boxActions.set_margin(cWidgetMargin); + m_btnExecutePlan.set_halign(Gtk::Align::CENTER); + m_btnExecutePlan.set_hexpand(true); + m_boxActions.append(m_btnExecutePlan); + + m_btnExecutePlan.signal_clicked().connect([this]() { + m_signalExecutePlan.emit(); + }); + + m_boxRoot.append(m_boxChannels); + m_boxRoot.append(m_boxActions); + m_boxRoot.append(m_scrolled_window); + set_child(m_boxRoot); + + for (ssize_t i = 0; i < cNumOfChannels; i++) { + auto widget = std::make_unique(static_cast(i)); + + widget->signal_changed().connect( + sigc::bind( + sigc::mem_fun(*this, &AppHome::onChannelChanged), + static_cast(i) + ) + ); + + m_boxChannels.append(*widget); + m_channelWidgets.push_back(std::move(widget)); + } +} + +SigSettings AppHome::controlChanged() { return m_controlSignal; } + +void AppHome::setControlSetup(const SettingsSetup &setup) { m_setup = setup; } + +void AppHome::updateUiData() { + const auto &config = *m_setup.m_config; + + for (ssize_t i = 0; i < cNumOfChannels; i++) { + m_channelWidgets[static_cast(i)]->updateState( + config.getChannelState(static_cast(i)) + ); + } +} + +void AppHome::getUiData() { + auto &config = *m_setup.m_config; + + for (ssize_t i = 0; i < cNumOfChannels; i++) { + config.setChannelState( + static_cast(i), + m_channelWidgets[static_cast(i)]->getState() + ); + } + + m_controlSignal.emit(m_setup); +} + +void AppHome::onChannelChanged(size_t index) { + auto &config = *m_setup.m_config; + config.setChannelState(index, m_channelWidgets[index]->getState()); + m_controlSignal.emit(m_setup); +} + +void AppHome::show() { set_visible(true); } + +void AppHome::hide() { set_visible(false); } + +void AppHome::connect_close_request(const sigc::slot &slot) { + signal_close_request().connect(slot, false); +} + +Gtk::Window &AppHome::getGtkWindow() { return *this; } + +void AppHome::postData(const std::string &data) { + std::lock_guard lock(m_mutex); + m_incomingDataQueue.push(data); + m_dispatcher.emit(); +} + +void AppHome::onDataReceivedDispatcher() { + std::lock_guard lock(m_mutex); + auto buffer = m_textView.get_buffer(); + + while (!m_incomingDataQueue.empty()) { + std::string data = m_incomingDataQueue.front(); + + updateLedsFromMessage(data); + + buffer->insert(buffer->end(), formatPlanString(data)); + buffer->insert(buffer->end(), "\n"); + + m_incomingDataQueue.pop(); + } +} + +void AppHome::updateLedsFromMessage(const std::string &msg) { + // 0. Check for "rs#all#plan#" + size_t planPos = msg.find("rs#all#plan#"); + if (planPos != std::string::npos) { + std::string plan = msg.substr(planPos); + std::vector tokens; + std::stringstream ss(plan); + std::string token; + while (std::getline(ss, token, '#')) { + if (!token.empty()) { + tokens.push_back(token); + } + } + for (size_t i = 0; i < tokens.size(); ++i) { + if (tokens[i] == "ch" && i + 2 < tokens.size()) { + int chNum = std::stoi(tokens[i+1]); + std::string mode = tokens[i+2]; + if (chNum >= 1 && chNum <= 8) { + bool is_on = false; + if (mode == "on" || mode == "tmron") { + is_on = true; + } else if (mode == "off" || mode == "tmroff") { + is_on = false; + } + m_channelWidgets[static_cast(chNum - 1)]->setLedState(is_on); + } + i += 2; + if (mode == "tmron" || mode == "tmroff") { + i++; // skip duration + } + } + } + return; + } + + // 0.5. Check for "all channels on" or "all channels off" + if (msg.find("all channels on") != std::string::npos) { + for (size_t i = 0; i < 8; ++i) { + m_channelWidgets[i]->setLedState(true); + } + return; + } + if (msg.find("all channels off") != std::string::npos) { + for (size_t i = 0; i < 8; ++i) { + m_channelWidgets[i]->setLedState(false); + } + return; + } + + // 0.6. Check for "channels mask applied: 10101010" + size_t maskPos = msg.find("channels mask applied: "); + if (maskPos != std::string::npos) { + std::string mask = msg.substr(maskPos + 23, 8); + for (size_t i = 0; i < 8 && i < mask.length(); ++i) { + m_channelWidgets[i]->setLedState(mask[i] == '1'); + } + return; + } + + // 1. Check for "channels: 1:OFF 2:ON ..." + size_t channelsPos = msg.find("channels: "); + if (channelsPos != std::string::npos) { + std::string listStr = msg.substr(channelsPos + 10); + std::stringstream ss(listStr); + std::string item; + while (ss >> item) { + size_t colon = item.find(':'); + if (colon != std::string::npos) { + int chNum = std::stoi(item.substr(0, colon)); + std::string state = item.substr(colon + 1); + if (chNum >= 1 && chNum <= 8) { + m_channelWidgets[static_cast(chNum - 1)]->setLedState(state == "ON"); + } + } + } + return; + } + + // 2. Check for "channel X on" or "channel X off" + size_t channelPos = msg.find("channel "); + if (channelPos != std::string::npos) { + std::string sub = msg.substr(channelPos + 8); + std::stringstream ss(sub); + int chNum = 0; + std::string state; + if (ss >> chNum >> state) { + if (chNum >= 1 && chNum <= 8) { + m_channelWidgets[static_cast(chNum - 1)]->setLedState(state == "on"); + } + } + return; + } + + // 3. Check for "Channel X: ON" or "Channel X: OFF" + size_t channelCapPos = msg.find("Channel "); + if (channelCapPos != std::string::npos) { + std::string sub = msg.substr(channelCapPos + 8); + std::stringstream ss(sub); + int chNum = 0; + std::string colon; + std::string state; + if (ss >> chNum >> colon >> state) { + if (colon == ":" && chNum >= 1 && chNum <= 8) { + m_channelWidgets[static_cast(chNum - 1)]->setLedState(state == "ON"); + } + } + return; + } +} diff --git a/sw/restatdesk/view/home.h b/sw/restatdesk/view/home.h new file mode 100644 index 0000000..24e43b2 --- /dev/null +++ b/sw/restatdesk/view/home.h @@ -0,0 +1,86 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// home.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::View { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class AppHome + /// @brief Home view window definition for the restatdesk application. + /// + /// Provides the main user interface for monitoring and controlling + /// multiple channels, delegating to individual ChannelWidget components. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class AppHome : public Gtk::ApplicationWindow, public IHomeView { + public: + explicit AppHome(); + virtual ~AppHome() override = default; + + AppHome(const AppHome &) = delete; + AppHome &operator=(const AppHome &) = delete; + + SigSettings controlChanged() override; + void setControlSetup(const SettingsSetup &setup) override; + void getUiData() override; + void updateUiData() override; + + sigc::signal& signal_execute_plan() override { return m_signalExecutePlan; } + + void show() override; + void hide() override; + void connect_close_request(const sigc::slot &slot) override; + Gtk::Window &getGtkWindow() override; + + void postData(const std::string& data) override; + + private: + void onChannelChanged(size_t index); + void onDataReceivedDispatcher(); + void updateLedsFromMessage(const std::string &msg); + + SettingsSetup m_setup{}; + SigSettings m_controlSignal{}; + sigc::signal m_signalExecutePlan; + + Gtk::Box m_boxRoot{}; + Gtk::Box m_boxChannels{}; + Gtk::Box m_boxActions{}; + Gtk::Button m_btnExecutePlan; + Gtk::ScrolledWindow m_scrolled_window{}; + Gtk::TextView m_textView{}; + std::vector> m_channelWidgets{}; + + Glib::Dispatcher m_dispatcher{}; + std::queue m_incomingDataQueue{}; + std::mutex m_mutex{}; + }; +} // namespace Electux::App::View diff --git a/sw/restatdesk/view/ihome_view.h b/sw/restatdesk/view/ihome_view.h new file mode 100644 index 0000000..28ae5ed --- /dev/null +++ b/sw/restatdesk/view/ihome_view.h @@ -0,0 +1,56 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ihome_view.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +namespace Gtk { + class Window; +} + +namespace Electux::App::View { + using SettingsSetup = Electux::App::Model::SettingsSetup; + using SigSettings = sigc::signal; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class IHomeView + /// @brief Interface defining the contract for the main home screen view. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class IHomeView { + public: + virtual ~IHomeView() = default; + + virtual SigSettings controlChanged() = 0; + virtual void setControlSetup(const SettingsSetup &setup) = 0; + virtual void updateUiData() = 0; + virtual void getUiData() = 0; + + virtual sigc::signal& signal_execute_plan() = 0; + + virtual void show() = 0; + virtual void hide() = 0; + virtual void connect_close_request(const sigc::slot &slot) = 0; + virtual Gtk::Window &getGtkWindow() = 0; + + virtual void postData(const std::string& data) = 0; + }; +} // namespace Electux::App::View diff --git a/sw/restatdesk/view/settings/.editorconfig b/sw/restatdesk/view/settings/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/settings/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/settings/ble/.editorconfig b/sw/restatdesk/view/settings/ble/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/settings/ble/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/settings/ble/ble_settings_tab.cc b/sw/restatdesk/view/settings/ble/ble_settings_tab.cc new file mode 100644 index 0000000..a8464ef --- /dev/null +++ b/sw/restatdesk/view/settings/ble/ble_settings_tab.cc @@ -0,0 +1,78 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_settings_tab.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace { + constexpr std::string_view cSettingsBleAddressLabel{"BLE Device Address / Name"}; + constexpr std::string_view cSettingsBleServiceUuidLabel{"Service UUID"}; + constexpr std::string_view cSettingsBleRxUuidLabel{"RX Characteristic UUID"}; + constexpr std::string_view cSettingsBleTxUuidLabel{"TX Characteristic UUID"}; +} // namespace + +using namespace Electux::App::View::Settings; +using namespace Electux::App::Model; + +BleSettingsTab::BleSettingsTab() : Gtk::Box(Gtk::Orientation::VERTICAL) { + m_labelAddress.set_label(cSettingsBleAddressLabel.data()); + append(m_labelAddress); + append(m_entryAddress); + + m_labelServiceUuid.set_label(cSettingsBleServiceUuidLabel.data()); + append(m_labelServiceUuid); + append(m_entryServiceUuid); + + m_labelRxUuid.set_label(cSettingsBleRxUuidLabel.data()); + append(m_labelRxUuid); + append(m_entryRxUuid); + + m_labelTxUuid.set_label(cSettingsBleTxUuidLabel.data()); + append(m_labelTxUuid); + append(m_entryTxUuid); +} + +void BleSettingsTab::updateData(const IModel &config) { + auto addrKey = config.toString(ModelBleKey::Address); + m_entryAddress.set_text(config.getEntity(addrKey).data()); + + auto serviceKey = config.toString(ModelBleKey::ServiceUuid); + m_entryServiceUuid.set_text(config.getEntity(serviceKey).data()); + + auto rxKey = config.toString(ModelBleKey::RxUuid); + m_entryRxUuid.set_text(config.getEntity(rxKey).data()); + + auto txKey = config.toString(ModelBleKey::TxUuid); + m_entryTxUuid.set_text(config.getEntity(txKey).data()); +} + +void BleSettingsTab::getData(IModel &config) { + auto addrKey = config.toString(ModelBleKey::Address); + config.update(addrKey, m_entryAddress.get_text().raw()); + + auto serviceKey = config.toString(ModelBleKey::ServiceUuid); + config.update(serviceKey, m_entryServiceUuid.get_text().raw()); + + auto rxKey = config.toString(ModelBleKey::RxUuid); + config.update(rxKey, m_entryRxUuid.get_text().raw()); + + auto txKey = config.toString(ModelBleKey::TxUuid); + config.update(txKey, m_entryTxUuid.get_text().raw()); +} diff --git a/sw/restatdesk/view/settings/ble/ble_settings_tab.h b/sw/restatdesk/view/settings/ble/ble_settings_tab.h new file mode 100644 index 0000000..c202f04 --- /dev/null +++ b/sw/restatdesk/view/settings/ble/ble_settings_tab.h @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// ble_settings_tab.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::View::Settings { + class BleSettingsTab : public Gtk::Box { + public: + explicit BleSettingsTab(); + virtual ~BleSettingsTab() override = default; + + BleSettingsTab(const BleSettingsTab &) = delete; + BleSettingsTab &operator=(const BleSettingsTab &) = delete; + + void updateData(const Electux::App::Model::IModel &config); + void getData(Electux::App::Model::IModel &config); + + private: + Gtk::Label m_labelAddress; + Gtk::Entry m_entryAddress; + Gtk::Label m_labelServiceUuid; + Gtk::Entry m_entryServiceUuid; + Gtk::Label m_labelRxUuid; + Gtk::Entry m_entryRxUuid; + Gtk::Label m_labelTxUuid; + Gtk::Entry m_entryTxUuid; + }; +} // namespace Electux::App::View::Settings diff --git a/sw/restatdesk/view/settings/general/.editorconfig b/sw/restatdesk/view/settings/general/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/settings/general/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/settings/general/general_settings_tab.cc b/sw/restatdesk/view/settings/general/general_settings_tab.cc new file mode 100644 index 0000000..cfcf5ff --- /dev/null +++ b/sw/restatdesk/view/settings/general/general_settings_tab.cc @@ -0,0 +1,68 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// general_settings_tab.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace { + constexpr std::string_view cSettingsComTypeLabel{"Connection type"}; +} // namespace + +using Electux::App::Com::cComTypeDescriptors; +using Electux::App::Com::ComType; +using Electux::App::Com::fromConfigString; +using Electux::App::Com::toConfigString; +using Electux::App::Model::IModel; +using Electux::App::Model::ModelGeneralKey; +using Electux::App::View::Settings::GeneralSettingsTab; + +GeneralSettingsTab::GeneralSettingsTab() + : Gtk::Box(Gtk::Orientation::VERTICAL) { + m_labelComType.set_label(cSettingsComTypeLabel.data()); + append(m_labelComType); + + for (const auto &desc : cComTypeDescriptors) { + m_comboComType.append(desc.displayName.data()); + } + + m_comboComType.set_active(0); + append(m_comboComType); +} + +void GeneralSettingsTab::updateData(const IModel &config) { + auto comTypeKey = config.toString(ModelGeneralKey::ComType); + auto value = config.getEntity(comTypeKey); + + ComType type = fromConfigString(value); + m_comboComType.set_active(static_cast(type)); +} + +void GeneralSettingsTab::getData(IModel &config) { + auto comTypeKey = config.toString(ModelGeneralKey::ComType); + int active = m_comboComType.get_active_row_number(); + + if (active >= 0 && active < static_cast(ComType::Count)) { + ComType type = static_cast(active); + config.update(comTypeKey, std::string(toConfigString(type))); + } else { + config.update(comTypeKey, std::string(toConfigString(ComType::Serial))); + } +} diff --git a/sw/restatdesk/view/settings/general/general_settings_tab.h b/sw/restatdesk/view/settings/general/general_settings_tab.h new file mode 100644 index 0000000..e98434f --- /dev/null +++ b/sw/restatdesk/view/settings/general/general_settings_tab.h @@ -0,0 +1,43 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// general_settings_tab.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::View::Settings { + class GeneralSettingsTab : public Gtk::Box { + public: + explicit GeneralSettingsTab(); + virtual ~GeneralSettingsTab() override = default; + + GeneralSettingsTab(const GeneralSettingsTab &) = delete; + GeneralSettingsTab &operator=(const GeneralSettingsTab &) = delete; + + void updateData(const Electux::App::Model::IModel &config); + void getData(Electux::App::Model::IModel &config); + + private: + Gtk::Label m_labelComType; + Gtk::ComboBoxText m_comboComType; + }; +} // namespace Electux::App::View::Settings diff --git a/sw/restatdesk/view/settings/isettings_view.h b/sw/restatdesk/view/settings/isettings_view.h new file mode 100644 index 0000000..8f40719 --- /dev/null +++ b/sw/restatdesk/view/settings/isettings_view.h @@ -0,0 +1,45 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// isettings_view.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace Electux::App::View::Settings { + using SettingsSetup = Electux::App::Model::SettingsSetup; + using SigSetup = sigc::signal; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ISettingsView + /// @brief Interface defining the contract for the settings tab view. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ISettingsView { + public: + virtual ~ISettingsView() = default; + + virtual SigSetup setupChanged() = 0; + virtual void setSettingsSetup(const SettingsSetup &setup) = 0; + virtual void updateUiData() = 0; + virtual void getUiData() = 0; + + virtual void show() = 0; + virtual void hide() = 0; + }; +} // namespace Electux::App::View::Settings diff --git a/sw/restatdesk/view/settings/log/.editorconfig b/sw/restatdesk/view/settings/log/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/settings/log/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/settings/log/log_settings_tab.cc b/sw/restatdesk/view/settings/log/log_settings_tab.cc new file mode 100644 index 0000000..21a58c5 --- /dev/null +++ b/sw/restatdesk/view/settings/log/log_settings_tab.cc @@ -0,0 +1,64 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log_settings_tab.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace { + constexpr std::string_view cSettingsLogPath{"Log file path"}; + constexpr std::string_view cSettingsLogLevel{"Log level"}; +} // namespace + +using namespace Electux::App::View::Settings; +using namespace Electux::App::Model; +using namespace Electux::App::Logger::LogLevels; + +LogSettingsTab::LogSettingsTab() : Gtk::Box(Gtk::Orientation::VERTICAL) { + m_labelLogPath.set_label(cSettingsLogPath.data()); + append(m_labelLogPath); + append(m_entryLogPath); + + m_labelLogLevel.set_label(cSettingsLogLevel.data()); + append(m_labelLogLevel); + for (const auto &level : cLogLevels) { + m_comboLogLevel.append(std::string(level)); + } + append(m_comboLogLevel); +} + +void LogSettingsTab::updateData(const IModel &config) { + auto pathKey = config.toString(ModelLogKey::FilePath); + m_entryLogPath.set_text(config.getEntity(pathKey).data()); + + auto levelKey = config.toString(ModelLogKey::LogLevel); + auto levelValue = std::stoi(config.getEntity(levelKey).data()); + m_comboLogLevel.set_active(levelValue); +} + +void LogSettingsTab::getData(IModel &config) { + auto pathKey = config.toString(ModelLogKey::FilePath); + config.update(pathKey, m_entryLogPath.get_text().raw()); + + auto levelKey = config.toString(ModelLogKey::LogLevel); + config.update( + levelKey, std::to_string(m_comboLogLevel.get_active_row_number()) + ); +} diff --git a/sw/restatdesk/view/settings/log/log_settings_tab.h b/sw/restatdesk/view/settings/log/log_settings_tab.h new file mode 100644 index 0000000..395a438 --- /dev/null +++ b/sw/restatdesk/view/settings/log/log_settings_tab.h @@ -0,0 +1,46 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// log_settings_tab.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include + +namespace Electux::App::View::Settings { + class LogSettingsTab : public Gtk::Box { + public: + explicit LogSettingsTab(); + virtual ~LogSettingsTab() override = default; + + LogSettingsTab(const LogSettingsTab &) = delete; + LogSettingsTab &operator=(const LogSettingsTab &) = delete; + + void updateData(const Electux::App::Model::IModel &config); + void getData(Electux::App::Model::IModel &config); + + private: + Gtk::Label m_labelLogPath; + Gtk::Entry m_entryLogPath; + Gtk::Label m_labelLogLevel; + Gtk::ComboBoxText m_comboLogLevel; + }; +} // namespace Electux::App::View::Settings diff --git a/sw/restatdesk/view/settings/serial/.editorconfig b/sw/restatdesk/view/settings/serial/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/settings/serial/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/settings/serial/serial_settings_tab.cc b/sw/restatdesk/view/settings/serial/serial_settings_tab.cc new file mode 100644 index 0000000..788941e --- /dev/null +++ b/sw/restatdesk/view/settings/serial/serial_settings_tab.cc @@ -0,0 +1,133 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_settings_tab.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace { + constexpr std::string_view cSettingsSerialPath{"Device port"}; + constexpr std::string_view cSettingsSerialBaud{"Baud rate"}; + constexpr std::string_view cSettingsSerialData{"Data bits"}; + constexpr std::string_view cSettingsSerialParity{"Parity"}; + constexpr std::string_view cSettingsSerialStop{"Stop bits"}; + constexpr std::string_view cSettingsSerialFlowControl{"Flow control"}; +} // namespace + +using namespace Electux::App::View::Settings; +using namespace Electux::App::Model; +using namespace Electux::App::Com::SerialComConstants; + +SerialSettingsTab::SerialSettingsTab() : Gtk::Box(Gtk::Orientation::VERTICAL) { + m_labelSerialPath.set_label(cSettingsSerialPath.data()); + append(m_labelSerialPath); + append(m_entrySerialPath); + + m_labelSerialBaud.set_label(cSettingsSerialBaud.data()); + append(m_labelSerialBaud); + for (const auto &rate : cComBaudRates) { + m_comboSerialBaud.append(std::string(rate)); + } + append(m_comboSerialBaud); + + m_labelSerialData.set_label(cSettingsSerialData.data()); + append(m_labelSerialData); + for (const auto &data : cComDataBits) { + m_comboSerialData.append(std::string(data)); + } + append(m_comboSerialData); + + m_labelSerialParity.set_label(cSettingsSerialParity.data()); + append(m_labelSerialParity); + for (const auto &parity : cComParities) { + m_comboSerialParity.append(std::string(parity)); + } + append(m_comboSerialParity); + + m_labelSerialStop.set_label(cSettingsSerialStop.data()); + append(m_labelSerialStop); + for (const auto &stop : cComStopBits) { + m_comboSerialStop.append(std::string(stop)); + } + append(m_comboSerialStop); + + m_labelSerialFlowControl.set_label(cSettingsSerialFlowControl.data()); + append(m_labelSerialFlowControl); + for (const auto &flow : cComFlowControls) { + m_comboSerialFlowControl.append(std::string(flow)); + } + append(m_comboSerialFlowControl); +} + +void SerialSettingsTab::updateData(const IModel &config) { + auto pathKey = config.toString(ModelSerialKey::Device); + m_entrySerialPath.set_text(config.getEntity(pathKey).data()); + + auto baudKey = config.toString(ModelSerialKey::Baud); + auto baudValue = std::stoi(config.getEntity(baudKey).data()); + m_comboSerialBaud.set_active(baudValue); + + auto dataKey = config.toString(ModelSerialKey::Data); + auto dataValue = std::stoi(config.getEntity(dataKey).data()); + m_comboSerialData.set_active(dataValue); + + auto parityKey = config.toString(ModelSerialKey::Parity); + auto parityValue = std::stoi(config.getEntity(parityKey).data()); + m_comboSerialParity.set_active(parityValue); + + auto stopKey = config.toString(ModelSerialKey::Stop); + auto stopValue = std::stoi(config.getEntity(stopKey).data()); + m_comboSerialStop.set_active(stopValue); + + auto flowKey = config.toString(ModelSerialKey::Flow); + auto flowValue = std::stoi(config.getEntity(flowKey).data()); + m_comboSerialFlowControl.set_active(flowValue); +} + +void SerialSettingsTab::getData(IModel &config) { + auto pathKey = config.toString(ModelSerialKey::Device); + config.update(pathKey, m_entrySerialPath.get_text().raw()); + + auto baudKey = config.toString(ModelSerialKey::Baud); + config.update( + baudKey, std::to_string(m_comboSerialBaud.get_active_row_number()) + ); + + auto dataKey = config.toString(ModelSerialKey::Data); + config.update( + dataKey, std::to_string(m_comboSerialData.get_active_row_number()) + ); + + auto parityKey = config.toString(ModelSerialKey::Parity); + config.update( + parityKey, std::to_string(m_comboSerialParity.get_active_row_number()) + ); + + auto stopKey = config.toString(ModelSerialKey::Stop); + config.update( + stopKey, std::to_string(m_comboSerialStop.get_active_row_number()) + ); + + auto flowKey = config.toString(ModelSerialKey::Flow); + config.update( + flowKey, + std::to_string(m_comboSerialFlowControl.get_active_row_number()) + ); +} diff --git a/sw/restatdesk/view/settings/serial/serial_settings_tab.h b/sw/restatdesk/view/settings/serial/serial_settings_tab.h new file mode 100644 index 0000000..375be24 --- /dev/null +++ b/sw/restatdesk/view/settings/serial/serial_settings_tab.h @@ -0,0 +1,54 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// serial_settings_tab.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include + +namespace Electux::App::View::Settings { + class SerialSettingsTab : public Gtk::Box { + public: + explicit SerialSettingsTab(); + virtual ~SerialSettingsTab() override = default; + + SerialSettingsTab(const SerialSettingsTab &) = delete; + SerialSettingsTab &operator=(const SerialSettingsTab &) = delete; + + void updateData(const Electux::App::Model::IModel &config); + void getData(Electux::App::Model::IModel &config); + + private: + Gtk::Label m_labelSerialPath; + Gtk::Entry m_entrySerialPath; + Gtk::Label m_labelSerialBaud; + Gtk::ComboBoxText m_comboSerialBaud; + Gtk::Label m_labelSerialData; + Gtk::ComboBoxText m_comboSerialData; + Gtk::Label m_labelSerialParity; + Gtk::ComboBoxText m_comboSerialParity; + Gtk::Label m_labelSerialStop; + Gtk::ComboBoxText m_comboSerialStop; + Gtk::Label m_labelSerialFlowControl; + Gtk::ComboBoxText m_comboSerialFlowControl; + }; +} // namespace Electux::App::View::Settings diff --git a/sw/restatdesk/view/settings/settings.cc b/sw/restatdesk/view/settings/settings.cc new file mode 100644 index 0000000..91bd7ba --- /dev/null +++ b/sw/restatdesk/view/settings/settings.cc @@ -0,0 +1,142 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// settings.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace { + constexpr std::string_view cSettingsTitle{"restatdesk"}; + constexpr int cSettingsWidth{320}; + constexpr int cSettingsHeight{320}; + constexpr int cSettingsNotebookMargin{10}; + constexpr std::string_view cSettingsPageGeneralLabel{"General"}; + constexpr std::string_view cSettingsPageSerialLabel{"Serial port"}; + constexpr std::string_view cSettingsPageTcpLabel{"TCP/IP"}; + constexpr std::string_view cSettingsPageBleLabel{"BLE"}; + constexpr std::string_view cSettingsPageLogLabel{"Log"}; + + constexpr int cSettingsButtonBoxWidth{220}; + constexpr int cSettingsButtonBoxHeight{60}; + constexpr int cSettingsButtonBoxMargin{10}; + constexpr int cSettingsButtonBoxRowSpacing{5}; + constexpr int cSettingsButtonBoxColumnSpacing{5}; + constexpr std::string_view cSettingsButtonOkLabel{"Ok"}; + constexpr std::string_view cSettingsButtonCancelLabel{"Cancel"}; + constexpr int cSettingsButtonWidth{100}; + constexpr int cSettingsButtonHeight{50}; + constexpr int cSettingsGridRowColumnOccupyZero{0}; + constexpr int cSettingsGridRowColumnOccupyOne{1}; +} // namespace + +using namespace Electux::App::View::Settings; + +AppSettings::AppSettings() { + set_title(cSettingsTitle.data()); + set_default_size(cSettingsWidth, cSettingsHeight); + set_resizable(false); + set_hide_on_close(true); + set_child(m_boxRoot); + + m_boxRoot.set_orientation(Gtk::Orientation::VERTICAL); + m_notebook.set_margin(cSettingsNotebookMargin); + m_notebook.set_expand(); + + m_notebook.append_page(m_generalTab, cSettingsPageGeneralLabel.data()); + m_notebook.append_page(m_serialTab, cSettingsPageSerialLabel.data()); + m_notebook.append_page(m_tcpTab, cSettingsPageTcpLabel.data()); + m_notebook.append_page(m_bleTab, cSettingsPageBleLabel.data()); + m_notebook.append_page(m_logTab, cSettingsPageLogLabel.data()); + m_boxRoot.append(m_notebook); + + m_buttonBox.set_size_request( + cSettingsButtonBoxWidth, cSettingsButtonBoxHeight + ); + m_buttonBox.set_margin(cSettingsButtonBoxMargin); + + m_buttonOk.set_label(cSettingsButtonOkLabel.data()); + m_buttonOk.set_size_request(cSettingsButtonWidth, cSettingsButtonHeight); + + m_buttonCancel.set_label(cSettingsButtonCancelLabel.data()); + m_buttonCancel.set_size_request( + cSettingsButtonWidth, cSettingsButtonHeight + ); + + m_buttonBox.attach( + m_buttonCancel, cSettingsGridRowColumnOccupyZero, + cSettingsGridRowColumnOccupyZero + ); + m_buttonBox.attach( + m_buttonOk, cSettingsGridRowColumnOccupyOne, + cSettingsGridRowColumnOccupyZero + ); + + m_buttonBox.set_hexpand(false); + m_buttonBox.set_vexpand(false); + m_buttonBox.set_row_spacing(cSettingsButtonBoxRowSpacing); + m_buttonBox.set_column_spacing(cSettingsButtonBoxColumnSpacing); + + m_boxRoot.append(m_buttonBox); + + mapping(); +} + +SigSetup AppSettings::setupChanged() { return m_setupSignal; } + +void AppSettings::setSettingsSetup(const SettingsSetup &setup) { + m_setup = setup; +} + +void AppSettings::updateUiData() { + m_generalTab.updateData(*m_setup.m_config); + m_serialTab.updateData(*m_setup.m_config); + m_tcpTab.updateData(*m_setup.m_config); + m_bleTab.updateData(*m_setup.m_config); + m_logTab.updateData(*m_setup.m_config); +} + +void AppSettings::getUiData() { + m_generalTab.getData(*m_setup.m_config); + m_serialTab.getData(*m_setup.m_config); + m_tcpTab.getData(*m_setup.m_config); + m_bleTab.getData(*m_setup.m_config); + m_logTab.getData(*m_setup.m_config); +} + +void AppSettings::mapping() { + m_buttonOk.signal_clicked().connect( + sigc::mem_fun(*this, &AppSettings::onButtonOkClicked) + ); + + m_buttonCancel.signal_clicked().connect( + sigc::mem_fun(*this, &AppSettings::onButtonCancelClicked) + ); +} + +void AppSettings::onButtonOkClicked() { + getUiData(); + m_setupSignal.emit(m_setup); + hide(); +} + +void AppSettings::onButtonCancelClicked() { hide(); } + +void AppSettings::show() { set_visible(true); } + +void AppSettings::hide() { set_visible(false); } diff --git a/sw/restatdesk/view/settings/settings.h b/sw/restatdesk/view/settings/settings.h new file mode 100644 index 0000000..b6772b0 --- /dev/null +++ b/sw/restatdesk/view/settings/settings.h @@ -0,0 +1,81 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// settings.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Electux::App::View::Settings { + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class AppSettings + /// @brief Application settings window definition. + /// + /// Manages the UI for configuring settings, delegating tab rendering + /// and data binding to SerialSettingsTab and LogSettingsTab. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class AppSettings : public Gtk::Window, public ISettingsView { + public: + explicit AppSettings(); + virtual ~AppSettings() override = default; + + AppSettings(const AppSettings &) = delete; + AppSettings &operator=(const AppSettings &) = delete; + + SigSetup setupChanged() override; + void setSettingsSetup(const SettingsSetup &setup) override; + void getUiData() override; + void updateUiData() override; + + void show() override; + void hide() override; + + protected: + void mapping(); + void onButtonOkClicked(); + void onButtonCancelClicked(); + + private: + SettingsSetup m_setup{}; + SigSetup m_setupSignal{}; + + Gtk::Box m_boxRoot{}; + Gtk::Notebook m_notebook{}; + GeneralSettingsTab m_generalTab{}; + SerialSettingsTab m_serialTab{}; + TcpSettingsTab m_tcpTab{}; + BleSettingsTab m_bleTab{}; + LogSettingsTab m_logTab{}; + Gtk::Grid m_buttonBox{}; + + Gtk::Button m_buttonOk{}; + Gtk::Button m_buttonCancel{}; + }; +} // namespace Electux::App::View::Settings diff --git a/sw/restatdesk/view/settings/tcp/.editorconfig b/sw/restatdesk/view/settings/tcp/.editorconfig new file mode 100644 index 0000000..b92ec54 --- /dev/null +++ b/sw/restatdesk/view/settings/tcp/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 \ No newline at end of file diff --git a/sw/restatdesk/view/settings/tcp/tcp_settings_tab.cc b/sw/restatdesk/view/settings/tcp/tcp_settings_tab.cc new file mode 100644 index 0000000..b9bf2a6 --- /dev/null +++ b/sw/restatdesk/view/settings/tcp/tcp_settings_tab.cc @@ -0,0 +1,56 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// tcp_settings_tab.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace { + constexpr std::string_view cSettingsTcpIpLabel{"IP Address"}; + constexpr std::string_view cSettingsTcpPortLabel{"Port number"}; +} // namespace + +using namespace Electux::App::View::Settings; +using namespace Electux::App::Model; + +TcpSettingsTab::TcpSettingsTab() : Gtk::Box(Gtk::Orientation::VERTICAL) { + m_labelIpAddress.set_label(cSettingsTcpIpLabel.data()); + append(m_labelIpAddress); + append(m_entryIpAddress); + + m_labelPort.set_label(cSettingsTcpPortLabel.data()); + append(m_labelPort); + append(m_entryPort); +} + +void TcpSettingsTab::updateData(const IModel &config) { + auto ipKey = config.toString(ModelGeneralKey::TcpIp); + m_entryIpAddress.set_text(config.getEntity(ipKey).data()); + + auto portKey = config.toString(ModelGeneralKey::TcpPort); + m_entryPort.set_text(config.getEntity(portKey).data()); +} + +void TcpSettingsTab::getData(IModel &config) { + auto ipKey = config.toString(ModelGeneralKey::TcpIp); + config.update(ipKey, m_entryIpAddress.get_text().raw()); + + auto portKey = config.toString(ModelGeneralKey::TcpPort); + config.update(portKey, m_entryPort.get_text().raw()); +} diff --git a/sw/restatdesk/view/settings/tcp/tcp_settings_tab.h b/sw/restatdesk/view/settings/tcp/tcp_settings_tab.h new file mode 100644 index 0000000..e1b518d --- /dev/null +++ b/sw/restatdesk/view/settings/tcp/tcp_settings_tab.h @@ -0,0 +1,45 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// tcp_settings_tab.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include + +namespace Electux::App::View::Settings { + class TcpSettingsTab : public Gtk::Box { + public: + explicit TcpSettingsTab(); + virtual ~TcpSettingsTab() override = default; + + TcpSettingsTab(const TcpSettingsTab &) = delete; + TcpSettingsTab &operator=(const TcpSettingsTab &) = delete; + + void updateData(const Electux::App::Model::IModel &config); + void getData(Electux::App::Model::IModel &config); + + private: + Gtk::Label m_labelIpAddress; + Gtk::Entry m_entryIpAddress; + Gtk::Label m_labelPort; + Gtk::Entry m_entryPort; + }; +} // namespace Electux::App::View::Settings diff --git a/sw/restatdesk/view/settings_setup.cc b/sw/restatdesk/view/settings_setup.cc new file mode 100644 index 0000000..1829bb9 --- /dev/null +++ b/sw/restatdesk/view/settings_setup.cc @@ -0,0 +1,41 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// settings_setup.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace Electux::App::Model { + SettingsSetup::SettingsSetup() : m_config(nullptr) {} + + SettingsSetup::~SettingsSetup() = default; + + SettingsSetup::SettingsSetup(const SettingsSetup &other) + : m_config(other.m_config ? other.m_config->clone() : nullptr) {} + + SettingsSetup &SettingsSetup::operator=(const SettingsSetup &other) { + if (this != &other) { + m_config = other.m_config ? other.m_config->clone() : nullptr; + } + return *this; + } + + SettingsSetup::SettingsSetup(SettingsSetup &&) noexcept = default; + SettingsSetup & + SettingsSetup::operator=(SettingsSetup &&) noexcept = default; +} // namespace Electux::App::Model diff --git a/sw/restatdesk/view/settings_setup.h b/sw/restatdesk/view/settings_setup.h new file mode 100644 index 0000000..766fd8f --- /dev/null +++ b/sw/restatdesk/view/settings_setup.h @@ -0,0 +1,73 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// settings_setup.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include + +namespace Electux::App::Model { + class IModel; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SettingsSetup + /// @brief Data structure for aggregating various configuration models. + /// + /// This class acts as a container for control, serial, and logging + /// configuration models, facilitating their transfer between views. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SettingsSetup { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief SettingsSetup constructor. + //////////////////////////////////////////////////////////////////////////////////////////////// + SettingsSetup(); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief SettingsSetup destructor. + //////////////////////////////////////////////////////////////////////////////////////////////// + ~SettingsSetup(); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief SettingsSetup copy constructor. + //////////////////////////////////////////////////////////////////////////////////////////////// + SettingsSetup(const SettingsSetup &other); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief SettingsSetup copy assignment operator. + //////////////////////////////////////////////////////////////////////////////////////////////// + SettingsSetup &operator=(const SettingsSetup &other); + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief SettingsSetup move constructor. + //////////////////////////////////////////////////////////////////////////////////////////////// + SettingsSetup(SettingsSetup &&) noexcept; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief SettingsSetup move assignment operator. + //////////////////////////////////////////////////////////////////////////////////////////////// + SettingsSetup &operator=(SettingsSetup &&) noexcept; + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Configuration Model + /// @{ + /// @brief Configuration model instance. + std::unique_ptr m_config; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + }; +} // namespace Electux::App::Model diff --git a/sw/restatdesk_tests/CMakeLists.txt b/sw/restatdesk_tests/CMakeLists.txt new file mode 100644 index 0000000..946c0dd --- /dev/null +++ b/sw/restatdesk_tests/CMakeLists.txt @@ -0,0 +1,68 @@ +# +# @brief restatdesk_tests main entry point for build tests +# @version v1.0.3 +# @date Tue Sep 19 08:55:54 PM CEST 2023 +# @author Vladimir Roncevic +# + +cmake_minimum_required(VERSION 3.12) +project(restat_tests CXX) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(GOOGLETEST_VERSION 1.14.0) + +enable_testing() + +# Add gtkmm and glibmm packages +find_package(PkgConfig REQUIRED) +pkg_check_modules(gtkmm REQUIRED IMPORTED_TARGET gtkmm-4.0 glibmm-2.4) + + +# Add sources and includes for googletest +add_subdirectory(googletest) +include_directories(googletest/include) +include_directories(googletest/googletest/include) +include_directories(googletest/googlemock/include) + +# Add sources and includes +include(${PROJECT_SOURCE_DIR}/com/pack.cmake) +include(${PROJECT_SOURCE_DIR}/config/pack.cmake) +include(${PROJECT_SOURCE_DIR}/log/pack.cmake) +include(${PROJECT_SOURCE_DIR}/channel/pack.cmake) +include(${PROJECT_SOURCE_DIR}/model/pack.cmake) +include_directories(com) +include_directories(config) +include_directories(log) +include_directories(channel) +include_directories(model) +include_directories(${RESTAT_COM_HEADERS}) +include_directories(${RESTAT_CONFIG_HEADERS}) +include_directories(${RESTAT_LOG_HEADERS}) +include_directories(${RESTAT_PARAMS_HEADERS}) +include_directories(${RESTAT_MODEL_HEADERS}) + +add_executable( + restat_tests + main.cc + ${RESTAT_COM_TESTS} + ${RESTAT_CONFIG_TESTS} + ${RESTAT_LOG_TESTS} + ${RESTAT_MODEL_TESTS} + ${RESTAT_COM_SOURCES} + ${RESTAT_CONFIG_SOURCES} + ${RESTAT_LOG_SOURCES} + ${RESTAT_MODEL_SOURCES} + ${RESTAT_PARAMS_TESTS} +) + +# Link libraries +target_link_libraries( + restat_tests + PUBLIC + gtest + gtest_main + gmock + gmock_main + PkgConfig::gtkmm +) +include(GoogleTest) +gtest_discover_tests(restat_tests) diff --git a/sw/restatdesk_tests/README.md b/sw/restatdesk_tests/README.md new file mode 100644 index 0000000..e69de29 diff --git a/sw/restatdesk_tests/build/googletest/googletest/generated/GTestConfig.cmake b/sw/restatdesk_tests/build/googletest/googletest/generated/GTestConfig.cmake new file mode 100644 index 0000000..9ab9a5e --- /dev/null +++ b/sw/restatdesk_tests/build/googletest/googletest/generated/GTestConfig.cmake @@ -0,0 +1,37 @@ + +####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### +####### Any changes to this file will be overwritten by the next CMake run #### +####### The input file was Config.cmake.in ######## + +get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE) + +macro(set_and_check _var _file) + set(${_var} "${_file}") + if(NOT EXISTS "${_file}") + message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !") + endif() +endmacro() + +macro(check_required_components _NAME) + foreach(comp ${${_NAME}_FIND_COMPONENTS}) + if(NOT ${_NAME}_${comp}_FOUND) + if(${_NAME}_FIND_REQUIRED_${comp}) + set(${_NAME}_FOUND FALSE) + endif() + endif() + endforeach() +endmacro() + +#################################################################################### +include(CMakeFindDependencyMacro) +if (ON) + set(THREADS_PREFER_PTHREAD_FLAG ) + find_dependency(Threads) +endif() +if (OFF) + find_dependency(absl) + find_dependency(re2) +endif() + +include("${CMAKE_CURRENT_LIST_DIR}/GTestTargets.cmake") +check_required_components("") diff --git a/sw/restatdesk_tests/build/googletest/googletest/generated/GTestConfigVersion.cmake b/sw/restatdesk_tests/build/googletest/googletest/generated/GTestConfigVersion.cmake new file mode 100644 index 0000000..a290d14 --- /dev/null +++ b/sw/restatdesk_tests/build/googletest/googletest/generated/GTestConfigVersion.cmake @@ -0,0 +1,43 @@ +# This is a basic version file for the Config-mode of find_package(). +# It is used by write_basic_package_version_file() as input file for configure_file() +# to create a version-file which can be installed along a config.cmake file. +# +# The created file sets PACKAGE_VERSION_EXACT if the current version string and +# the requested version string are exactly the same and it sets +# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version. +# The variable CVF_VERSION must be set before calling configure_file(). + +set(PACKAGE_VERSION "1.17.0") + +if (PACKAGE_FIND_VERSION_RANGE) + # Package version must be in the requested version range + if ((PACKAGE_FIND_VERSION_RANGE_MIN STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN) + OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_GREATER PACKAGE_FIND_VERSION_MAX) + OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_GREATER_EQUAL PACKAGE_FIND_VERSION_MAX))) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + endif() +else() + if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) + set(PACKAGE_VERSION_COMPATIBLE FALSE) + else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) + set(PACKAGE_VERSION_EXACT TRUE) + endif() + endif() +endif() + + +# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: +if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "") + return() +endif() + +# check that the installed version has the same 32/64bit-ness as the one which is currently searching: +if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8") + math(EXPR installedBits "8 * 8") + set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") + set(PACKAGE_VERSION_UNSUITABLE TRUE) +endif() diff --git a/sw/restatdesk_tests/build/googletest/googletest/generated/gmock.pc b/sw/restatdesk_tests/build/googletest/googletest/generated/gmock.pc new file mode 100644 index 0000000..e152eba --- /dev/null +++ b/sw/restatdesk_tests/build/googletest/googletest/generated/gmock.pc @@ -0,0 +1,10 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gmock +Description: GoogleMock (without main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Requires: gtest = 1.17.0 +Libs: -L${libdir} -lgmock +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restatdesk_tests/build/googletest/googletest/generated/gmock_main.pc b/sw/restatdesk_tests/build/googletest/googletest/generated/gmock_main.pc new file mode 100644 index 0000000..df9620a --- /dev/null +++ b/sw/restatdesk_tests/build/googletest/googletest/generated/gmock_main.pc @@ -0,0 +1,10 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Requires: gmock = 1.17.0 +Libs: -L${libdir} -lgmock_main +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restatdesk_tests/build/googletest/googletest/generated/gtest.pc b/sw/restatdesk_tests/build/googletest/googletest/generated/gtest.pc new file mode 100644 index 0000000..aeb8b52 --- /dev/null +++ b/sw/restatdesk_tests/build/googletest/googletest/generated/gtest.pc @@ -0,0 +1,9 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restatdesk_tests/build/googletest/googletest/generated/gtest_main.pc b/sw/restatdesk_tests/build/googletest/googletest/generated/gtest_main.pc new file mode 100644 index 0000000..d103700 --- /dev/null +++ b/sw/restatdesk_tests/build/googletest/googletest/generated/gtest_main.pc @@ -0,0 +1,10 @@ +libdir=/usr/local/lib +includedir=/usr/local/include + +Name: gtest_main +Description: GoogleTest (with main() function) +Version: 1.17.0 +URL: https://github.com/google/googletest +Requires: gtest = 1.17.0 +Libs: -L${libdir} -lgtest_main +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 diff --git a/sw/restatdesk_tests/build/restat_tests b/sw/restatdesk_tests/build/restat_tests new file mode 100755 index 0000000..efe2058 Binary files /dev/null and b/sw/restatdesk_tests/build/restat_tests differ diff --git a/sw/restatdesk_tests/build/restat_tests[1]_include.cmake b/sw/restatdesk_tests/build/restat_tests[1]_include.cmake new file mode 100644 index 0000000..03d77b8 --- /dev/null +++ b/sw/restatdesk_tests/build/restat_tests[1]_include.cmake @@ -0,0 +1,5 @@ +if(EXISTS "/data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests[1]_tests.cmake") + include("/data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests[1]_tests.cmake") +else() + add_test(restat_tests_NOT_BUILT restat_tests_NOT_BUILT) +endif() diff --git a/sw/restatdesk_tests/build/restat_tests[1]_tests.cmake b/sw/restatdesk_tests/build/restat_tests[1]_tests.cmake new file mode 100644 index 0000000..95e32b3 --- /dev/null +++ b/sw/restatdesk_tests/build/restat_tests[1]_tests.cmake @@ -0,0 +1,197 @@ +add_test([=[SerialComTest.InvalidBaudRateDetectionTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.InvalidBaudRateDetectionTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.InvalidBaudRateDetectionTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.InvalidDataBitsDetectionTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.InvalidDataBitsDetectionTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.InvalidDataBitsDetectionTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.InvalidParityDetectionTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.InvalidParityDetectionTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.InvalidParityDetectionTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.InvalidStopBitsDetectionTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.InvalidStopBitsDetectionTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.InvalidStopBitsDetectionTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.InvalidFlowControlDetectionTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.InvalidFlowControlDetectionTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.InvalidFlowControlDetectionTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.OpenSerialPortTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.OpenSerialPortTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.OpenSerialPortTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.OpenInvalidPortTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.OpenInvalidPortTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.OpenInvalidPortTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.closeSerialPortTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.closeSerialPortTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.closeSerialPortTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest.ReadFromPortTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest.ReadFromPortTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest.ReadFromPortTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[MockISerialTest.SetDeviceTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=MockISerialTest.SetDeviceTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[MockISerialTest.SetDeviceTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[MockISerialTest.SetupTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=MockISerialTest.SetupTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[MockISerialTest.SetupTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[MockISerialTest.SequentialConfigTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=MockISerialTest.SequentialConfigTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[MockISerialTest.SequentialConfigTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[MockIComTest.CloseIComTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=MockIComTest.CloseIComTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[MockIComTest.CloseIComTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[MockILibSerialPortTest.CloseILibSerialPortTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=MockILibSerialPortTest.CloseILibSerialPortTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[MockILibSerialPortTest.CloseILibSerialPortTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[BleComConfiguratorTest.ConfigureSuccessTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=BleComConfiguratorTest.ConfigureSuccessTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[BleComConfiguratorTest.ConfigureSuccessTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[BleComConfiguratorTest.ConfigureFailureTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=BleComConfiguratorTest.ConfigureFailureTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[BleComConfiguratorTest.ConfigureFailureTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.ControlConfigTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.ControlConfigTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.ControlConfigTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.LogConfigTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.LogConfigTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.LogConfigTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.SerialConfigTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.SerialConfigTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.SerialConfigTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.LoadConfigTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.LoadConfigTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.LoadConfigTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.MissingFileLoadDefaultsTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.MissingFileLoadDefaultsTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.MissingFileLoadDefaultsTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.ParsingEdgeCasesTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.ParsingEdgeCasesTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.ParsingEdgeCasesTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.StoreConfigTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.StoreConfigTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.StoreConfigTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.StoreFailureTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.StoreFailureTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.StoreFailureTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.ExplicitDefaultStoreTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.ExplicitDefaultStoreTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.ExplicitDefaultStoreTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.SetConfigTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.SetConfigTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.SetConfigTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ConfigManagerTest.StoreAndReloadTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ConfigManagerTest.StoreAndReloadTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ConfigManagerTest.StoreAndReloadTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.SetOutputFileTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.SetOutputFileTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.SetOutputFileTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.EmptyFilePathIsWithoutEffectTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.EmptyFilePathIsWithoutEffectTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.EmptyFilePathIsWithoutEffectTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.LevelManagementTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.LevelManagementTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.LevelManagementTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.DefaultLevelTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.DefaultLevelTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.DefaultLevelTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.FileOpenTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.FileOpenTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.FileOpenTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.DoubleOpenTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.DoubleOpenTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.DoubleOpenTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.OpenFailureTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.OpenFailureTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.OpenFailureTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.LogMessageFormatTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.LogMessageFormatTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.LogMessageFormatTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.AllLevelFilteringTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.AllLevelFilteringTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.AllLevelFilteringTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.LogToClosedStreamIsWithoutEffectTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.LogToClosedStreamIsWithoutEffectTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.LogToClosedStreamIsWithoutEffectTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.LogFilteringTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.LogFilteringTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.LogFilteringTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.TagVerificationTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.TagVerificationTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.TagVerificationTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.MultiThreadedLoggingTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.MultiThreadedLoggingTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.MultiThreadedLoggingTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.CloseTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.CloseTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.CloseTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.DoubleCloseIsOkTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.DoubleCloseIsOkTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.DoubleCloseIsOkTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[LogTest.DestructorClosesFileTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=LogTest.DestructorClosesFileTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[LogTest.DestructorClosesFileTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[MockLogTest.OpenFailureHandlingTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=MockLogTest.OpenFailureHandlingTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[MockLogTest.OpenFailureHandlingTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.ValidateKeyTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.ValidateKeyTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.ValidateKeyTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.AddAndGetEntityTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.AddAndGetEntityTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.AddAndGetEntityTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.UpdateEntityTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.UpdateEntityTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.UpdateEntityTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.ClearTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.ClearTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.ClearTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.ToStringEnumTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.ToStringEnumTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.ToStringEnumTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.ChannelStateTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.ChannelStateTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.ChannelStateTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.SignalChangedTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.SignalChangedTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.SignalChangedTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ModelTest.CloneTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ModelTest.CloneTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ModelTest.CloneTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsChannelTest.BoolToStringTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsChannelTest.BoolToStringTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsChannelTest.BoolToStringTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsChannelTest.EmptyStringTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsChannelTest.EmptyStringTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsChannelTest.EmptyStringTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsChannelTest.NumberOfChannelsTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsChannelTest.NumberOfChannelsTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsChannelTest.NumberOfChannelsTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsChannelTest.SpaceStringTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsChannelTest.SpaceStringTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsChannelTest.SpaceStringTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsChannelTest.SpaceDelimiterTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsChannelTest.SpaceDelimiterTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsChannelTest.SpaceDelimiterTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsChannelTest.TrueStringTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsChannelTest.TrueStringTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsChannelTest.TrueStringTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsChannelTest.FalseStringTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsChannelTest.FalseStringTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsChannelTest.FalseStringTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsLogLevelsTest.LogLevelsArrayTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsLogLevelsTest.LogLevelsArrayTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsLogLevelsTest.LogLevelsArrayTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsLogLevelsTest.LogLevelErrorTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsLogLevelsTest.LogLevelErrorTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsLogLevelsTest.LogLevelErrorTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsLogLevelsTest.LogLevelWarningTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsLogLevelsTest.LogLevelWarningTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsLogLevelsTest.LogLevelWarningTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsLogLevelsTest.LogLevelInfoTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsLogLevelsTest.LogLevelInfoTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsLogLevelsTest.LogLevelInfoTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComBaudRatesArrayTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComBaudRatesArrayTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComBaudRatesArrayTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComBaudRatesConstantsTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComBaudRatesConstantsTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComBaudRatesConstantsTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComDataBitsArrayTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComDataBitsArrayTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComDataBitsArrayTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComDataBitsConstantsTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComDataBitsConstantsTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComDataBitsConstantsTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComParitiesArrayTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComParitiesArrayTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComParitiesArrayTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComParityConstantsTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComParityConstantsTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComParityConstantsTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComStopBitsArrayTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComStopBitsArrayTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComStopBitsArrayTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComStopBitsConstantsTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComStopBitsConstantsTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComStopBitsConstantsTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComFlowControlsArrayTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComFlowControlsArrayTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComFlowControlsArrayTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComFlowControlConstantsTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComFlowControlConstantsTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComFlowControlConstantsTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[ParamsSerialComTest.ComInvalidParameterTest]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=ParamsSerialComTest.ComInvalidParameterTest]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[ParamsSerialComTest.ComInvalidParameterTest]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <01-00 00-00 00-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/0]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <01-00 00-00 00-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <02-00 00-00 01-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/1]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <02-00 00-00 01-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <03-00 00-00 02-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/2]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <03-00 00-00 02-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <04-00 00-00 03-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/3]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <04-00 00-00 03-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <05-00 00-00 04-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/4]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <05-00 00-00 04-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <06-00 00-00 05-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/5]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <06-00 00-00 05-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <07-00 00-00 06-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/6]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <07-00 00-00 06-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <08-00 00-00 07-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/7]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <08-00 00-00 07-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <09-00 00-00 08-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/8]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <09-00 00-00 08-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0A-00 00-00 09-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/9]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0A-00 00-00 09-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0B-00 00-00 0A-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/10]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0B-00 00-00 0A-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0C-00 00-00 0B-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/BaudRateTest.BaudRateConversionTest/11]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0C-00 00-00 0B-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/DataBitsTest.DataBitsConversionTest/0]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <02-A0 6F-4F 01-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/DataBitsTest.DataBitsConversionTest/1]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <02-A0 6F-4F 01-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <03-00 00-00 02-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/DataBitsTest.DataBitsConversionTest/2]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <03-00 00-00 02-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <04-5F 10-07 03-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/DataBitsTest.DataBitsConversionTest/3]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <04-5F 10-07 03-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/ParityTest.ParityConversionTest/8-byte object <01-5F 10-07 02-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/ParityTest.ParityConversionTest/0]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/ParityTest.ParityConversionTest/8-byte object <01-5F 10-07 02-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/ParityTest.ParityConversionTest/8-byte object <02-24 70-4F 01-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/ParityTest.ParityConversionTest/1]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/ParityTest.ParityConversionTest/8-byte object <02-24 70-4F 01-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/ParityTest.ParityConversionTest/8-byte object <03-00 00-00 00-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/ParityTest.ParityConversionTest/2]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/ParityTest.ParityConversionTest/8-byte object <03-00 00-00 00-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/StopBitsTest.StopBitsConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/StopBitsTest.StopBitsConversionTest/0]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/StopBitsTest.StopBitsConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/StopBitsTest.StopBitsConversionTest/8-byte object <02-A7 70-4F 01-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/StopBitsTest.StopBitsConversionTest/1]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/StopBitsTest.StopBitsConversionTest/8-byte object <02-A7 70-4F 01-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/FlowControlTest.FlowControlConversionTest/0]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <03-29 71-4F 01-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/FlowControlTest.FlowControlConversionTest/1]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <03-29 71-4F 01-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +add_test([=[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <02-00 00-00 02-00 00-00>]=] /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build/restat_tests [==[--gtest_filter=SerialComTest/FlowControlTest.FlowControlConversionTest/2]==] --gtest_also_run_disabled_tests) +set_tests_properties([=[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <02-00 00-00 02-00 00-00>]=] PROPERTIES WORKING_DIRECTORY /data/dev/raspberry/restat/github/restat/sw/restatdesk_tests/build SKIP_REGULAR_EXPRESSION [==[\[ SKIPPED \]]==]) +set( restat_tests_TESTS SerialComTest.InvalidBaudRateDetectionTest SerialComTest.InvalidDataBitsDetectionTest SerialComTest.InvalidParityDetectionTest SerialComTest.InvalidStopBitsDetectionTest SerialComTest.InvalidFlowControlDetectionTest SerialComTest.OpenSerialPortTest SerialComTest.OpenInvalidPortTest SerialComTest.closeSerialPortTest SerialComTest.ReadFromPortTest MockISerialTest.SetDeviceTest MockISerialTest.SetupTest MockISerialTest.SequentialConfigTest MockIComTest.CloseIComTest MockILibSerialPortTest.CloseILibSerialPortTest BleComConfiguratorTest.ConfigureSuccessTest BleComConfiguratorTest.ConfigureFailureTest ConfigManagerTest.ControlConfigTest ConfigManagerTest.LogConfigTest ConfigManagerTest.SerialConfigTest ConfigManagerTest.LoadConfigTest ConfigManagerTest.MissingFileLoadDefaultsTest ConfigManagerTest.ParsingEdgeCasesTest ConfigManagerTest.StoreConfigTest ConfigManagerTest.StoreFailureTest ConfigManagerTest.ExplicitDefaultStoreTest ConfigManagerTest.SetConfigTest ConfigManagerTest.StoreAndReloadTest LogTest.SetOutputFileTest LogTest.EmptyFilePathIsWithoutEffectTest LogTest.LevelManagementTest LogTest.DefaultLevelTest LogTest.FileOpenTest LogTest.DoubleOpenTest LogTest.OpenFailureTest LogTest.LogMessageFormatTest LogTest.AllLevelFilteringTest LogTest.LogToClosedStreamIsWithoutEffectTest LogTest.LogFilteringTest LogTest.TagVerificationTest LogTest.MultiThreadedLoggingTest LogTest.CloseTest LogTest.DoubleCloseIsOkTest LogTest.DestructorClosesFileTest MockLogTest.OpenFailureHandlingTest ModelTest.ValidateKeyTest ModelTest.AddAndGetEntityTest ModelTest.UpdateEntityTest ModelTest.ClearTest ModelTest.ToStringEnumTest ModelTest.ChannelStateTest ModelTest.SignalChangedTest ModelTest.CloneTest ParamsChannelTest.BoolToStringTest ParamsChannelTest.EmptyStringTest ParamsChannelTest.NumberOfChannelsTest ParamsChannelTest.SpaceStringTest ParamsChannelTest.SpaceDelimiterTest ParamsChannelTest.TrueStringTest ParamsChannelTest.FalseStringTest ParamsLogLevelsTest.LogLevelsArrayTest ParamsLogLevelsTest.LogLevelErrorTest ParamsLogLevelsTest.LogLevelWarningTest ParamsLogLevelsTest.LogLevelInfoTest ParamsSerialComTest.ComBaudRatesArrayTest ParamsSerialComTest.ComBaudRatesConstantsTest ParamsSerialComTest.ComDataBitsArrayTest ParamsSerialComTest.ComDataBitsConstantsTest ParamsSerialComTest.ComParitiesArrayTest ParamsSerialComTest.ComParityConstantsTest ParamsSerialComTest.ComStopBitsArrayTest ParamsSerialComTest.ComStopBitsConstantsTest ParamsSerialComTest.ComFlowControlsArrayTest ParamsSerialComTest.ComFlowControlConstantsTest ParamsSerialComTest.ComInvalidParameterTest [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <01-00 00-00 00-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <02-00 00-00 01-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <03-00 00-00 02-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <04-00 00-00 03-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <05-00 00-00 04-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <06-00 00-00 05-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <07-00 00-00 06-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <08-00 00-00 07-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <09-00 00-00 08-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0A-00 00-00 09-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0B-00 00-00 0A-00 00-00>]==] [==[SerialComTest/BaudRateTest.BaudRateConversionTest/8-byte object <0C-00 00-00 0B-00 00-00>]==] [==[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]==] [==[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <02-A0 6F-4F 01-00 00-00>]==] [==[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <03-00 00-00 02-00 00-00>]==] [==[SerialComTest/DataBitsTest.DataBitsConversionTest/8-byte object <04-5F 10-07 03-00 00-00>]==] [==[SerialComTest/ParityTest.ParityConversionTest/8-byte object <01-5F 10-07 02-00 00-00>]==] [==[SerialComTest/ParityTest.ParityConversionTest/8-byte object <02-24 70-4F 01-00 00-00>]==] [==[SerialComTest/ParityTest.ParityConversionTest/8-byte object <03-00 00-00 00-00 00-00>]==] [==[SerialComTest/StopBitsTest.StopBitsConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]==] [==[SerialComTest/StopBitsTest.StopBitsConversionTest/8-byte object <02-A7 70-4F 01-00 00-00>]==] [==[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <01-5F 10-07 00-00 00-00>]==] [==[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <03-29 71-4F 01-00 00-00>]==] [==[SerialComTest/FlowControlTest.FlowControlConversionTest/8-byte object <02-00 00-00 02-00 00-00>]==]) diff --git a/sw/restatdesk_tests/channel/pack.cmake b/sw/restatdesk_tests/channel/pack.cmake new file mode 100644 index 0000000..d87e350 --- /dev/null +++ b/sw/restatdesk_tests/channel/pack.cmake @@ -0,0 +1,18 @@ +# +# @brief restatdesk_tests list of all sources and unit tests for config +# @version v1.0.3 +# @date Tue Sep 19 08:55:54 PM CEST 2023 +# @author Vladimir Roncevic +# + +set( + RESTAT_PARAMS_HEADERS + ${PROJECT_SOURCE_DIR}/../restatdesk/ +) + +set( + RESTAT_PARAMS_TESTS + ${PROJECT_SOURCE_DIR}/channel/test_params_channel.cc + ${PROJECT_SOURCE_DIR}/channel/test_log_params.cc + ${PROJECT_SOURCE_DIR}/channel/test_serial_params.cc +) diff --git a/sw/restatdesk_tests/channel/test_log_params.cc b/sw/restatdesk_tests/channel/test_log_params.cc new file mode 100644 index 0000000..6458234 --- /dev/null +++ b/sw/restatdesk_tests/channel/test_log_params.cc @@ -0,0 +1,69 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_log_params.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +using namespace Electux::App::Logger::LogLevels; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test log levels array. +/// +/// @param ParamsLogLevelsTest The name of the test case. +/// @param LogLevelsArrayTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsLogLevelsTest, LogLevelsArrayTest) +{ + EXPECT_EQ(cLogLevels[0], "Error"); + EXPECT_EQ(cLogLevels[1], "Warning"); + EXPECT_EQ(cLogLevels[2], "Info"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test log level error constant. +/// +/// @param ParamsLogLevelsTest The name of the test case. +/// @param LogLevelErrorTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsLogLevelsTest, LogLevelErrorTest) +{ + EXPECT_EQ(clogLevelError, 0); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test log level warning constant. +/// +/// @param ParamsLogLevelsTest The name of the test case. +/// @param LogLevelWarningTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsLogLevelsTest, LogLevelWarningTest) +{ + EXPECT_EQ(clogLevelWarning, 1); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test log level info constant. +/// +/// @param ParamsLogLevelsTest The name of the test case. +/// @param LogLevelInfoTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsLogLevelsTest, LogLevelInfoTest) +{ + EXPECT_EQ(clogLevelInfo, 2); +} diff --git a/sw/restatdesk_tests/channel/test_params_channel.cc b/sw/restatdesk_tests/channel/test_params_channel.cc new file mode 100644 index 0000000..a38f242 --- /dev/null +++ b/sw/restatdesk_tests/channel/test_params_channel.cc @@ -0,0 +1,103 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_params_channel.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +using namespace Electux::App::Model::Channel; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test bool to string. +/// +/// @param ParamsChannelTest The name of the test case. +/// @param BoolToStringTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsChannelTest, BoolToStringTest) +{ + EXPECT_EQ(boolToString(true), cTrue); + EXPECT_EQ(boolToString(false), cFalse); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test empty string. +/// +/// @param ParamsChannelTest The name of the test case. +/// @param EmptyStringTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsChannelTest, EmptyStringTest) +{ + EXPECT_EQ(cEmptyString.length(), 0); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test number of channels. +/// +/// @param ParamsChannelTest The name of the test case. +/// @param NumberOfChannelsTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsChannelTest, NumberOfChannelsTest) +{ + EXPECT_EQ(cNumOfChannels, 8); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test space string. +/// +/// @param ParamsChannelTest The name of the test case. +/// @param SpaceStringTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsChannelTest, SpaceStringTest) +{ + EXPECT_EQ(cSpaceString, " "); + EXPECT_EQ(cSpaceString.length(), 1); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test space delimiter. +/// +/// @param ParamsChannelTest The name of the test case. +/// @param SpaceDelimiterTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsChannelTest, SpaceDelimiterTest) +{ + EXPECT_EQ(cSpaceDelimiter, ' '); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test true string. +/// +/// @param ParamsChannelTest The name of the test case. +/// @param TrueStringTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsChannelTest, TrueStringTest) +{ + EXPECT_EQ(cTrue, "true"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test false string. +/// +/// @param ParamsChannelTest The name of the test case. +/// @param FalseStringTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsChannelTest, FalseStringTest) +{ + EXPECT_EQ(cFalse, "false"); +} diff --git a/sw/restatdesk_tests/channel/test_serial_params.cc b/sw/restatdesk_tests/channel/test_serial_params.cc new file mode 100644 index 0000000..af29c3d --- /dev/null +++ b/sw/restatdesk_tests/channel/test_serial_params.cc @@ -0,0 +1,182 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_params.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +using namespace Electux::App::Com::SerialComConstants; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test baud rates array. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComBaudRatesArrayTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComBaudRatesArrayTest) +{ + EXPECT_EQ(cComBaudRates[cComBaud110], "110"); + EXPECT_EQ(cComBaudRates[cComBaud300], "300"); + EXPECT_EQ(cComBaudRates[cComBaud600], "600"); + EXPECT_EQ(cComBaudRates[cComBaud1200], "1200"); + EXPECT_EQ(cComBaudRates[cComBaud2400], "2400"); + EXPECT_EQ(cComBaudRates[cComBaud4800], "4800"); + EXPECT_EQ(cComBaudRates[cComBaud9600], "9600"); + EXPECT_EQ(cComBaudRates[cComBaud19200], "19200"); + EXPECT_EQ(cComBaudRates[cComBaud38400], "38400"); + EXPECT_EQ(cComBaudRates[cComBaud57600], "57600"); + EXPECT_EQ(cComBaudRates[cComBaud115200], "115200"); + EXPECT_EQ(cComBaudRates[cComBaud230400], "230400"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test baud rate constants. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComBaudRatesConstantsTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComBaudRatesConstantsTest) +{ + EXPECT_EQ(cComBaud110, 0); + EXPECT_EQ(cComBaud300, 1); + EXPECT_EQ(cComBaud600, 2); + EXPECT_EQ(cComBaud1200, 3); + EXPECT_EQ(cComBaud2400, 4); + EXPECT_EQ(cComBaud4800, 5); + EXPECT_EQ(cComBaud9600, 6); + EXPECT_EQ(cComBaud19200, 7); + EXPECT_EQ(cComBaud38400, 8); + EXPECT_EQ(cComBaud57600, 9); + EXPECT_EQ(cComBaud115200, 10); + EXPECT_EQ(cComBaud230400, 11); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test data bits array. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComDataBitsArrayTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComDataBitsArrayTest) +{ + EXPECT_EQ(cComDataBits[cComDataBits5], "5"); + EXPECT_EQ(cComDataBits[cComDataBits6], "6"); + EXPECT_EQ(cComDataBits[cComDataBits7], "7"); + EXPECT_EQ(cComDataBits[cComDataBits8], "8"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test data bits constants. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComDataBitsConstantsTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComDataBitsConstantsTest) +{ + EXPECT_EQ(cComDataBits5, 0); + EXPECT_EQ(cComDataBits6, 1); + EXPECT_EQ(cComDataBits7, 2); + EXPECT_EQ(cComDataBits8, 3); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test parities array. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComParitiesArrayTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComParitiesArrayTest) +{ + EXPECT_EQ(cComParities[cComParityEven], "Even"); + EXPECT_EQ(cComParities[cComParityOdd], "Odd"); + EXPECT_EQ(cComParities[cComParityNone], "None"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test parity constants. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComParityConstantsTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComParityConstantsTest) +{ + EXPECT_EQ(cComParityEven, 0); + EXPECT_EQ(cComParityOdd, 1); + EXPECT_EQ(cComParityNone, 2); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test stop bits array. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComStopBitsArrayTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComStopBitsArrayTest) +{ + EXPECT_EQ(cComStopBits[cComStopBits1], "1"); + EXPECT_EQ(cComStopBits[cComStopBits2], "2"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test stop bits constants. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComStopBitsConstantsTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComStopBitsConstantsTest) +{ + EXPECT_EQ(cComStopBits1, 0); + EXPECT_EQ(cComStopBits2, 1); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test flow controls array. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComFlowControlsArrayTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComFlowControlsArrayTest) +{ + EXPECT_EQ(cComFlowControls[cComFlowControlNone], "None"); + EXPECT_EQ(cComFlowControls[cComFlowControlHw], "Hardware"); + EXPECT_EQ(cComFlowControls[cComFlowControlSw], "Software"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test flow control constants. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComFlowControlConstantsTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComFlowControlConstantsTest) +{ + EXPECT_EQ(cComFlowControlNone, 0); + EXPECT_EQ(cComFlowControlHw, 1); + EXPECT_EQ(cComFlowControlSw, 2); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test invalid parameter constant. +/// +/// @param ParamsSerialComTest The name of the test case. +/// @param ComInvalidParameterTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(ParamsSerialComTest, ComInvalidParameterTest) +{ + EXPECT_EQ(cComInvalidParameter, 127); +} diff --git a/sw/restatdesk_tests/com/.editorconfig b/sw/restatdesk_tests/com/.editorconfig new file mode 100644 index 0000000..72716a4 --- /dev/null +++ b/sw/restatdesk_tests/com/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 diff --git a/sw/restatdesk_tests/com/pack.cmake b/sw/restatdesk_tests/com/pack.cmake new file mode 100644 index 0000000..b0050ea --- /dev/null +++ b/sw/restatdesk_tests/com/pack.cmake @@ -0,0 +1,34 @@ +# +# @brief restatdesk_tests list of all sources and unit tests for config +# @version v1.0.3 +# @date Tue Sep 19 08:55:54 PM CEST 2023 +# @author Vladimir Roncevic +# + +set( + RESTAT_COM_HEADERS + ${PROJECT_SOURCE_DIR}/../restatdesk/ +) + +set( + RESTAT_COM_SOURCES + ${PROJECT_SOURCE_DIR}/../restatdesk/com/serial/serial_com.cc + ${PROJECT_SOURCE_DIR}/../restatdesk/com/serial/serialw/serial_lib_wrapper.cc + ${PROJECT_SOURCE_DIR}/../restatdesk/com/serial/serial_utils.cc + ${PROJECT_SOURCE_DIR}/../restatdesk/com/ble/configurator/ble_com_configurator.cc +) + +set( + RESTAT_COM_TESTS + ${PROJECT_SOURCE_DIR}/com/test_serial_baude_rate.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_data_bits.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_parity.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_stop_bits.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_flow_control.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_setup.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_open.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_close.cc + ${PROJECT_SOURCE_DIR}/com/test_serial_read.cc + ${PROJECT_SOURCE_DIR}/com/test_ble_com.cc + #${PROJECT_SOURCE_DIR}/com/test_serial_write.cc +) diff --git a/sw/restatdesk_tests/com/test_ble_com.cc b/sw/restatdesk_tests/com/test_ble_com.cc new file mode 100644 index 0000000..dbc2cb6 --- /dev/null +++ b/sw/restatdesk_tests/com/test_ble_com.cc @@ -0,0 +1,76 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_ble_com.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include "test_mock_ible.h" +#include "test_mock_icom.h" + +using namespace Electux::App::Com; +using namespace Electux::App::Model; +using namespace ::testing; + +class BleComConfiguratorTest : public Test { + protected: + void SetUp() override { + m_model = Electux::App::Model::createDefault(); + + auto addrKey = m_model->toString(ModelBleKey::Address); + auto serviceKey = m_model->toString(ModelBleKey::ServiceUuid); + auto rxKey = m_model->toString(ModelBleKey::RxUuid); + auto txKey = m_model->toString(ModelBleKey::TxUuid); + + m_model->add(addrKey, "00:11:22:33:44:55"); + m_model->add(serviceKey, "ffe0"); + m_model->add(rxKey, "ffe1"); + m_model->add(txKey, "ffe2"); + + m_bleMock = std::make_unique(); + m_comMock = std::make_unique(); + m_configurator = std::make_unique(m_bleMock.get()); + } + + std::unique_ptr m_model; + std::unique_ptr m_bleMock; + std::unique_ptr m_comMock; + std::unique_ptr m_configurator; +}; + +TEST_F(BleComConfiguratorTest, ConfigureSuccessTest) { + EXPECT_CALL(*m_comMock, open()).WillOnce(Return(true)); + + bool result = m_configurator->configure(*m_model, m_comMock.get()); + + EXPECT_TRUE(result); + EXPECT_EQ(m_bleMock->m_address, "00:11:22:33:44:55"); + EXPECT_EQ(m_bleMock->m_serviceUuid, "ffe0"); + EXPECT_EQ(m_bleMock->m_rxUuid, "ffe1"); + EXPECT_EQ(m_bleMock->m_txUuid, "ffe2"); +} + +TEST_F(BleComConfiguratorTest, ConfigureFailureTest) { + EXPECT_CALL(*m_comMock, open()).WillOnce(Return(false)); + + bool result = m_configurator->configure(*m_model, m_comMock.get()); + + EXPECT_FALSE(result); +} diff --git a/sw/restatdesk_tests/com/test_mock_ible.h b/sw/restatdesk_tests/com/test_mock_ible.h new file mode 100644 index 0000000..46d62a3 --- /dev/null +++ b/sw/restatdesk_tests/com/test_mock_ible.h @@ -0,0 +1,52 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_mock_ible.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +/// +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +namespace com::mock { + class MockIBle : public Electux::App::Com::IBle { + public: + MockIBle() = default; + ~MockIBle() override = default; + + void setBleAddress(const std::string &address) override { + m_address = address; + } + + void setServiceUuid(const std::string &uuid) override { + m_serviceUuid = uuid; + } + + void setRxUuid(const std::string &uuid) override { + m_rxUuid = uuid; + } + + void setTxUuid(const std::string &uuid) override { + m_txUuid = uuid; + } + + std::string m_address; + std::string m_serviceUuid; + std::string m_rxUuid; + std::string m_txUuid; + }; +} // namespace com::mock diff --git a/sw/restatdesk_tests/com/test_mock_icom.h b/sw/restatdesk_tests/com/test_mock_icom.h new file mode 100644 index 0000000..daa0b77 --- /dev/null +++ b/sw/restatdesk_tests/com/test_mock_icom.h @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_mock_icom.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace com::mock +/// @brief Namespace for application communication mocks +namespace com::mock +{ + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using ICom = Electux::App::Com::ICom; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class MockICom + /// @brief Mock implementation of the ICom interface for testing purposes. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class MockICom : public ICom + { + public: + MOCK_METHOD(bool, open, (), (override)); + MOCK_METHOD(bool, close, (), (override)); + MOCK_METHOD(bool, isOpen, (), (const, override)); + MOCK_METHOD(void, read, (std::vector &data, size_t len), (override)); + MOCK_METHOD(void, write, (const std::vector &data), (override)); + }; +} // namespace com::mock diff --git a/sw/restatdesk_tests/com/test_mock_ilib.h b/sw/restatdesk_tests/com/test_mock_ilib.h new file mode 100644 index 0000000..d8ae32e --- /dev/null +++ b/sw/restatdesk_tests/com/test_mock_ilib.h @@ -0,0 +1,59 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_mock_ilib.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace com::mock +/// @brief Namespace for application communication mocks +namespace com::mock +{ + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using ILibSerialPort = Electux::App::Com::ILibSerialPort; + using BaudRate = Electux::App::Com::BaudRate; + using CharacterSize = Electux::App::Com::CharacterSize; + using Parity = Electux::App::Com::Parity; + using StopBits = Electux::App::Com::StopBits; + using FlowControl = Electux::App::Com::FlowControl; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class MockILibSerialPort + /// @brief Mock implementation of the ILibSerialPort interface for testing purposes. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class MockILibSerialPort : public ILibSerialPort + { + public: + MOCK_METHOD(void, Open, (const std::string &device), (override)); + MOCK_METHOD(void, Close, (), (override)); + MOCK_METHOD(bool, IsOpen, (), (const, override)); + MOCK_METHOD(void, Read, (std::vector &data, size_t len), (override)); + MOCK_METHOD(void, Write, (const std::vector &data), (override)); + MOCK_METHOD(void, SetBaudRate, (BaudRate baudRate), (override)); + MOCK_METHOD(void, SetCharacterSize, (CharacterSize characterSize), (override)); + MOCK_METHOD(void, SetParity, (Parity parity), (override)); + MOCK_METHOD(void, SetStopBits, (StopBits stopBits), (override)); + MOCK_METHOD(void, SetFlowControl, (FlowControl flowControl), (override)); + }; +} // namespace com::mock diff --git a/sw/restatdesk_tests/com/test_mock_iserial.h b/sw/restatdesk_tests/com/test_mock_iserial.h new file mode 100644 index 0000000..a15f580 --- /dev/null +++ b/sw/restatdesk_tests/com/test_mock_iserial.h @@ -0,0 +1,58 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_mock_iserial.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace com::mock +/// @brief Namespace for application communication mocks +namespace com::mock +{ + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using ISerial = Electux::App::Com::ISerial; + using SerialParams = Electux::App::Com::SerialParams; + using BaudRate = Electux::App::Com::BaudRate; + using CharacterSize = Electux::App::Com::CharacterSize; + using Parity = Electux::App::Com::Parity; + using StopBits = Electux::App::Com::StopBits; + using FlowControl = Electux::App::Com::FlowControl; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class MockISerial + /// @brief Mock implementation of the ISerial interface for testing purposes. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class MockISerial : public ISerial + { + public: + MOCK_METHOD(bool, setup, (const SerialParams ¶ms), (override)); + MOCK_METHOD(void, setDevice, (const std::string &device), (override)); + MOCK_METHOD(void, setBaudRate, (BaudRate baudRate), (override)); + MOCK_METHOD(void, setCharacterSize, (CharacterSize characterSize), (override)); + MOCK_METHOD(void, setParity, (Parity parity), (override)); + MOCK_METHOD(void, setStopBits, (StopBits stopBits), (override)); + MOCK_METHOD(void, setFlowControl, (FlowControl flowControl), (override)); + + }; +} // namespace com::mock diff --git a/sw/restatdesk_tests/com/test_serial_baude_rate.cc b/sw/restatdesk_tests/com/test_serial_baude_rate.cc new file mode 100644 index 0000000..b20237f --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_baude_rate.cc @@ -0,0 +1,89 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_baude_rate.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" +#include +#include + +using namespace Electux::App::Com; +using namespace Electux::App::Com::SerialComConstants; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test bidirectional conversion of all supported BaudRates. +/// +/// Iterates through provided parameters to verify that baudToUint and +/// uintToBaud mappings are consistent and correct based on serial_com_utils. +/// +/// @param BaudRateTest The name of the test case. +/// @param BaudRateConversionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_P(BaudRateTest, BaudRateConversionTest) +{ + ParameterMapping params = this->GetParam(); + + EXPECT_EQ(SerialUtils::baudToUint(params.enum_val), params.uint_val); + EXPECT_EQ(SerialUtils::uintToBaud(params.uint_val), params.enum_val); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief List of all supported baud rate mappings from serial_com_utils.cc. +/// +/// Note: Replace numeric values with actual constants if they differ. +/// +/// @param SerialComTest The name of the test suite. +/// @param BaudRateTest The name of the parameterized test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +INSTANTIATE_TEST_SUITE_P +( + SerialComTest, + BaudRateTest, + ::testing::Values + ( + ParameterMapping{BaudRate::BAUD_110, 0}, + ParameterMapping{BaudRate::BAUD_300, 1}, + ParameterMapping{BaudRate::BAUD_600, 2}, + ParameterMapping{BaudRate::BAUD_1200, 3}, + ParameterMapping{BaudRate::BAUD_2400, 4}, + ParameterMapping{BaudRate::BAUD_4800, 5}, + ParameterMapping{BaudRate::BAUD_9600, 6}, + ParameterMapping{BaudRate::BAUD_19200, 7}, + ParameterMapping{BaudRate::BAUD_38400, 8}, + ParameterMapping{BaudRate::BAUD_57600, 9}, + ParameterMapping{BaudRate::BAUD_115200, 10}, + ParameterMapping{BaudRate::BAUD_230400, 11} + ) +); + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test detection of invalid baud rate parameters. +/// +/// Verifies that the conversion logic correctly identifies unsupported +/// baud rates and returns the predefined invalid parameter constant or enum. +/// +/// @param SerialComTest The name of the test suite. +/// @param InvalidBaudRateDetectionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, InvalidBaudRateDetectionTest) +{ + uint32_t invalid_uint = SerialUtils::baudToUint(BaudRate::BAUD_INVALID); + EXPECT_EQ(invalid_uint, cComInvalidParameter); + + BaudRate invalid_enum = SerialUtils::uintToBaud(999999); + EXPECT_EQ(invalid_enum, BaudRate::BAUD_INVALID); +} diff --git a/sw/restatdesk_tests/com/test_serial_close.cc b/sw/restatdesk_tests/com/test_serial_close.cc new file mode 100644 index 0000000..349332b --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_close.cc @@ -0,0 +1,81 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_close.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_mock_icom.h" +#include "test_mock_ilib.h" +#include "test_serial_com.h" + +using namespace com::mock; +using namespace Electux::App::Com; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test closing the serial port connection. +/// +/// Verifies that the close operation correctly releases the system resources +/// associated with the serial device. +/// +/// @param SerialComTest The test fixture. +/// @param closeSerialPortTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, closeSerialPortTest) +{ + // TODO: Implement actual resource release verification + // Example: Check if file descriptor is -1 or invalid after close + EXPECT_EQ(true, true); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test closing the mock ICom interface. +/// +/// Verifies that the MockICom mock object correctly handles expectations for +/// open and close method calls. +/// +/// @param MockIComTest The test suite name. +/// @param CloseIComTest The test case name. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(MockIComTest, CloseIComTest) +{ + MockICom mockCom; + + EXPECT_CALL(mockCom, open()).WillOnce(::testing::Return(true)); + EXPECT_CALL(mockCom, close()).WillOnce(::testing::Return(true)); + + ASSERT_TRUE(mockCom.open()); + ASSERT_TRUE(mockCom.close()); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test closing the mock ILibSerialPort interface. +/// +/// Verifies that the MockILibSerialPort mock object correctly handles expectations +/// for Open and Close method calls. +/// +/// @param MockILibSerialPortTest The test suite name. +/// @param CloseILibSerialPortTest The test case name. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(MockILibSerialPortTest, CloseILibSerialPortTest) +{ + MockILibSerialPort mockPort; + + EXPECT_CALL(mockPort, Open("/dev/ttyS0")); + EXPECT_CALL(mockPort, Close()); + + mockPort.Open("/dev/ttyS0"); + mockPort.Close(); +} diff --git a/sw/restatdesk_tests/com/test_serial_com.h b/sw/restatdesk_tests/com/test_serial_com.h new file mode 100644 index 0000000..dbbc9b2 --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_com.h @@ -0,0 +1,111 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_com.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Com +/// @brief Namespace for serial communication and related unit tests +namespace Electux::App::Com +{ + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SerialComProxy + /// @brief Proxy class to expose protected SerialCom methods for testing. + /// + /// This class uses inheritance to promote internal conversion methods + /// to public visibility, allowing GoogleTest to verify the accuracy + /// of parameter mappings (baud, parity, etc.). + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SerialComProxy : public SerialCom + { + public: + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SerialComTest + /// @brief Test fixture for SerialCom class. + /// + /// Provides a controlled environment and instance of SerialComProxy + /// to perform unit testing on serial communication logic. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class SerialComTest : public ::testing::Test + { + protected: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using SerialCom = Electux::App::Com::SerialComProxy; + using BaudRate = Electux::App::Com::BaudRate; + using CharacterSize = Electux::App::Com::CharacterSize; + using Parity = Electux::App::Com::Parity; + using StopBits = Electux::App::Com::StopBits; + using FlowControl = Electux::App::Com::FlowControl; + using SerialParams = Electux::App::Com::SerialParams; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief The instance being tested (SerialComProxy). + //////////////////////////////////////////////////////////////////////////////////////////////// + SerialCom m_serial{}; + + void SetUp() override + { + + } + + void TearDown() override + { + + } + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @struct ParameterMapping + /// @brief Structure to hold enum and corresponding uint32_t values for testing. + //////////////////////////////////////////////////////////////////////////////////////////////////// + template + struct ParameterMapping + { + T enum_val; + uint32_t uint_val; + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class SerialParamTest + /// @brief Base parameterized test class for all serial parameters. + //////////////////////////////////////////////////////////////////////////////////////////////////// + template + class SerialParamTest : public SerialComTest, + public ::testing::WithParamInterface> + { + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Type aliases for specific parameter tests to improve readability in test cases. + //////////////////////////////////////////////////////////////////////////////////////////////////// + using BaudRateTest = SerialParamTest; + using DataBitsTest = SerialParamTest; + using ParityTest = SerialParamTest; + using StopBitsTest = SerialParamTest; + using FlowControlTest = SerialParamTest; +} // namespace Electux::App::Com diff --git a/sw/restatdesk_tests/com/test_serial_data_bits.cc b/sw/restatdesk_tests/com/test_serial_data_bits.cc new file mode 100644 index 0000000..e667d9a --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_data_bits.cc @@ -0,0 +1,83 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_data_bits.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" +#include +#include + +using namespace Electux::App::Com; +using namespace Electux::App::Com::SerialComConstants; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test bidirectional conversion of all supported Character sizes. +/// +/// This parameterized test iterates through all valid Data Bits mappings to +/// ensure that the internal conversion logic (enum to uint and vice versa) +/// is consistent and matches the expected system constants. +/// +/// @param DataBitsTest The name of the test case. +/// @param DataBitsConversionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_P(DataBitsTest, DataBitsConversionTest) +{ + const ParameterMapping params = this->GetParam(); + + EXPECT_EQ(SerialUtils::dataBitsToUint(params.enum_val), params.uint_val); + EXPECT_EQ(SerialUtils::uintToDataBits(params.uint_val), params.enum_val); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Define the test suite instance with all supported data bits values. +/// +/// These values correspond to the switch-case logic found in serial_com_utils.cc. +/// +/// @param SerialComTest The name of the test suite. +/// @param DataBitsTest The name of the parameterized test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +INSTANTIATE_TEST_SUITE_P +( + SerialComTest, + DataBitsTest, + ::testing::Values + ( + ParameterMapping{CharacterSize::CHAR_SIZE_5, 0}, + ParameterMapping{CharacterSize::CHAR_SIZE_6, 1}, + ParameterMapping{CharacterSize::CHAR_SIZE_7, 2}, + ParameterMapping{CharacterSize::CHAR_SIZE_8, 3} + ) +); + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test detection of invalid data bits parameters. +/// +/// Verifies that the conversion logic correctly identifies unsupported +/// character sizes (outside the 5-8 range) and returns the predefined +/// invalid parameter constant or enum. +/// +/// @param SerialComTest The name of the test suite. +/// @param InvalidDataBitsDetectionTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, InvalidDataBitsDetectionTest) +{ + uint32_t invalid_uint = SerialUtils::dataBitsToUint(CharacterSize::CHAR_SIZE_INVALID); + EXPECT_EQ(invalid_uint, cComInvalidParameter); + + CharacterSize invalid_enum = SerialUtils::uintToDataBits(9); + EXPECT_EQ(invalid_enum, CharacterSize::CHAR_SIZE_INVALID); +} diff --git a/sw/restatdesk_tests/com/test_serial_flow_control.cc b/sw/restatdesk_tests/com/test_serial_flow_control.cc new file mode 100644 index 0000000..4541b54 --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_flow_control.cc @@ -0,0 +1,82 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_flow_control.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" +#include +#include + +using namespace Electux::App::Com; +using namespace Electux::App::Com::SerialComConstants; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test bidirectional conversion of all supported Flow Control modes. +/// +/// This parameterized test iterates through all valid Flow Control mappings +/// to ensure that the internal conversion logic (enum to uint and vice versa) +/// is consistent and matches the expected system constants. +/// +/// @param FlowControlTest The name of the test case. +/// @param FlowControlConversionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_P(FlowControlTest, FlowControlConversionTest) +{ + const ParameterMapping params = this->GetParam(); + + EXPECT_EQ(SerialUtils::flowControlToUint(params.enum_val), params.uint_val); + EXPECT_EQ(SerialUtils::uintToFlowControl(params.uint_val), params.enum_val); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Define the test suite instance with all supported flow control values. +/// +/// These values correspond to the switch-case logic found in serial_com_utils.cc. +/// +/// @param SerialComTest The name of the test suite. +/// @param FlowControlTest The name of the parameterized test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +INSTANTIATE_TEST_SUITE_P +( + SerialComTest, + FlowControlTest, + ::testing::Values + ( + ParameterMapping{FlowControl::FLOW_CONTROL_NONE, 0}, + ParameterMapping{FlowControl::FLOW_CONTROL_HARDWARE, 1}, + ParameterMapping{FlowControl::FLOW_CONTROL_SOFTWARE, 2} + ) +); + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test detection of invalid flow control parameters. +/// +/// Verifies that the conversion logic correctly identifies unsupported +/// flow control modes and returns the predefined invalid parameter +/// constant or enum. +/// +/// @param SerialComTest The name of the test suite. +/// @param InvalidFlowControlDetectionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, InvalidFlowControlDetectionTest) +{ + uint32_t invalid_uint = SerialUtils::flowControlToUint(FlowControl::FLOW_CONTROL_INVALID); + EXPECT_EQ(invalid_uint, cComInvalidParameter); + + FlowControl invalid_enum = SerialUtils::uintToFlowControl(9); + EXPECT_EQ(invalid_enum, FlowControl::FLOW_CONTROL_INVALID); +} diff --git a/sw/restatdesk_tests/com/test_serial_open.cc b/sw/restatdesk_tests/com/test_serial_open.cc new file mode 100644 index 0000000..e00a7ec --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_open.cc @@ -0,0 +1,57 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_open.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" + +using namespace Electux::App::Com; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test opening the serial port connection. +/// +/// Ensure that the class handles missing device path gracefully by returning false. +/// +/// @param SerialComTest The test fixture. +/// @param OpenSerialPortTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, OpenSerialPortTest) +{ + EXPECT_FALSE(m_serial.open()); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test opening a non-existent serial port. +/// +/// Ensures that the class handles invalid device paths gracefully by returning false. +/// +/// @param SerialComTest The test fixture. +/// @param OpenInvalidPortTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, OpenInvalidPortTest) +{ + SerialParams bad_params = + { + .device = "/dev/non_existent_device_999", + .baud = BaudRate::BAUD_9600 + }; + + m_serial.setup(bad_params); + + EXPECT_FALSE(m_serial.open()); +} + diff --git a/sw/restatdesk_tests/com/test_serial_parity.cc b/sw/restatdesk_tests/com/test_serial_parity.cc new file mode 100644 index 0000000..eac1623 --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_parity.cc @@ -0,0 +1,82 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_parity.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" +#include +#include + +using namespace Electux::App::Com; +using namespace Electux::App::Com::SerialComConstants; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test bidirectional conversion of all supported Parity modes. +/// +/// This parameterized test iterates through all valid Parity mappings to +/// ensure that the internal conversion logic (enum to uint and vice versa) +/// is consistent and matches the expected system constants. +/// +/// @param ParityTest The name of the test case. +/// @param ParityConversionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_P(ParityTest, ParityConversionTest) +{ + const ParameterMapping params = this->GetParam(); + + EXPECT_EQ(SerialUtils::parityToUint(params.enum_val), params.uint_val); + EXPECT_EQ(SerialUtils::uintToParity(params.uint_val), params.enum_val); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Define the test suite instance with all supported parity values. +/// +/// These values correspond to the switch-case logic found in serial_com_utils.cc. +/// +/// @param SerialComTest The name of the test suite. +/// @param ParityTest The name of the parameterized test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +INSTANTIATE_TEST_SUITE_P +( + SerialComTest, + ParityTest, + ::testing::Values + ( + ParameterMapping{Parity::PARITY_NONE, 2}, + ParameterMapping{Parity::PARITY_ODD, 1}, + ParameterMapping{Parity::PARITY_EVEN, 0} + ) +); + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test detection of invalid parity parameters. +/// +/// Verifies that the conversion logic correctly identifies unsupported +/// parity modes and returns the predefined invalid parameter +/// constant or enum. +/// +/// @param SerialComTest The name of the test suite. +/// @param InvalidParityDetectionTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, InvalidParityDetectionTest) +{ + uint32_t invalid_uint = SerialUtils::parityToUint(Parity::PARITY_INVALID); + EXPECT_EQ(invalid_uint, cComInvalidParameter); + + Parity invalid_enum = SerialUtils::uintToParity(9); + EXPECT_EQ(invalid_enum, Parity::PARITY_INVALID); +} diff --git a/sw/restatdesk_tests/com/test_serial_read.cc b/sw/restatdesk_tests/com/test_serial_read.cc new file mode 100644 index 0000000..7c1708d --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_read.cc @@ -0,0 +1,39 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_read.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" + +using namespace Electux::App::Com; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test reading from a closed serial port. +/// +/// Verifies that attempting to read from a serial port that has not been +/// opened does not cause a crash and leaves the data buffer unchanged. +/// +/// @param SerialComTest The test fixture. +/// @param ReadFromPortTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, ReadFromPortTest) +{ + std::vector buffer; + + EXPECT_NO_THROW(m_serial.read(buffer, 10)); + EXPECT_TRUE(buffer.empty()); +} diff --git a/sw/restatdesk_tests/com/test_serial_setup.cc b/sw/restatdesk_tests/com/test_serial_setup.cc new file mode 100644 index 0000000..a271a60 --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_setup.cc @@ -0,0 +1,99 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_setup.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_mock_iserial.h" +#include "test_serial_com.h" + +using namespace com::mock; +using namespace Electux::App::Com; +using ::testing::_; +using ::testing::Return; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test setting the device path via the mock interface. +/// +/// Verifies that setDevice correctly receives the path string and that the mock +/// records the call as expected. +/// +/// @param MockISerialTest The test suite name for MockISerial. +/// @param SetDeviceTest The specific name of this test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(MockISerialTest, SetDeviceTest) +{ + MockISerial mockSerial; + const std::string devicePath = "/dev/ttyUSB0"; + + EXPECT_CALL(mockSerial, setDevice(devicePath)).Times(1); + + mockSerial.setDevice(devicePath); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the setup process using a mock serial interface. +/// +/// This test verifies that the setup method is correctly invoked on the ISerial +/// interface with the expected parameters. It uses GoogleMock to simulate a +/// successful configuration, ensuring the software logic correctly handles the +/// return state without requiring physical hardware access. +/// +/// @param MockISerialTest The test suite name for MockISerial. +/// @param SetupTest The specific name of this test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(MockISerialTest, SetupTest) +{ + MockISerial mockSerial; + SerialParams params{ + "/dev/ttyS0", + BaudRate::BAUD_9600, + CharacterSize::CHAR_SIZE_8, + Parity::PARITY_NONE, + StopBits::STOP_BITS_1, + FlowControl::FLOW_CONTROL_NONE + }; + + // Set expectation that setup() will be called once with any SerialParams and return true + EXPECT_CALL(mockSerial, setup(_)).WillOnce(Return(true)); + + // Perform the assertion + ASSERT_TRUE(mockSerial.setup(params)); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test multiple configuration calls in sequence. +/// +/// Validates that the interface can handle a series of configuration updates +/// in a specific order. +/// +/// @param MockISerialTest The test suite name. +/// @param SequentialConfigTest The test case name. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(MockISerialTest, SequentialConfigTest) +{ + MockISerial mockSerial; + + ::testing::InSequence seq; // Forces the order of expectations + + EXPECT_CALL(mockSerial, setBaudRate(BaudRate::BAUD_57600)).Times(1); + EXPECT_CALL(mockSerial, setParity(Parity::PARITY_EVEN)).Times(1); + EXPECT_CALL(mockSerial, setFlowControl(FlowControl::FLOW_CONTROL_HARDWARE)).Times(1); + + mockSerial.setBaudRate(BaudRate::BAUD_57600); + mockSerial.setParity(Parity::PARITY_EVEN); + mockSerial.setFlowControl(FlowControl::FLOW_CONTROL_HARDWARE); +} diff --git a/sw/restatdesk_tests/com/test_serial_stop_bits.cc b/sw/restatdesk_tests/com/test_serial_stop_bits.cc new file mode 100644 index 0000000..f94123d --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_stop_bits.cc @@ -0,0 +1,81 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_stop_bits.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" +#include +#include + +using namespace Electux::App::Com; +using namespace Electux::App::Com::SerialComConstants; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test bidirectional conversion of all supported Stop Bits. +/// +/// This parameterized test iterates through all valid Stop Bits mappings to +/// ensure that the internal conversion logic (enum to uint and vice versa) +/// is consistent and matches the expected system constants. +/// +/// @param StopBitsTest The name of the test case. +/// @param StopBitsConversionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_P(StopBitsTest, StopBitsConversionTest) +{ + const ParameterMapping params = this->GetParam(); + + EXPECT_EQ(SerialUtils::stopBitsToUint(params.enum_val), params.uint_val); + EXPECT_EQ(SerialUtils::uintToStopBits(params.uint_val), params.enum_val); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Define the test suite instance with all supported stop bits values. +/// +/// These values correspond to the switch-case logic found in serial_com_utils.cc. +/// +/// @param SerialComTest The name of the test suite. +/// @param StopBitsTest The name of the parameterized test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +INSTANTIATE_TEST_SUITE_P +( + SerialComTest, + StopBitsTest, + ::testing::Values + ( + ParameterMapping{StopBits::STOP_BITS_1, 0}, + ParameterMapping{StopBits::STOP_BITS_2, 1} + ) +); + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test detection of invalid stop bits parameters. +/// +/// Verifies that the conversion logic correctly identifies unsupported +/// stop bits settings and returns the predefined invalid parameter +/// constant or enum. +/// +/// @param SerialComTest The name of the test suite. +/// @param InvalidStopBitsDetectionTest The name of the test. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, InvalidStopBitsDetectionTest) +{ + uint32_t invalid_uint = SerialUtils::stopBitsToUint(StopBits::STOP_BITS_INVALID); + EXPECT_EQ(invalid_uint, cComInvalidParameter); + + StopBits invalid_enum = SerialUtils::uintToStopBits(9); + EXPECT_EQ(invalid_enum, StopBits::STOP_BITS_INVALID); +} diff --git a/sw/restatdesk_tests/com/test_serial_write.cc b/sw/restatdesk_tests/com/test_serial_write.cc new file mode 100644 index 0000000..959f617 --- /dev/null +++ b/sw/restatdesk_tests/com/test_serial_write.cc @@ -0,0 +1,38 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_serial_write.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_serial_com.h" + +using namespace Electux::App::Com; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test writing to a closed serial port. +/// +/// Verifies that attempting to write to a serial port that has not been +/// opened does not cause a crash. +/// +/// @param SerialComTest The test fixture. +/// @param WriteToPortTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(SerialComTest, WriteToPortTest) +{ + const std::vector data_to_write = {0xDE, 0xAD, 0xBE, 0xEF}; + + EXPECT_NO_THROW(m_serial.write(data_to_write)); +} diff --git a/sw/restatdesk_tests/config/.editorconfig b/sw/restatdesk_tests/config/.editorconfig new file mode 100644 index 0000000..72716a4 --- /dev/null +++ b/sw/restatdesk_tests/config/.editorconfig @@ -0,0 +1,3 @@ +[**.*] +indent_style = tab +tab_width = 4 diff --git a/sw/restatdesk_tests/config/mock_config.h b/sw/restatdesk_tests/config/mock_config.h new file mode 100644 index 0000000..4ed8537 --- /dev/null +++ b/sw/restatdesk_tests/config/mock_config.h @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// mock_config.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Config +/// @brief Namespace for application configuration management +namespace Electux::App::Config +{ + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using Model = Electux::App::Model::Model; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class MockConfig + /// @brief Mock implementation of the IConfig interface. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class MockConfig : public IConfig + { + public: + MOCK_METHOD(void, init, (), (override)); + MOCK_METHOD(bool, load, (), (override)); + MOCK_METHOD(bool, store, (), (override)); + MOCK_METHOD(void, setConfig, (const Model& config), (override)); + MOCK_METHOD(const Model&, getConfig, (), (const, override)); + }; +} // namespace Electux::App::Config diff --git a/sw/restatdesk_tests/config/pack.cmake b/sw/restatdesk_tests/config/pack.cmake new file mode 100644 index 0000000..9e3833a --- /dev/null +++ b/sw/restatdesk_tests/config/pack.cmake @@ -0,0 +1,26 @@ +# +# @brief restatdesk_tests list of all sources and unit tests for config +# @version v1.0.3 +# @date Tue Sep 19 08:55:54 PM CEST 2023 +# @author Vladimir Roncevic +# + +set( + RESTAT_CONFIG_HEADERS + ${PROJECT_SOURCE_DIR}/../restatdesk/ +) + +set( + RESTAT_CONFIG_SOURCES + ${PROJECT_SOURCE_DIR}/../restatdesk/config/config_manager.cc + ${PROJECT_SOURCE_DIR}/../restatdesk/config/config_manager_utils.cc +) + +set( + RESTAT_CONFIG_TESTS + ${PROJECT_SOURCE_DIR}/config/test_config_control.cc + ${PROJECT_SOURCE_DIR}/config/test_config_log.cc + ${PROJECT_SOURCE_DIR}/config/test_config_serial.cc + ${PROJECT_SOURCE_DIR}/config/test_config_load.cc + ${PROJECT_SOURCE_DIR}/config/test_config_store.cc +) diff --git a/sw/restatdesk_tests/config/test_config.h b/sw/restatdesk_tests/config/test_config.h new file mode 100644 index 0000000..a6aba40 --- /dev/null +++ b/sw/restatdesk_tests/config/test_config.h @@ -0,0 +1,97 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_config.h +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @namespace Electux::App::Config +/// @brief Namespace for application configuration management and unit tests +namespace Electux::App::Config +{ + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ConfigManagerProxy + /// @brief Proxy class to expose protected ConfigManager methods for testing. + /// + /// Uses inheritance to promote internal configuration storage and default + /// setup methods to public visibility, enabling GoogleTest to verify + /// internal state and data integrity. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ConfigManagerProxy : public ConfigManager + { + public: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Constructor that initializes ConfigManager with a file name. + /// @param fileName The name of the configuration file. + //////////////////////////////////////////////////////////////////////////////////////////////// + explicit ConfigManagerProxy(const std::string &fileName) + : ConfigManager(Electux::App::Model::createDefault(), fileName) {} + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Promoting protected methods to public for unit testing. + //////////////////////////////////////////////////////////////////////////////////////////////// + using ConfigManager::defaultConfigStore; + }; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + /// @class ConfigManagerTest + /// @brief Fixture for ConfigManager unit tests. + /// + /// Provides a controlled environment for testing configuration management, + /// including automated setup and cleanup of temporary test files. + //////////////////////////////////////////////////////////////////////////////////////////////////// + class ConfigManagerTest : public ::testing::Test + { + protected: + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Local Type Aliases + /// @{ + using ConfigManager = Electux::App::Config::ConfigManagerProxy; + using ModelControlKey = Electux::App::Model::ModelControlKey; + using ModelLogKey = Electux::App::Model::ModelLogKey; + using ModelSerialKey = Electux::App::Model::ModelSerialKey; + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////////////////////////// + /// @name Test Environment Members + /// @{ + std::unique_ptr m_config; ///< ConfigManagerProxy instance + const std::string m_testConfigFileName = "test_config"; ///< Test file name + /// @} + //////////////////////////////////////////////////////////////////////////////////////////////// + + void SetUp() override + { + m_config = std::make_unique(m_testConfigFileName); + } + + void TearDown() override + { + if (std::filesystem::exists(m_testConfigFileName)) + { + std::filesystem::remove(m_testConfigFileName); + } + } + }; +} // namespace Electux::App::Config diff --git a/sw/restatdesk_tests/config/test_config_control.cc b/sw/restatdesk_tests/config/test_config_control.cc new file mode 100644 index 0000000..1953e57 --- /dev/null +++ b/sw/restatdesk_tests/config/test_config_control.cc @@ -0,0 +1,46 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_config_control.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_config.h" + +using namespace Electux::App::Model; +using namespace Electux::App::Config; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the control configuration functionality of ConfigManager. +/// +/// Verifies that the configuration manager correctly loads and retrieves +/// control-related parameters, ensuring that keys like 'Enable' and 'Timer' +/// match the expected default values. +/// +/// @param ConfigManagerTest The test fixture. +/// @param ControlConfigTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, ControlConfigTest) +{ + m_config->init(); + m_config->load(); + const auto& control = m_config->getConfig(); + + auto enableKey = control.toString(ModelControlKey::Enable); + auto timerKey = control.toString(ModelControlKey::Timer); + + EXPECT_EQ(control.getEntity(enableKey), "false false false false false false false false"); + EXPECT_EQ(control.getEntity(timerKey), "0 0 0 0 0 0 0 0"); +} diff --git a/sw/restatdesk_tests/config/test_config_load.cc b/sw/restatdesk_tests/config/test_config_load.cc new file mode 100644 index 0000000..08ec622 --- /dev/null +++ b/sw/restatdesk_tests/config/test_config_load.cc @@ -0,0 +1,104 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_config_load.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include "test_config.h" + +using namespace Electux::App::Config; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the load functionality of ConfigManager. +/// +/// Verifies that the configuration manager can successfully open, read, +/// and parse an existing configuration file from the filesystem, ensuring +/// data integrity for the 'device' parameter. +/// +/// @param ConfigManagerTest The test fixture. +/// @param LoadConfigTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, LoadConfigTest) +{ + // Create a dummy config file for testing load + std::ofstream ofs(m_testConfigFileName); + ofs << "device=/dev/ttyUSB0\n"; + ofs.close(); + + m_config->init(); + bool success = m_config->load(); + EXPECT_TRUE(success); + + const auto& serial = m_config->getConfig(); + auto deviceKey = serial.toString(ModelSerialKey::Device); + + EXPECT_EQ(serial.getEntity(deviceKey), "/dev/ttyUSB0"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test behavior when the configuration file is missing. +/// +/// Verifies that if the file does not exist, load() returns true (because it +/// creates a default one) and populates the models with default values. +/// +/// @param ConfigManagerTest The test fixture. +/// @param MissingFileLoadDefaultsTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, MissingFileLoadDefaultsTest) +{ + // Ensure file does not exist + if (std::filesystem::exists(m_testConfigFileName)) { + std::filesystem::remove(m_testConfigFileName); + } + + // load() should call defaultConfigStore() and return true + m_config->init(); + EXPECT_TRUE(m_config->load()); + EXPECT_TRUE(std::filesystem::exists(m_testConfigFileName)); + + // Verify a default value was set + const auto& serial = m_config->getConfig(); + auto deviceKey = serial.toString(ModelSerialKey::Device); + EXPECT_EQ(serial.getEntity(deviceKey), "/dev/ttyUSB0"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test parsing of malformed lines, comments, and empty spaces. +/// +/// Verifies that the load() method can handle various edge cases in the config +/// file, such as comments, empty lines, and malformed entries, without crashing or +/// failing to load valid entries correctly. +/// +/// @param ConfigManagerTest The test fixture. +/// @param ParsingEdgeCasesTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, ParsingEdgeCasesTest) +{ + { + std::ofstream ofs(m_testConfigFileName); + ofs << "# This is a comment\n"; + ofs << " \n"; // Empty line with spaces + ofs << "invalid_line_no_delimiter\n"; + ofs << "valid_key=valid_value\n"; + ofs.close(); + } + + m_config->init(); + EXPECT_TRUE(m_config->load()); + // Verification is implicit: if parser crashes or fails on malformed lines, + // the test fails. +} diff --git a/sw/restatdesk_tests/config/test_config_log.cc b/sw/restatdesk_tests/config/test_config_log.cc new file mode 100644 index 0000000..45c97e6 --- /dev/null +++ b/sw/restatdesk_tests/config/test_config_log.cc @@ -0,0 +1,46 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_config_log.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_config.h" + +using namespace Electux::App::Model; +using namespace Electux::App::Config; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the log configuration functionality of ConfigManager. +/// +/// Verifies that the configuration manager correctly loads and retrieves +/// logging parameters, ensuring that the log file path is defined and +/// the default log level is set to 'Info'. +/// +/// @param ConfigManagerTest The test fixture. +/// @param LogConfigTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, LogConfigTest) +{ + m_config->init(); + m_config->load(); + const auto& logCfg = m_config->getConfig(); + + auto filePathKey = logCfg.toString(ModelLogKey::FilePath); + auto logLevelKey = logCfg.toString(ModelLogKey::LogLevel); + + EXPECT_FALSE(logCfg.getEntity(filePathKey).empty()); + EXPECT_EQ(logCfg.getEntity(logLevelKey), "2"); +} diff --git a/sw/restatdesk_tests/config/test_config_serial.cc b/sw/restatdesk_tests/config/test_config_serial.cc new file mode 100644 index 0000000..e3b12db --- /dev/null +++ b/sw/restatdesk_tests/config/test_config_serial.cc @@ -0,0 +1,48 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_config_serial.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "test_config.h" + +using namespace Electux::App::Model; +using namespace Electux::App::Config; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the serial configuration functionality of ConfigManager. +/// +/// Verifies that the configuration manager correctly loads and retrieves +/// serial communication parameters, ensuring that device path, baud rate, +/// and data bits match the expected system defaults. +/// +/// @param ConfigManagerTest The test fixture. +/// @param SerialConfigTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, SerialConfigTest) +{ + m_config->init(); + m_config->load(); + const auto& serial = m_config->getConfig(); + + auto deviceKey = serial.toString(ModelSerialKey::Device); + auto baudKey = serial.toString(ModelSerialKey::Baud); + auto dataKey = serial.toString(ModelSerialKey::Data); + + EXPECT_EQ(serial.getEntity(deviceKey), "/dev/ttyUSB0"); + EXPECT_EQ(serial.getEntity(baudKey), "10"); + EXPECT_EQ(serial.getEntity(dataKey), "3"); +} diff --git a/sw/restatdesk_tests/config/test_config_store.cc b/sw/restatdesk_tests/config/test_config_store.cc new file mode 100644 index 0000000..62f08a6 --- /dev/null +++ b/sw/restatdesk_tests/config/test_config_store.cc @@ -0,0 +1,138 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_config_store.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include +#include "test_config.h" + +using namespace Electux::App::Config; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the storage functionality of ConfigManager. +/// +/// Verifies that the configuration manager can successfully serialize internal +/// settings and write them to a file. Checks for file creation and ensures +/// that the resulting file contains data. +/// +/// @param ConfigManagerTest The test fixture. +/// @param StoreConfigTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, StoreConfigTest) +{ + bool success = m_config->store(); + + EXPECT_TRUE(success); + EXPECT_TRUE(std::filesystem::exists(m_testConfigFileName)); + EXPECT_GT(std::filesystem::file_size(m_testConfigFileName), 0); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test store functionality when file permissions prevent writing. +/// +/// Creates a temporary configuration file, removes write permissions, and verifies +/// that the store() method fails gracefully without crashing. Restores permissions +/// afterward to allow cleanup. +/// +/// @param ConfigManagerTest The test fixture. +/// @param StoreFailureTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, StoreFailureTest) +{ + // Create a dummy file and remove write permissions + { + std::ofstream ofs(m_testConfigFileName); + ofs << "data=1\n"; + } + + chmod(m_testConfigFileName.c_str(), S_IRUSR); // Read only + + EXPECT_FALSE(m_config->store()); + + chmod(m_testConfigFileName.c_str(), S_IWUSR | S_IRUSR); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test that defaultConfigStore resets values to defaults. +/// +/// Creates a temporary configuration file, removes write permissions, and verifies +/// that the store() method fails gracefully without crashing. Restores permissions +/// afterward to allow cleanup. +/// +/// @param ConfigManagerTest The test fixture. +/// @param ExplicitDefaultStoreTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, ExplicitDefaultStoreTest) +{ + m_config->init(); + auto serial = m_config->getConfig().clone(); + const auto deviceKey = serial->toString(ModelSerialKey::Device); + + serial->add(deviceKey, "/dev/custom_path"); + m_config->defaultConfigStore(); + + EXPECT_EQ(m_config->getConfig().getEntity(deviceKey), "/dev/ttyUSB0"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the setConfig functionality. +/// +/// Verifies that the setConfig method correctly updates the internal configuration model. +/// +/// @param ConfigManagerTest The test fixture. +/// @param SetConfigTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, SetConfigTest) +{ + m_config->init(); + auto config = m_config->getConfig().clone(); + auto key = config->toString(ModelSerialKey::Baud); + config->update(key, "9600"); + + m_config->setConfig(*config); + + EXPECT_EQ(m_config->getConfig().getEntity(key), "9600"); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the store and reload functionality. +/// +/// Verifies that data set via setConfig is correctly stored to disk and can be +/// reloaded, ensuring data persistence integrity. +/// +/// @param ConfigManagerTest The test fixture. +/// @param StoreAndReloadTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST_F(ConfigManagerTest, StoreAndReloadTest) +{ + m_config->init(); + auto config = m_config->getConfig().clone(); + auto key = config->toString(ModelSerialKey::Baud); + config->update(key, "115200"); + m_config->setConfig(*config); + + ASSERT_TRUE(m_config->store()); + + // Modify memory to ensure we are reading from file + config->update(key, "0"); + m_config->setConfig(*config); + EXPECT_EQ(m_config->getConfig().getEntity(key), "0"); + + // Reload from file + ASSERT_TRUE(m_config->load()); + EXPECT_EQ(m_config->getConfig().getEntity(key), "115200"); +} diff --git a/sw/restatdesk_tests/config/test_mock_config_failure.cc b/sw/restatdesk_tests/config/test_mock_config_failure.cc new file mode 100644 index 0000000..a3bffd3 --- /dev/null +++ b/sw/restatdesk_tests/config/test_mock_config_failure.cc @@ -0,0 +1,110 @@ +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// test_mock_config_failure.cc +/// Copyright (C) 2025 - 2026 Vladimir Roncevic +/// +/// restatdesk is free software: you can redistribute it and/or modify it +/// under the terms of the GNU General Public License as published by the +/// Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// restatdesk 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 General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License along +/// with this program. If not, see . +//////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "mock_config.h" +#include +#include + +using namespace Electux::App::Config; +using namespace Electux::App::Model; + +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::_; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief A hypothetical component that relies on IConfig. +/// +/// This class demonstrates how to test interaction with the Config interface +/// using a mock object, specifically for error handling scenarios. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +class ConfigConsumer +{ +public: + explicit ConfigConsumer(IConfig& config) : m_config(config) {} + + bool initializeApp(const std::string& configPath) + { + // Attempt to load configuration + if (!m_config.load()) + { + // Unhappy flow: Configuration failed to load + return false; + } + + // Attempt to retrieve a critical setting + auto &model = m_config.getConfig(); + + if (model.getAllEntries().empty()) + { + // Unhappy flow: Critical setting missing + return false; + } + + return true; + } + +private: + IConfig& m_config; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the unhappy flow where configuration loading fails. +/// +/// Verifies that the consumer handles the load failure gracefully. +/// +/// @param MockConfigTest The test fixture. +/// @param LoadFailureHandlingTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(MockConfigTest, LoadFailureHandlingTest) +{ + MockConfig mockConfig; + ConfigConsumer consumer(mockConfig); + + // Expectation: load() is called and returns false + EXPECT_CALL(mockConfig, load()).WillOnce(Return(false)); + + // Expectation: getString() should NOT be called if load fails + EXPECT_CALL(mockConfig, getConfig()).Times(0); + + // Verify the result + EXPECT_FALSE(consumer.initializeApp("/path/to/config.json")); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Test the unhappy flow where a critical configuration key is missing. +/// +/// Verifies that the consumer handles missing keys gracefully after a successful load. +/// +/// @param MockConfigTest The test fixture. +/// @param MissingKeyHandlingTest The name of the test case. +//////////////////////////////////////////////////////////////////////////////////////////////////////// +TEST(MockConfigTest, MissingKeyHandlingTest) +{ + MockConfig mockConfig; + ConfigConsumer consumer(mockConfig); + + EXPECT_CALL(mockConfig, load()).WillOnce(Return(true)); + + Model emptyModel; + EXPECT_CALL(mockConfig, getConfig()).WillOnce(ReturnRef(emptyModel)); + + // Verify the result + EXPECT_FALSE(consumer.initializeApp("/path/to/config.json")); +} diff --git a/sw/restatdesk_tests/googletest/.clang-format b/sw/restatdesk_tests/googletest/.clang-format new file mode 100644 index 0000000..5b9bfe6 --- /dev/null +++ b/sw/restatdesk_tests/googletest/.clang-format @@ -0,0 +1,4 @@ +# Run manually to reformat a file: +# clang-format -i --style=file +Language: Cpp +BasedOnStyle: Google diff --git a/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/00-bug_report.yml b/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/00-bug_report.yml new file mode 100644 index 0000000..586779a --- /dev/null +++ b/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/00-bug_report.yml @@ -0,0 +1,53 @@ +name: Bug Report +description: Let us know that something does not work as expected. +title: "[Bug]: Please title this bug report" +body: + - type: textarea + id: what-happened + attributes: + label: Describe the issue + description: What happened, and what did you expect to happen? + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce the problem + description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful. + validations: + required: true + - type: textarea + id: version + attributes: + label: What version of GoogleTest are you using? + description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using. + validations: + required: true + - type: textarea + id: os + attributes: + label: What operating system and version are you using? + description: If you are using a Linux distribution please include the name and version of the distribution as well. + validations: + required: true + - type: textarea + id: compiler + attributes: + label: What compiler and version are you using? + description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler. + validations: + required: true + - type: textarea + id: buildsystem + attributes: + label: What build system are you using? + description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system. + validations: + required: true + - type: textarea + id: additional + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/10-feature_request.yml b/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/10-feature_request.yml new file mode 100644 index 0000000..f3bbc09 --- /dev/null +++ b/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/10-feature_request.yml @@ -0,0 +1,33 @@ +name: Feature request +description: Propose a new feature. +title: "[FR]: Please title this feature request" +labels: "enhancement" +body: + - type: textarea + id: version + attributes: + label: Does the feature exist in the most recent commit? + description: We recommend using the latest commit from GitHub in your projects. + validations: + required: true + - type: textarea + id: why + attributes: + label: Why do we need this feature? + description: Ideally, explain why a combination of existing features cannot be used instead. + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Describe the proposal. + description: Include a detailed description of the feature, with usage examples. + validations: + required: true + - type: textarea + id: platform + attributes: + label: Is the feature specific to an operating system, compiler, or build system version? + description: If it is, please specify which versions. + validations: + required: true diff --git a/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/config.yml b/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..65170d1 --- /dev/null +++ b/sw/restatdesk_tests/googletest/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Get Help + url: https://github.com/google/googletest/discussions + about: Please ask and answer questions here. diff --git a/sw/restatdesk_tests/googletest/.gitignore b/sw/restatdesk_tests/googletest/.gitignore new file mode 100644 index 0000000..f0df39d --- /dev/null +++ b/sw/restatdesk_tests/googletest/.gitignore @@ -0,0 +1,89 @@ +# Ignore CI build directory +build/ +xcuserdata +cmake-build-debug/ +.idea/ +bazel-bin +bazel-genfiles +bazel-googletest +bazel-out +bazel-testlogs +MODULE.bazel.lock +# python +*.pyc + +# Visual Studio files +.vs +*.sdf +*.opensdf +*.VC.opendb +*.suo +*.user +_ReSharper.Caches/ +Win32-Debug/ +Win32-Release/ +x64-Debug/ +x64-Release/ + +# VSCode files +.cache/ +cmake-variants.yaml + +# Ignore autoconf / automake files +Makefile.in +aclocal.m4 +configure +build-aux/ +autom4te.cache/ +googletest/m4/libtool.m4 +googletest/m4/ltoptions.m4 +googletest/m4/ltsugar.m4 +googletest/m4/ltversion.m4 +googletest/m4/lt~obsolete.m4 +googlemock/m4 + +# Ignore generated directories. +googlemock/fused-src/ +googletest/fused-src/ + +# macOS files +.DS_Store +googletest/.DS_Store +googletest/xcode/.DS_Store + +# Ignore cmake generated directories and files. +CMakeFiles +CTestTestfile.cmake +Makefile +cmake_install.cmake +googlemock/CMakeFiles +googlemock/CTestTestfile.cmake +googlemock/Makefile +googlemock/cmake_install.cmake +googlemock/gtest +/bin +/googlemock/gmock.dir +/googlemock/gmock_main.dir +/googlemock/RUN_TESTS.vcxproj.filters +/googlemock/RUN_TESTS.vcxproj +/googlemock/INSTALL.vcxproj.filters +/googlemock/INSTALL.vcxproj +/googlemock/gmock_main.vcxproj.filters +/googlemock/gmock_main.vcxproj +/googlemock/gmock.vcxproj.filters +/googlemock/gmock.vcxproj +/googlemock/gmock.sln +/googlemock/ALL_BUILD.vcxproj.filters +/googlemock/ALL_BUILD.vcxproj +/lib +/Win32 +/ZERO_CHECK.vcxproj.filters +/ZERO_CHECK.vcxproj +/RUN_TESTS.vcxproj.filters +/RUN_TESTS.vcxproj +/INSTALL.vcxproj.filters +/INSTALL.vcxproj +/googletest-distribution.sln +/CMakeCache.txt +/ALL_BUILD.vcxproj.filters +/ALL_BUILD.vcxproj diff --git a/sw/restatdesk_tests/googletest/BUILD.bazel b/sw/restatdesk_tests/googletest/BUILD.bazel new file mode 100644 index 0000000..5350145 --- /dev/null +++ b/sw/restatdesk_tests/googletest/BUILD.bazel @@ -0,0 +1,250 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Bazel Build for Google C++ Testing Framework(Google Test) + +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +exports_files(["LICENSE"]) + +config_setting( + name = "qnx", + constraint_values = ["@platforms//os:qnx"], +) + +config_setting( + name = "windows", + constraint_values = ["@platforms//os:windows"], +) + +config_setting( + name = "freebsd", + constraint_values = ["@platforms//os:freebsd"], +) + +config_setting( + name = "openbsd", + constraint_values = ["@platforms//os:openbsd"], +) + +# NOTE: Fuchsia is not an officially supported platform. +config_setting( + name = "fuchsia", + constraint_values = ["@platforms//os:fuchsia"], +) + +config_setting( + name = "msvc_compiler", + flag_values = { + "@bazel_tools//tools/cpp:compiler": "msvc-cl", + }, + visibility = [":__subpackages__"], +) + +config_setting( + name = "has_absl", + values = {"define": "absl=1"}, +) + +# Library that defines the FRIEND_TEST macro. +cc_library( + name = "gtest_prod", + hdrs = ["googletest/include/gtest/gtest_prod.h"], + includes = ["googletest/include"], +) + +# Google Test including Google Mock + +# For an actual test, use `gtest` and also `gtest_main` if you depend on gtest's +# main(). For a library, use `gtest_for_library` instead if the library can be +# testonly. +cc_library( + name = "gtest", + srcs = glob( + include = [ + "googletest/src/*.cc", + "googletest/src/*.h", + "googletest/include/gtest/**/*.h", + "googlemock/src/*.cc", + "googlemock/include/gmock/**/*.h", + ], + exclude = [ + "googletest/src/gtest-all.cc", + "googletest/src/gtest_main.cc", + "googlemock/src/gmock-all.cc", + "googlemock/src/gmock_main.cc", + ], + ), + hdrs = glob([ + "googletest/include/gtest/*.h", + "googlemock/include/gmock/*.h", + ]), + copts = select({ + ":qnx": [], + ":windows": [], + "//conditions:default": ["-pthread"], + }), + defines = select({ + ":has_absl": ["GTEST_HAS_ABSL=1"], + "//conditions:default": [], + }), + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), + includes = [ + "googlemock", + "googlemock/include", + "googletest", + "googletest/include", + ], + linkopts = select({ + ":qnx": ["-lregex"], + ":windows": [], + ":freebsd": [ + "-lm", + "-pthread", + ], + ":openbsd": [ + "-lm", + "-pthread", + ], + "//conditions:default": ["-pthread"], + }), + deps = select({ + ":has_absl": [ + "@abseil-cpp//absl/container:flat_hash_set", + "@abseil-cpp//absl/debugging:failure_signal_handler", + "@abseil-cpp//absl/debugging:stacktrace", + "@abseil-cpp//absl/debugging:symbolize", + "@abseil-cpp//absl/flags:flag", + "@abseil-cpp//absl/flags:parse", + "@abseil-cpp//absl/flags:reflection", + "@abseil-cpp//absl/flags:usage", + "@abseil-cpp//absl/strings", + "@abseil-cpp//absl/types:any", + "@abseil-cpp//absl/types:optional", + "@abseil-cpp//absl/types:variant", + "@re2//:re2", + ], + "//conditions:default": [], + }) + select({ + # `gtest-death-test.cc` has `EXPECT_DEATH` that spawns a process, + # expects it to crash and inspects its logs with the given matcher, + # so that's why these libraries are needed. + # Otherwise, builds targeting Fuchsia would fail to compile. + ":fuchsia": [ + "@fuchsia_sdk//pkg/fdio", + "@fuchsia_sdk//pkg/syslog", + "@fuchsia_sdk//pkg/zx", + ], + "//conditions:default": [], + }), +) + +# `gtest`, but testonly. See guidance on `gtest` for when to use this. +alias( + name = "gtest_for_library", + actual = ":gtest", + testonly = True, +) + +# Implements main() for tests using gtest. Prefer to depend on `gtest` as well +# to ensure compliance with the layering_check Bazel feature where only the +# direct hdrs values are available. +cc_library( + name = "gtest_main", + srcs = ["googlemock/src/gmock_main.cc"], + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), + deps = [":gtest"], +) + +# The following rules build samples of how to use gTest. +cc_library( + name = "gtest_sample_lib", + srcs = [ + "googletest/samples/sample1.cc", + "googletest/samples/sample2.cc", + "googletest/samples/sample4.cc", + ], + hdrs = [ + "googletest/samples/prime_tables.h", + "googletest/samples/sample1.h", + "googletest/samples/sample2.h", + "googletest/samples/sample3-inl.h", + "googletest/samples/sample4.h", + ], + features = select({ + ":windows": ["windows_export_all_symbols"], + "//conditions:default": [], + }), +) + +cc_test( + name = "gtest_samples", + size = "small", + # All Samples except: + # sample9 (main) + # sample10 (main and takes a command line option and needs to be separate) + srcs = [ + "googletest/samples/sample1_unittest.cc", + "googletest/samples/sample2_unittest.cc", + "googletest/samples/sample3_unittest.cc", + "googletest/samples/sample4_unittest.cc", + "googletest/samples/sample5_unittest.cc", + "googletest/samples/sample6_unittest.cc", + "googletest/samples/sample7_unittest.cc", + "googletest/samples/sample8_unittest.cc", + ], + linkstatic = 0, + deps = [ + "gtest_sample_lib", + ":gtest_main", + ], +) + +cc_test( + name = "sample9_unittest", + size = "small", + srcs = ["googletest/samples/sample9_unittest.cc"], + deps = [":gtest"], +) + +cc_test( + name = "sample10_unittest", + size = "small", + srcs = ["googletest/samples/sample10_unittest.cc"], + deps = [":gtest"], +) diff --git a/sw/restatdesk_tests/googletest/CMakeLists.txt b/sw/restatdesk_tests/googletest/CMakeLists.txt new file mode 100644 index 0000000..0567ae7 --- /dev/null +++ b/sw/restatdesk_tests/googletest/CMakeLists.txt @@ -0,0 +1,36 @@ +# Note: CMake support is community-based. The maintainers do not use CMake +# internally. + +cmake_minimum_required(VERSION 3.16) + +project(googletest-distribution) +set(GOOGLETEST_VERSION 1.17.0) + +if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) + set(CMAKE_CXX_EXTENSIONS OFF) +endif() + +enable_testing() + +include(CMakeDependentOption) +include(GNUInstallDirs) + +# Note that googlemock target already builds googletest. +option(BUILD_GMOCK "Builds the googlemock subproject" ON) +option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) +option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF) + +if(GTEST_HAS_ABSL) + if(NOT TARGET absl::base) + find_package(absl REQUIRED) + endif() + if(NOT TARGET re2::re2) + find_package(re2 REQUIRED) + endif() +endif() + +if(BUILD_GMOCK) + add_subdirectory( googlemock ) +else() + add_subdirectory( googletest ) +endif() diff --git a/sw/restatdesk_tests/googletest/CONTRIBUTING.md b/sw/restatdesk_tests/googletest/CONTRIBUTING.md new file mode 100644 index 0000000..ab5a47b --- /dev/null +++ b/sw/restatdesk_tests/googletest/CONTRIBUTING.md @@ -0,0 +1,141 @@ +# How to become a contributor and submit your own code + +## Contributor License Agreements + +We'd love to accept your patches! Before we can take them, we have to jump a +couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + +* If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an + [individual CLA](https://developers.google.com/open-source/cla/individual). +* If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a + [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Are you a Googler? + +If you are a Googler, please make an attempt to submit an internal contribution +rather than a GitHub Pull Request. If you are not able to submit internally, a +PR is acceptable as an alternative. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the + [issue tracker](https://github.com/google/googletest/issues). +2. Please don't mix more than one logical change per submittal, because it + makes the history hard to follow. If you want to make a change that doesn't + have a corresponding issue in the issue tracker, please create one. +3. Also, coordinate with team members that are listed on the issue in question. + This ensures that work isn't being duplicated and communicating your plan + early also generally leads to better patches. +4. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement + ([see details above](#contributor-license-agreements)). +5. Fork the desired repo, develop and test your code changes. +6. Ensure that your code adheres to the existing style in the sample to which + you are contributing. +7. Ensure that your code has an appropriate set of unit tests which all pass. +8. Submit a pull request. + +## The Google Test and Google Mock Communities + +The Google Test community exists primarily through the +[discussion group](https://groups.google.com/group/googletestframework) and the +GitHub repository. Likewise, the Google Mock community exists primarily through +their own [discussion group](https://groups.google.com/group/googlemock). You +are definitely encouraged to contribute to the discussion and you can also help +us to keep the effectiveness of the group high by following and promoting the +guidelines listed here. + +### Please Be Friendly + +Showing courtesy and respect to others is a vital part of the Google culture, +and we strongly encourage everyone participating in Google Test development to +join us in accepting nothing less. Of course, being courteous is not the same as +failing to constructively disagree with each other, but it does mean that we +should be respectful of each other when enumerating the 42 technical reasons +that a particular proposal may not be the best choice. There's never a reason to +be antagonistic or dismissive toward anyone who is sincerely trying to +contribute to a discussion. + +Sure, C++ testing is serious business and all that, but it's also a lot of fun. +Let's keep it that way. Let's strive to be one of the friendliest communities in +all of open source. + +As always, discuss Google Test in the official GoogleTest discussion group. You +don't have to actually submit code in order to sign up. Your participation +itself is a valuable contribution. + +## Style + +To keep the source consistent, readable, diffable and easy to merge, we use a +fairly rigid coding style, as defined by the +[google-styleguide](https://github.com/google/styleguide) project. All patches +will be expected to conform to the style outlined +[here](https://google.github.io/styleguide/cppguide.html). Use +[.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to +check your formatting. + +## Requirements for Contributors + +If you plan to contribute a patch, you need to build Google Test, Google Mock, +and their own tests from a git checkout, which has further requirements: + +* [Python](https://www.python.org/) v3.6 or newer (for running some of the + tests and re-generating certain source files from templates) +* [CMake](https://cmake.org/) v2.8.12 or newer + +## Developing Google Test and Google Mock + +This section discusses how to make your own changes to the Google Test project. + +### Testing Google Test and Google Mock Themselves + +To make sure your changes work as intended and don't break existing +functionality, you'll want to compile and run Google Test and GoogleMock's own +tests. For that you can use CMake: + +``` +mkdir mybuild +cd mybuild +cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} +``` + +To choose between building only Google Test or Google Mock, you may modify your +cmake command to be one of each + +``` +cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests +cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests +``` + +Make sure you have Python installed, as some of Google Test's tests are written +in Python. If the cmake command complains about not being able to find Python +(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it +explicitly where your Python executable can be found: + +``` +cmake -DPYTHON_EXECUTABLE=path/to/python ... +``` + +Next, you can build Google Test and / or Google Mock and all desired tests. On +\*nix, this is usually done by + +``` +make +``` + +To run the tests, do + +``` +make test +``` + +All tests should pass. diff --git a/sw/restatdesk_tests/googletest/CONTRIBUTORS b/sw/restatdesk_tests/googletest/CONTRIBUTORS new file mode 100644 index 0000000..ccea41e --- /dev/null +++ b/sw/restatdesk_tests/googletest/CONTRIBUTORS @@ -0,0 +1,66 @@ +# This file contains a list of people who've made non-trivial +# contribution to the Google C++ Testing Framework project. People +# who commit code to the project are encouraged to add their names +# here. Please keep the list sorted by first names. + +Ajay Joshi +Balázs Dán +Benoit Sigoure +Bharat Mediratta +Bogdan Piloca +Chandler Carruth +Chris Prince +Chris Taylor +Dan Egnor +Dave MacLachlan +David Anderson +Dean Sturtevant +Eric Roman +Gene Volovich +Hady Zalek +Hal Burch +Jeffrey Yasskin +Jim Keller +Joe Walnes +Jon Wray +Jói Sigurðsson +Keir Mierle +Keith Ray +Kenton Varda +Kostya Serebryany +Krystian Kuzniarek +Lev Makhlis +Manuel Klimek +Mario Tanev +Mark Paskin +Markus Heule +Martijn Vels +Matthew Simmons +Mika Raento +Mike Bland +Miklós Fazekas +Neal Norwitz +Nermin Ozkiranartli +Owen Carlsen +Paneendra Ba +Pasi Valminen +Patrick Hanna +Patrick Riley +Paul Menage +Peter Kaminski +Piotr Kaminski +Preston Jackson +Rainer Klaffenboeck +Russ Cox +Russ Rufer +Sean Mcafee +Sigurður Ásgeirsson +Soyeon Kim +Sverre Sundsdal +Szymon Sobik +Takeshi Yoshino +Tracy Bialik +Vadim Berman +Vlad Losev +Wolfgang Klier +Zhanyong Wan diff --git a/sw/restatdesk_tests/googletest/LICENSE b/sw/restatdesk_tests/googletest/LICENSE new file mode 100644 index 0000000..1941a11 --- /dev/null +++ b/sw/restatdesk_tests/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/sw/restatdesk_tests/googletest/MODULE.bazel b/sw/restatdesk_tests/googletest/MODULE.bazel new file mode 100644 index 0000000..5cb0b15 --- /dev/null +++ b/sw/restatdesk_tests/googletest/MODULE.bazel @@ -0,0 +1,76 @@ +# Copyright 2024 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# https://bazel.build/external/overview#bzlmod + +module( + name = "googletest", + version = "1.17.0", + compatibility_level = 1, +) + +# Only direct dependencies need to be listed below. +# Please keep the versions in sync with the versions in the WORKSPACE file. + +bazel_dep( + name = "abseil-cpp", + version = "20250127.1", +) +bazel_dep( + name = "platforms", + version = "0.0.11", +) +bazel_dep( + name = "re2", + version = "2024-07-02.bcr.1", +) + +bazel_dep( + name = "rules_python", + version = "1.3.0", + dev_dependency = True, +) + +# https://rules-python.readthedocs.io/en/stable/toolchains.html#library-modules-with-dev-only-python-usage +python = use_extension( + "@rules_python//python/extensions:python.bzl", + "python", + dev_dependency = True, +) +python.toolchain( + ignore_root_user_error = True, + is_default = True, + python_version = "3.12", +) + +# See fake_fuchsia_sdk.bzl for instructions on how to override this with a real SDK, if needed. +fuchsia_sdk = use_extension("//:fake_fuchsia_sdk.bzl", "fuchsia_sdk") +fuchsia_sdk.create_fake() +use_repo(fuchsia_sdk, "fuchsia_sdk") diff --git a/sw/restatdesk_tests/googletest/README.md b/sw/restatdesk_tests/googletest/README.md new file mode 100644 index 0000000..598cf31 --- /dev/null +++ b/sw/restatdesk_tests/googletest/README.md @@ -0,0 +1,133 @@ +# GoogleTest + +### Announcements + +#### Documentation Updates + +Our documentation is now live on GitHub Pages at +https://google.github.io/googletest/. We recommend browsing the documentation on +GitHub Pages rather than directly in the repository. + +#### Release 1.17.0 + +[Release 1.17.0](https://github.com/google/googletest/releases/tag/v1.17.0) is +now available. + +The 1.17.x branch [requires at least C++17]((https://opensource.google/documentation/policies/cplusplus-support#c_language_standard). + +#### Continuous Integration + +We use Google's internal systems for continuous integration. + +#### Coming Soon + +* We are planning to take a dependency on + [Abseil](https://github.com/abseil/abseil-cpp). + +## Welcome to **GoogleTest**, Google's C++ test framework! + +This repository is a merger of the formerly separate GoogleTest and GoogleMock +projects. These were so closely related that it makes sense to maintain and +release them together. + +### Getting Started + +See the [GoogleTest User's Guide](https://google.github.io/googletest/) for +documentation. We recommend starting with the +[GoogleTest Primer](https://google.github.io/googletest/primer.html). + +More information about building GoogleTest can be found at +[googletest/README.md](googletest/README.md). + +## Features + +* xUnit test framework: \ + Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit) + testing framework, a popular architecture for unit testing +* Test discovery: \ + Googletest automatically discovers and runs your tests, eliminating the need + to manually register your tests +* Rich set of assertions: \ + Googletest provides a variety of assertions, such as equality, inequality, + exceptions, and more, making it easy to test your code +* User-defined assertions: \ + You can define your own assertions with Googletest, making it simple to + write tests that are specific to your code +* Death tests: \ + Googletest supports death tests, which verify that your code exits in a + certain way, making it useful for testing error-handling code +* Fatal and non-fatal failures: \ + You can specify whether a test failure should be treated as fatal or + non-fatal with Googletest, allowing tests to continue running even if a + failure occurs +* Value-parameterized tests: \ + Googletest supports value-parameterized tests, which run multiple times with + different input values, making it useful for testing functions that take + different inputs +* Type-parameterized tests: \ + Googletest also supports type-parameterized tests, which run with different + data types, making it useful for testing functions that work with different + data types +* Various options for running tests: \ + Googletest provides many options for running tests including running + individual tests, running tests in a specific order and running tests in + parallel + +## Supported Platforms + +GoogleTest follows Google's +[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). +See +[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) +for a list of currently supported versions of compilers, platforms, and build +tools. + +## Who Is Using GoogleTest? + +In addition to many internal projects at Google, GoogleTest is also used by the +following notable projects: + +* The [Chromium projects](https://www.chromium.org/) (behind the Chrome + browser and Chrome OS). +* The [LLVM](https://llvm.org/) compiler. +* [Protocol Buffers](https://github.com/google/protobuf), Google's data + interchange format. +* The [OpenCV](https://opencv.org/) computer vision library. + +## Related Open Source Projects + +[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based +automated test-runner and Graphical User Interface with powerful features for +Windows and Linux platforms. + +[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that +runs your test binary, allows you to track its progress via a progress bar, and +displays a list of test failures. Clicking on one shows failure text. GoogleTest +UI is written in C#. + +[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event +listener for GoogleTest that implements the +[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test +result output. If your test runner understands TAP, you may find it useful. + +[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that +runs tests from your binary in parallel to provide significant speed-up. + +[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) +is a VS Code extension allowing to view GoogleTest in a tree view and run/debug +your tests. + +[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS +Code extension allowing to view GoogleTest in a tree view and run/debug your +tests. + +[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser +that generates stub code for GoogleTest. + +## Contributing Changes + +Please read +[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md) +for details on how to contribute to this project. + +Happy testing! diff --git a/sw/restatdesk_tests/googletest/WORKSPACE b/sw/restatdesk_tests/googletest/WORKSPACE new file mode 100644 index 0000000..0ae5dee --- /dev/null +++ b/sw/restatdesk_tests/googletest/WORKSPACE @@ -0,0 +1,61 @@ +# Copyright 2024 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +workspace(name = "googletest") + +load("//:googletest_deps.bzl", "googletest_deps") +googletest_deps() + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "rules_python", + sha256 = "2cc26bbd53854ceb76dd42a834b1002cd4ba7f8df35440cf03482e045affc244", + strip_prefix = "rules_python-1.3.0", + url = "https://github.com/bazelbuild/rules_python/releases/download/1.3.0/rules_python-1.3.0.tar.gz", +) +# https://github.com/bazelbuild/rules_python/releases/tag/1.1.0 +load("@rules_python//python:repositories.bzl", "py_repositories") +py_repositories() + +http_archive( + name = "bazel_skylib", + sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94", + urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz"], +) + +http_archive( + name = "platforms", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz", + "https://github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz", + ], + sha256 = "29742e87275809b5e598dc2f04d86960cc7a55b3067d97221c9abbc9926bff0f", +) diff --git a/sw/restatdesk_tests/googletest/WORKSPACE.bzlmod b/sw/restatdesk_tests/googletest/WORKSPACE.bzlmod new file mode 100644 index 0000000..381432c --- /dev/null +++ b/sw/restatdesk_tests/googletest/WORKSPACE.bzlmod @@ -0,0 +1,35 @@ +# Copyright 2024 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# https://bazel.build/external/migration#workspace.bzlmod +# +# This file is intentionally empty. When bzlmod is enabled and this +# file exists, the content of WORKSPACE is ignored. This prevents +# bzlmod builds from unintentionally depending on the WORKSPACE file. diff --git a/sw/restatdesk_tests/googletest/ci/linux-presubmit.sh b/sw/restatdesk_tests/googletest/ci/linux-presubmit.sh new file mode 100755 index 0000000..6491e79 --- /dev/null +++ b/sw/restatdesk_tests/googletest/ci/linux-presubmit.sh @@ -0,0 +1,157 @@ +#!/bin/bash +# +# Copyright 2020, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +set -euox pipefail + +readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20241218" +readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20250205" + +if [[ -z ${GTEST_ROOT:-} ]]; then + GTEST_ROOT="$(realpath $(dirname ${0})/..)" +fi + +if [[ -z ${STD:-} ]]; then + STD="c++17 c++20" +fi + +# Test CMake + GCC +for cmake_off_on in OFF ON; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --tmpfs="/build:exec" \ + --workdir="/build" \ + --rm \ + --env="CC=/usr/local/bin/gcc" \ + --env=CXXFLAGS="-Werror -Wdeprecated" \ + ${LINUX_LATEST_CONTAINER} \ + /bin/bash -c " + cmake /src \ + -DCMAKE_CXX_STANDARD=17 \ + -Dgtest_build_samples=ON \ + -Dgtest_build_tests=ON \ + -Dgmock_build_tests=ON \ + -Dcxx_no_exception=${cmake_off_on} \ + -Dcxx_no_rtti=${cmake_off_on} && \ + make -j$(nproc) && \ + ctest -j$(nproc) --output-on-failure" +done + +# Test CMake + Clang +for cmake_off_on in OFF ON; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --tmpfs="/build:exec" \ + --workdir="/build" \ + --rm \ + --env="CC=/opt/llvm/clang/bin/clang" \ + --env=CXXFLAGS="-Werror -Wdeprecated --gcc-toolchain=/usr/local" \ + ${LINUX_LATEST_CONTAINER} \ + /bin/bash -c " + cmake /src \ + -DCMAKE_CXX_STANDARD=17 \ + -Dgtest_build_samples=ON \ + -Dgtest_build_tests=ON \ + -Dgmock_build_tests=ON \ + -Dcxx_no_exception=${cmake_off_on} \ + -Dcxx_no_rtti=${cmake_off_on} && \ + make -j$(nproc) && \ + ctest -j$(nproc) --output-on-failure" +done + +# Do one test with an older version of GCC +time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/usr/local/bin/gcc" \ + --env="BAZEL_CXXOPTS=-std=c++17" \ + ${LINUX_GCC_FLOOR_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --copt="-Wno-error=pragmas" \ + --enable_bzlmod=false \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors + +# Test GCC +for std in ${STD}; do + for absl in 0 1; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/usr/local/bin/gcc" \ + --env="BAZEL_CXXOPTS=-std=${std}" \ + ${LINUX_LATEST_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --define="absl=${absl}" \ + --enable_bzlmod=true \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors + done +done + +# Test Clang +for std in ${STD}; do + for absl in 0 1; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/opt/llvm/clang/bin/clang" \ + --env="BAZEL_CXXOPTS=-std=${std}" \ + ${LINUX_LATEST_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="--gcc-toolchain=/usr/local" \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --define="absl=${absl}" \ + --enable_bzlmod=true \ + --features=external_include_paths \ + --keep_going \ + --linkopt="--gcc-toolchain=/usr/local" \ + --show_timestamps \ + --test_output=errors + done +done diff --git a/sw/restatdesk_tests/googletest/ci/macos-presubmit.sh b/sw/restatdesk_tests/googletest/ci/macos-presubmit.sh new file mode 100755 index 0000000..5370ed6 --- /dev/null +++ b/sw/restatdesk_tests/googletest/ci/macos-presubmit.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# +# Copyright 2020, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +set -euox pipefail + +# Use Xcode 16.0 +sudo xcode-select -s /Applications/Xcode_16.0.app/Contents/Developer + +if [[ -z ${GTEST_ROOT:-} ]]; then + GTEST_ROOT="$(realpath $(dirname ${0})/..)" +fi + +# Test the CMake build +for cmake_off_on in OFF ON; do + BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX) + cd ${BUILD_DIR} + time cmake ${GTEST_ROOT} \ + -DCMAKE_CXX_STANDARD=17 \ + -Dgtest_build_samples=ON \ + -Dgtest_build_tests=ON \ + -Dgmock_build_tests=ON \ + -Dcxx_no_exception=${cmake_off_on} \ + -Dcxx_no_rtti=${cmake_off_on} + time make -j$(nproc) + time ctest -j$(nproc) --output-on-failure +done + +# Test the Bazel build + +# If we are running on Kokoro, check for a versioned Bazel binary. +KOKORO_GFILE_BAZEL_BIN="bazel-8.0.0-darwin-x86_64" +if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then + BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}" + chmod +x ${BAZEL_BIN} +else + BAZEL_BIN="bazel" +fi + +cd ${GTEST_ROOT} +for absl in 0 1; do + ${BAZEL_BIN} test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wundef" \ + --cxxopt="-std=c++17" \ + --define="absl=${absl}" \ + --enable_bzlmod=true \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors +done diff --git a/sw/restatdesk_tests/googletest/ci/windows-presubmit.bat b/sw/restatdesk_tests/googletest/ci/windows-presubmit.bat new file mode 100644 index 0000000..e2664c5 --- /dev/null +++ b/sw/restatdesk_tests/googletest/ci/windows-presubmit.bat @@ -0,0 +1,75 @@ +SETLOCAL ENABLEDELAYEDEXPANSION + +SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-8.0.0-windows-x86_64.exe + +SET PATH=C:\Python34;%PATH% +SET BAZEL_PYTHON=C:\python34\python.exe +SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe +SET CMAKE_BIN="cmake.exe" +SET CTEST_BIN="ctest.exe" +SET CTEST_OUTPUT_ON_FAILURE=1 +SET CMAKE_BUILD_PARALLEL_LEVEL=16 +SET CTEST_PARALLEL_LEVEL=16 + +SET GTEST_ROOT=%~dp0\.. +IF %errorlevel% neq 0 EXIT /B 1 + +:: ---------------------------------------------------------------------------- +:: CMake +SET CMAKE_BUILD_PATH=cmake_msvc2022 +MKDIR %CMAKE_BUILD_PATH% +CD %CMAKE_BUILD_PATH% + +%CMAKE_BIN% %GTEST_ROOT% ^ + -G "Visual Studio 17 2022" ^ + -DCMAKE_CXX_STANDARD=17 ^ + -DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^ + -DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^ + -DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^ + -Dgtest_build_samples=ON ^ + -Dgtest_build_tests=ON ^ + -Dgmock_build_tests=ON +IF %errorlevel% neq 0 EXIT /B 1 + +%CMAKE_BIN% --build . --target ALL_BUILD --config Debug -- -maxcpucount +IF %errorlevel% neq 0 EXIT /B 1 + +%CTEST_BIN% -C Debug --timeout 600 +IF %errorlevel% neq 0 EXIT /B 1 + +CD %GTEST_ROOT% +RMDIR /S /Q %CMAKE_BUILD_PATH% + +:: ---------------------------------------------------------------------------- +:: Bazel + +:: The default home directory on Kokoro is a long path which causes errors +:: because of Windows limitations on path length. +:: --output_user_root=C:\tmp causes Bazel to use a shorter path. +SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community + +:: C++17 +%BAZEL_EXE% ^ + --output_user_root=C:\tmp ^ + test ... ^ + --compilation_mode=dbg ^ + --copt=/std:c++17 ^ + --copt=/WX ^ + --enable_bzlmod=true ^ + --keep_going ^ + --test_output=errors ^ + --test_tag_filters=-no_test_msvc2017 +IF %errorlevel% neq 0 EXIT /B 1 + +:: C++20 +%BAZEL_EXE% ^ + --output_user_root=C:\tmp ^ + test ... ^ + --compilation_mode=dbg ^ + --copt=/std:c++20 ^ + --copt=/WX ^ + --enable_bzlmod=true ^ + --keep_going ^ + --test_output=errors ^ + --test_tag_filters=-no_test_msvc2017 +IF %errorlevel% neq 0 EXIT /B 1 diff --git a/sw/restatdesk_tests/googletest/docs/_config.yml b/sw/restatdesk_tests/googletest/docs/_config.yml new file mode 100644 index 0000000..d12867e --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/_config.yml @@ -0,0 +1 @@ +title: GoogleTest diff --git a/sw/restatdesk_tests/googletest/docs/_data/navigation.yml b/sw/restatdesk_tests/googletest/docs/_data/navigation.yml new file mode 100644 index 0000000..9f33327 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/_data/navigation.yml @@ -0,0 +1,43 @@ +nav: +- section: "Get Started" + items: + - title: "Supported Platforms" + url: "/platforms.html" + - title: "Quickstart: Bazel" + url: "/quickstart-bazel.html" + - title: "Quickstart: CMake" + url: "/quickstart-cmake.html" +- section: "Guides" + items: + - title: "GoogleTest Primer" + url: "/primer.html" + - title: "Advanced Topics" + url: "/advanced.html" + - title: "Mocking for Dummies" + url: "/gmock_for_dummies.html" + - title: "Mocking Cookbook" + url: "/gmock_cook_book.html" + - title: "Mocking Cheat Sheet" + url: "/gmock_cheat_sheet.html" +- section: "References" + items: + - title: "Testing Reference" + url: "/reference/testing.html" + - title: "Mocking Reference" + url: "/reference/mocking.html" + - title: "Assertions" + url: "/reference/assertions.html" + - title: "Matchers" + url: "/reference/matchers.html" + - title: "Actions" + url: "/reference/actions.html" + - title: "Testing FAQ" + url: "/faq.html" + - title: "Mocking FAQ" + url: "/gmock_faq.html" + - title: "Code Samples" + url: "/samples.html" + - title: "Using pkg-config" + url: "/pkgconfig.html" + - title: "Community Documentation" + url: "/community_created_documentation.html" diff --git a/sw/restatdesk_tests/googletest/docs/_layouts/default.html b/sw/restatdesk_tests/googletest/docs/_layouts/default.html new file mode 100644 index 0000000..c7f331b --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/_layouts/default.html @@ -0,0 +1,58 @@ + + + + + + + +{% seo %} + + + + + + +
+
+ {{ content }} +
+ +
+ + + + diff --git a/sw/restatdesk_tests/googletest/docs/_sass/main.scss b/sw/restatdesk_tests/googletest/docs/_sass/main.scss new file mode 100644 index 0000000..92edc87 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/_sass/main.scss @@ -0,0 +1,200 @@ +// Styles for GoogleTest docs website on GitHub Pages. +// Color variables are defined in +// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables + +$sidebar-width: 260px; + +body { + display: flex; + margin: 0; +} + +.sidebar { + background: $black; + color: $text-white; + flex-shrink: 0; + height: 100vh; + overflow: auto; + position: sticky; + top: 0; + width: $sidebar-width; +} + +.sidebar h1 { + font-size: 1.5em; +} + +.sidebar h2 { + color: $gray-light; + font-size: 0.8em; + font-weight: normal; + margin-bottom: 0.8em; + padding-left: 2.5em; + text-transform: uppercase; +} + +.sidebar .header { + background: $black; + padding: 2em; + position: sticky; + top: 0; + width: 100%; +} + +.sidebar .header a { + color: $text-white; + text-decoration: none; +} + +.sidebar .nav-toggle { + display: none; +} + +.sidebar .expander { + cursor: pointer; + display: none; + height: 3em; + position: absolute; + right: 1em; + top: 1.5em; + width: 3em; +} + +.sidebar .expander .arrow { + border: solid $white; + border-width: 0 3px 3px 0; + display: block; + height: 0.7em; + margin: 1em auto; + transform: rotate(45deg); + transition: transform 0.5s; + width: 0.7em; +} + +.sidebar nav { + width: 100%; +} + +.sidebar nav ul { + list-style-type: none; + margin-bottom: 1em; + padding: 0; + + &:last-child { + margin-bottom: 2em; + } + + a { + text-decoration: none; + } + + li { + color: $text-white; + padding-left: 2em; + text-decoration: none; + } + + li.active { + background: $border-gray-darker; + font-weight: bold; + } + + li:hover { + background: $border-gray-darker; + } +} + +.main { + background-color: $bg-gray; + width: calc(100% - #{$sidebar-width}); +} + +.main .main-inner { + background-color: $white; + padding: 2em; +} + +.main .footer { + margin: 0; + padding: 2em; +} + +.main table th { + text-align: left; +} + +.main .callout { + border-left: 0.25em solid $white; + padding: 1em; + + a { + text-decoration: underline; + } + + &.important { + background-color: $bg-yellow-light; + border-color: $bg-yellow; + color: $black; + } + + &.note { + background-color: $bg-blue-light; + border-color: $text-blue; + color: $text-blue; + } + + &.tip { + background-color: $green-000; + border-color: $green-700; + color: $green-700; + } + + &.warning { + background-color: $red-000; + border-color: $text-red; + color: $text-red; + } +} + +.main .good pre { + background-color: $bg-green-light; +} + +.main .bad pre { + background-color: $red-000; +} + +@media all and (max-width: 768px) { + body { + flex-direction: column; + } + + .sidebar { + height: auto; + position: relative; + width: 100%; + } + + .sidebar .expander { + display: block; + } + + .sidebar nav { + height: 0; + overflow: hidden; + } + + .sidebar .nav-toggle:checked { + & ~ nav { + height: auto; + } + + & + .expander .arrow { + transform: rotate(-135deg); + } + } + + .main { + width: 100%; + } +} diff --git a/sw/restatdesk_tests/googletest/docs/advanced.md b/sw/restatdesk_tests/googletest/docs/advanced.md new file mode 100644 index 0000000..9b1220a --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/advanced.md @@ -0,0 +1,2466 @@ +# Advanced GoogleTest Topics + +## Introduction + +Now that you have read the [GoogleTest Primer](primer.md) and learned how to +write tests using GoogleTest, it's time to learn some new tricks. This document +will show you more assertions as well as how to construct complex failure +messages, propagate fatal failures, reuse and speed up your test fixtures, and +use various flags with your tests. + +## More Assertions + +This section covers some less frequently used, but still significant, +assertions. + +### Explicit Success and Failure + +See [Explicit Success and Failure](reference/assertions.md#success-failure) in +the Assertions Reference. + +### Exception Assertions + +See [Exception Assertions](reference/assertions.md#exceptions) in the Assertions +Reference. + +### Predicate Assertions for Better Error Messages + +Even though GoogleTest has a rich set of assertions, they can never be complete, +as it's impossible (nor a good idea) to anticipate all scenarios a user might +run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a +complex expression, for lack of a better macro. This has the problem of not +showing you the values of the parts of the expression, making it hard to +understand what went wrong. As a workaround, some users choose to construct the +failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this +is awkward especially when the expression has side-effects or is expensive to +evaluate. + +GoogleTest gives you three different options to solve this problem: + +#### Using an Existing Boolean Function + +If you already have a function or functor that returns `bool` (or a type that +can be implicitly converted to `bool`), you can use it in a *predicate +assertion* to get the function arguments printed for free. See +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions +Reference for details. + +#### Using a Function That Returns an AssertionResult + +While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not +satisfactory: you have to use different macros for different arities, and it +feels more like Lisp than C++. The `::testing::AssertionResult` class solves +this problem. + +An `AssertionResult` object represents the result of an assertion (whether it's +a success or a failure, and an associated message). You can create an +`AssertionResult` using one of these factory functions: + +```c++ +namespace testing { + +// Returns an AssertionResult object to indicate that an assertion has +// succeeded. +AssertionResult AssertionSuccess(); + +// Returns an AssertionResult object to indicate that an assertion has +// failed. +AssertionResult AssertionFailure(); + +} +``` + +You can then use the `<<` operator to stream messages to the `AssertionResult` +object. + +To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), +write a predicate function that returns `AssertionResult` instead of `bool`. For +example, if you define `IsEven()` as: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess(); + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +instead of: + +```c++ +bool IsEven(int n) { + return (n % 2) == 0; +} +``` + +the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: + +```none +Value of: IsEven(Fib(4)) + Actual: false (3 is odd) +Expected: true +``` + +instead of a more opaque + +```none +Value of: IsEven(Fib(4)) + Actual: false +Expected: true +``` + +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well +(one third of Boolean assertions in the Google code base are negative ones), and +are fine with making the predicate slower in the success case, you can supply a +success message: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess() << n << " is even"; + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print + +```none + Value of: IsEven(Fib(6)) + Actual: true (8 is even) + Expected: false +``` + +#### Using a Predicate-Formatter + +If you find the default message generated by +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and +[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some +arguments to your predicate do not support streaming to `ostream`, you can +instead use *predicate-formatter assertions* to *fully* customize how the +message is formatted. See +[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the +Assertions Reference for details. + +### Floating-Point Comparison + +See [Floating-Point Comparison](reference/assertions.md#floating-point) in the +Assertions Reference. + +#### Floating-Point Predicate-Format Functions + +Some floating-point operations are useful, but not that often used. In order to +avoid an explosion of new macros, we provide them as predicate-format functions +that can be used in the predicate assertion macro +[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for +example: + +```c++ +using ::testing::FloatLE; +using ::testing::DoubleLE; +... +EXPECT_PRED_FORMAT2(FloatLE, val1, val2); +EXPECT_PRED_FORMAT2(DoubleLE, val1, val2); +``` + +The above code verifies that `val1` is less than, or approximately equal to, +`val2`. + +### Asserting Using gMock Matchers + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### More String Assertions + +(Please read the [previous](#asserting-using-gmock-matchers) section first if +you haven't.) + +You can use the gMock [string matchers](reference/matchers.md#string-matchers) +with [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string +comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For +example, + +```c++ +using ::testing::HasSubstr; +using ::testing::MatchesRegex; +... + ASSERT_THAT(foo_string, HasSubstr("needle")); + EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); +``` + +### Windows HRESULT assertions + +See [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the +Assertions Reference. + +### Type Assertions + +You can call the function + +```c++ +::testing::StaticAssertTypeEq(); +``` + +to assert that types `T1` and `T2` are the same. The function does nothing if +the assertion is satisfied. If the types are different, the function call will +fail to compile, the compiler error message will say that `T1 and T2 are not the +same type` and most likely (depending on the compiler) show you the actual +values of `T1` and `T2`. This is mainly useful inside template code. + +**Caveat**: When used inside a member function of a class template or a function +template, `StaticAssertTypeEq()` is effective only if the function is +instantiated. For example, given: + +```c++ +template class Foo { + public: + void Bar() { testing::StaticAssertTypeEq(); } +}; +``` + +the code: + +```c++ +void Test1() { Foo foo; } +``` + +will not generate a compiler error, as `Foo::Bar()` is never actually +instantiated. Instead, you need: + +```c++ +void Test2() { Foo foo; foo.Bar(); } +``` + +to cause a compiler error. + +### Assertion Placement + +You can use assertions in any C++ function. In particular, it doesn't have to be +a method of the test fixture class. The one constraint is that assertions that +generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in +void-returning functions. This is a consequence of Google's not using +exceptions. By placing it in a non-void function you'll get a confusing compile +error like `"error: void value not ignored as it ought to be"` or `"cannot +initialize return object of type 'bool' with an rvalue of type 'void'"` or +`"error: no viable conversion from 'void' to 'string'"`. + +If you need to use fatal assertions in a function that returns non-void, one +option is to make the function return the value in an out parameter instead. For +example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You +need to make sure that `*result` contains some sensible value even when the +function returns prematurely. As the function now returns `void`, you can use +any assertion inside of it. + +If changing the function's type is not an option, you should just use assertions +that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. + +{: .callout .note} +NOTE: Constructors and destructors are not considered void-returning functions, +according to the C++ language specification, and so you may not use fatal +assertions in them; you'll get a compilation error if you try. Instead, either +call `abort` and crash the entire test executable, or put the fatal assertion in +a `SetUp`/`TearDown` function; see +[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp) + +{: .callout .warning} +WARNING: A fatal assertion in a helper function (private void-returning method) +called from a constructor or destructor does not terminate the current test, as +your intuition might suggest: it merely returns from the constructor or +destructor early, possibly leaving your object in a partially-constructed or +partially-destructed state! You almost certainly want to `abort` or use +`SetUp`/`TearDown` instead. + +## Skipping test execution + +Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test +execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need +to check for preconditions of the system under test during runtime and skip +tests in a meaningful way. + +`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods +of classes derived from either `::testing::Environment` or `::testing::Test`. +For example: + +```c++ +TEST(SkipTest, DoesSkip) { + GTEST_SKIP() << "Skipping single test"; + FAIL(); // Won't fail; it won't be executed +} + +class SkipFixture : public ::testing::Test { + protected: + void SetUp() override { + GTEST_SKIP() << "Skipping all tests for this fixture"; + } +}; + +// Tests for SkipFixture won't be executed. +TEST_F(SkipFixture, SkipsOneTest) { + FAIL(); // Won't fail; it won't be executed +} +``` + +As with assertion macros, you can stream a custom message into `GTEST_SKIP()`. + +## Teaching GoogleTest How to Print Your Values + +When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument +values to help you debug. It does this using a user-extensible value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. + +As mentioned earlier, the printer is *extensible*. That means you can teach it +to do a better job at printing your particular type than to dump the bytes. To +do that, define an `AbslStringify()` overload as a `friend` function template +for your type: + +```cpp +namespace foo { + +class Point { // We want GoogleTest to be able to print instances of this. + ... + // Provide a friend overload. + template + friend void AbslStringify(Sink& sink, const Point& point) { + absl::Format(&sink, "(%d, %d)", point.x, point.y); + } + + int x; + int y; +}; + +// If you can't declare the function in the class it's important that the +// AbslStringify overload is defined in the SAME namespace that defines Point. +// C++'s look-up rules rely on that. +enum class EnumWithStringify { kMany = 0, kChoices = 1 }; + +template +void AbslStringify(Sink& sink, EnumWithStringify e) { + absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices"); +} + +} // namespace foo +``` + +{: .callout .note} +Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its +string. For more information about supported operations on `AbslStringify()`'s +sink, see go/abslstringify. + +`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier +within its own format strings to perform type deduction. `Point` above could be +formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`. + +Sometimes, `AbslStringify()` might not be an option: your team may wish to print +types with extra debugging information for testing purposes only. If so, you can +instead define a `PrintTo()` function like this: + +```c++ +#include + +namespace foo { + +class Point { + ... + friend void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; + } + + int x; + int y; +}; + +// If you can't declare the function in the class it's important that PrintTo() +// is defined in the SAME namespace that defines Point. C++'s look-up rules +// rely on that. +void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; +} + +} // namespace foo +``` + +If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be +used by GoogleTest. This allows you to customize how the value appears in +GoogleTest's output without affecting code that relies on the behavior of +`AbslStringify()`. + +If you have an existing `<<` operator and would like to define an +`AbslStringify()`, the latter will be used for GoogleTest printing. + +If you want to print a value `x` using GoogleTest's value printer yourself, just +call `::testing::PrintToString(x)`, which returns an `std::string`: + +```c++ +vector > point_ints = GetPointIntVector(); + +EXPECT_TRUE(IsCorrectPointIntVector(point_ints)) + << "point_ints = " << testing::PrintToString(point_ints); +``` + +For more details regarding `AbslStringify()` and its integration with other +libraries, see go/abslstringify. + +## Regular Expression Syntax + +When built with Bazel and using Abseil, GoogleTest uses the +[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX +systems (Linux, Cygwin, Mac), GoogleTest uses the +[POSIX extended regular expression](https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +syntax. To learn about POSIX syntax, you may want to read this +[Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). + +On Windows, GoogleTest uses its own simple regular expression implementation. It +lacks many features. For example, we don't support union (`"x|y"`), grouping +(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among +others. Below is what we do support (`A` denotes a literal character, period +(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular +expressions.): + +Expression | Meaning +---------- | -------------------------------------------------------------- +`c` | matches any literal character `c` +`\\d` | matches any decimal digit +`\\D` | matches any character that's not a decimal digit +`\\f` | matches `\f` +`\\n` | matches `\n` +`\\r` | matches `\r` +`\\s` | matches any ASCII whitespace, including `\n` +`\\S` | matches any character that's not a whitespace +`\\t` | matches `\t` +`\\v` | matches `\v` +`\\w` | matches any letter, `_`, or decimal digit +`\\W` | matches any character that `\\w` doesn't match +`\\c` | matches any literal character `c`, which must be a punctuation +`.` | matches any single character except `\n` +`A?` | matches 0 or 1 occurrences of `A` +`A*` | matches 0 or many occurrences of `A` +`A+` | matches 1 or many occurrences of `A` +`^` | matches the beginning of a string (not that of each line) +`$` | matches the end of a string (not that of each line) +`xy` | matches `x` followed by `y` + +To help you determine which capability is available on your system, GoogleTest +defines macros to govern which regular expression it is using. The macros are: +`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death +tests to work in all cases, you can either `#if` on these macros or use the more +limited syntax only. + +## Death Tests + +In many applications, there are assertions that can cause application failure if +a condition is not met. These consistency checks, which ensure that the program +is in a known good state, are there to fail at the earliest possible time after +some program state is corrupted. If the assertion checks the wrong condition, +then the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test that +such assertion statements work as expected. + +Since these precondition checks cause the processes to die, we call such tests +*death tests*. More generally, any test that checks that a program terminates +(except by throwing an exception) in an expected fashion is also a death test. + +Note that if a piece of code throws an exception, we don't consider it "death" +for the purpose of death tests, as the caller of the code could catch the +exception and avoid the crash. If you want to verify exceptions thrown by your +code, see [Exception Assertions](#ExceptionAssertions). + +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see +["Catching" Failures](#catching-failures). + +### How to Write a Death Test + +GoogleTest provides assertion macros to support death tests. See +[Death Assertions](reference/assertions.md#death) in the Assertions Reference +for details. + +To write a death test, simply use one of the macros inside your test function. +For example, + +```c++ +TEST(MyDeathTest, Foo) { + // This death test uses a compound statement. + ASSERT_DEATH({ + int n = 5; + Foo(&n); + }, "Error on line .* of Foo()"); +} + +TEST(MyDeathTest, NormalExit) { + EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +} + +TEST(MyDeathTest, KillProcess) { + EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL), + "Sending myself unblockable signal"); +} +``` + +verifies that: + +* calling `Foo(5)` causes the process to die with the given error message, +* calling `NormalExit()` causes the process to print `"Success"` to stderr and + exit with exit code 0, and +* calling `KillProcess()` kills the process with signal `SIGKILL`. + +{: .callout .warning} +Warning: If your death test contains mocks and is expecting a specific exit +code, then you must allow the mock objects to be leaked via `Mock::AllowLeak`. +This is because the mock leak detector will exit with its own error code if it +detects a leak. + +The test function body may contain other assertions and statements as well, if +necessary. + +Note that a death test only cares about three things: + +1. does `statement` abort or exit the process? +2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status + satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) + is the exit status non-zero? And +3. does the stderr output match `matcher`? + +In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it +will **not** cause the death test to fail, as GoogleTest assertions don't abort +the process. + +### Death Test Naming + +{: .callout .important} +IMPORTANT: We strongly recommend you to follow the convention of naming your +**test suite** (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The +[Death Tests And Threads](#death-tests-and-threads) section below explains why. + +If a test fixture class is shared by normal tests and death tests, you can use +`using` or `typedef` to introduce an alias for the fixture class and avoid +duplicating its code: + +```c++ +class FooTest : public testing::Test { ... }; + +using FooDeathTest = FooTest; + +TEST_F(FooTest, DoesThis) { + // normal test +} + +TEST_F(FooDeathTest, DoesThat) { + // death test +} +``` + +### How It Works + +See [Death Assertions](reference/assertions.md#death) in the Assertions +Reference. + +### Death Tests And Threads + +The reason for the two death test styles has to do with thread safety. Due to +well-known problems with forking in the presence of threads, death tests should +be run in a single-threaded context. Sometimes, however, it isn't feasible to +arrange that kind of environment. For example, statically-initialized modules +may start threads before main is ever reached. Once threads have been created, +it may be difficult or impossible to clean them up. + +GoogleTest has three features intended to raise awareness of threading issues. + +1. A warning is emitted if multiple threads are running when a death test is + encountered. +2. Test suites with a name ending in "DeathTest" are run before all other + tests. +3. It uses `clone()` instead of `fork()` to spawn the child process on Linux + (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely + to cause the child to hang when the parent process has multiple threads. + +It's perfectly fine to create threads inside a death test statement; they are +executed in a separate process and cannot affect the parent. + +### Death Test Styles + +The "threadsafe" death test style was introduced in order to help mitigate the +risks of testing in a possibly multithreaded environment. It trades increased +test execution time (potentially dramatically so) for improved thread safety. + +The automated testing framework does not set the style flag. You can choose a +particular style of death tests by setting the flag programmatically: + +```c++ +GTEST_FLAG_SET(death_test_style, "threadsafe"); +``` + +You can do this in `main()` to set the style for all death tests in the binary, +or in individual tests. Recall that flags are saved before running each test and +restored afterwards, so you need not do that yourself. For example: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + GTEST_FLAG_SET(death_test_style, "fast"); + return RUN_ALL_TESTS(); +} + +TEST(MyDeathTest, TestOne) { + GTEST_FLAG_SET(death_test_style, "threadsafe"); + // This test is run in the "threadsafe" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +TEST(MyDeathTest, TestTwo) { + // This test is run in the "fast" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} +``` + +### Caveats + +The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If +it leaves the current function via a `return` statement or by throwing an +exception, the death test is considered to have failed. Some GoogleTest macros +may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid +them in `statement`. + +Since `statement` runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will *not* be observable +in the parent process. In particular, if you release memory in a death test, +your program will fail the heap check as the parent process will never see the +memory reclaimed. To solve this problem, you can + +1. try not to free memory in a death test; +2. free the memory again in the parent process; or +3. do not use the heap checker in your program. + +Due to an implementation detail, you cannot place multiple death test assertions +on the same line; otherwise, compilation will fail with an unobvious error +message. + +Despite the improved thread safety afforded by the "threadsafe" style of death +test, thread problems such as deadlock are still possible in the presence of +handlers registered with `pthread_atfork(3)`. + +## Using Assertions in Sub-routines + +{: .callout .note} +Note: If you want to put a series of test assertions in a subroutine to check +for a complex condition, consider using +[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you +provide a more readable error message in case of failure and avoid all of the +issues described below. + +### Adding Traces to Assertions + +If a test sub-routine is called from several places, when an assertion inside it +fails, it can be hard to tell which invocation of the sub-routine the failure is +from. You can alleviate this problem using extra logging or custom failure +messages, but that usually clutters up your tests. A better solution is to use +the `SCOPED_TRACE` macro or the `ScopedTrace` utility: + +```c++ +SCOPED_TRACE(message); +``` + +```c++ +ScopedTrace trace("file_path", line_number, message); +``` + +where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` +macro will cause the current file name, line number, and the given message to be +added in every failure message. `ScopedTrace` accepts explicit file name and +line number in arguments, which is useful for writing test helpers. The effect +will be undone when the control leaves the current lexical scope. + +For example, + +```c++ +10: void Sub1(int n) { +11: EXPECT_EQ(Bar(n), 1); +12: EXPECT_EQ(Bar(n + 1), 2); +13: } +14: +15: TEST(FooTest, Bar) { +16: { +17: SCOPED_TRACE("A"); // This trace point will be included in +18: // every failure in this scope. +19: Sub1(1); +20: } +21: // Now it won't. +22: Sub1(9); +23: } +``` + +could result in messages like these: + +```none +path/to/foo_test.cc:11: Failure +Value of: Bar(n) +Expected: 1 + Actual: 2 +Google Test trace: +path/to/foo_test.cc:17: A + +path/to/foo_test.cc:12: Failure +Value of: Bar(n + 1) +Expected: 2 + Actual: 3 +``` + +Without the trace, it would've been difficult to know which invocation of +`Sub1()` the two failures come from respectively. (You could add an extra +message to each assertion in `Sub1()` to indicate the value of `n`, but that's +tedious.) + +Some tips on using `SCOPED_TRACE`: + +1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the + beginning of a sub-routine, instead of at each call site. +2. When calling sub-routines inside a loop, make the loop iterator part of the + message in `SCOPED_TRACE` such that you can know which iteration the failure + is from. +3. Sometimes the line number of the trace point is enough for identifying the + particular invocation of a sub-routine. In this case, you don't have to + choose a unique message for `SCOPED_TRACE`. You can simply use `""`. +4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer + scope. In this case, all active trace points will be included in the failure + messages, in reverse order they are encountered. +5. The trace dump is clickable in Emacs - hit `return` on a line number and + you'll be taken to that line in the source file! + +### Propagating Fatal Failures + +A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that +when they fail they only abort the *current function*, not the entire test. For +example, the following test will segfault: + +```c++ +void Subroutine() { + // Generates a fatal failure and aborts the current function. + ASSERT_EQ(1, 2); + + // The following won't be executed. + ... +} + +TEST(FooTest, Bar) { + Subroutine(); // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + + // The actual behavior: the function goes on after Subroutine() returns. + int* p = nullptr; + *p = 3; // Segfault! +} +``` + +To alleviate this, GoogleTest provides three different solutions. You could use +either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the +`HasFatalFailure()` function. They are described in the following two +subsections. + +#### Asserting on Subroutines with an exception + +The following code can turn ASSERT-failure into an exception: + +```c++ +class ThrowListener : public testing::EmptyTestEventListener { + void OnTestPartResult(const testing::TestPartResult& result) override { + if (result.type() == testing::TestPartResult::kFatalFailure) { + throw testing::AssertionException(result); + } + } +}; +int main(int argc, char** argv) { + ... + testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); + return RUN_ALL_TESTS(); +} +``` + +This listener should be added after other listeners if you have any, otherwise +they won't see failed `OnTestPartResult`. + +#### Asserting on Subroutines + +As shown above, if your test calls a subroutine that has an `ASSERT_*` failure +in it, the test will continue after the subroutine returns. This may not be what +you want. + +Often people want fatal failures to propagate like exceptions. For that +GoogleTest offers the following macros: + +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------- | ------------------------------------- | -------- +`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. + +Only failures in the thread that executes the assertion are checked to determine +the result of this type of assertions. If `statement` creates new threads, +failures in these threads are ignored. + +Examples: + +```c++ +ASSERT_NO_FATAL_FAILURE(Foo()); + +int i; +EXPECT_NO_FATAL_FAILURE({ + i = Bar(); +}); +``` + +Assertions from multiple threads are currently not supported on Windows. + +#### Checking for Failures in the Current Test + +`HasFatalFailure()` in the `::testing::Test` class returns `true` if an +assertion in the current test has suffered a fatal failure. This allows +functions to catch fatal failures in a sub-routine and return early. + +```c++ +class Test { + public: + ... + static bool HasFatalFailure(); +}; +``` + +The typical usage, which basically simulates the behavior of a thrown exception, +is: + +```c++ +TEST(FooTest, Bar) { + Subroutine(); + // Aborts if Subroutine() had a fatal failure. + if (HasFatalFailure()) return; + + // The following won't be executed. + ... +} +``` + +If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test +fixture, you must add the `::testing::Test::` prefix, as in: + +```c++ +if (testing::Test::HasFatalFailure()) return; +``` + +Similarly, `HasNonfatalFailure()` returns `true` if the current test has at +least one non-fatal failure, and `HasFailure()` returns `true` if the current +test has at least one failure of either kind. + +## Logging Additional Information + +In your test code, you can call `RecordProperty("key", value)` to log additional +information, where `value` can be either a string or an `int`. The *last* value +recorded for a key will be emitted to the +[XML output](#generating-an-xml-report) if you specify one. For example, the +test + +```c++ +TEST_F(WidgetUsageTest, MinAndMaxWidgets) { + RecordProperty("MaximumWidgets", ComputeMaxUsage()); + RecordProperty("MinimumWidgets", ComputeMinUsage()); +} +``` + +will output XML like this: + +```xml + ... + + ... +``` + +{: .callout .note} +> NOTE: +> +> * `RecordProperty()` is a static member of the `Test` class. Therefore it +> needs to be prefixed with `::testing::Test::` if used outside of the +> `TEST` body and the test fixture class. +> * *`key`* must be a valid XML attribute name, and cannot conflict with the +> ones already used by GoogleTest (`name`, `status`, `time`, `classname`, +> `type_param`, and `value_param`). +> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. +> If it's called outside of a test but between a test suite's +> `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be +> attributed to the XML element for the test suite. If it's called outside +> of all test suites (e.g. in a test environment), it will be attributed to +> the top-level XML element. + +## Sharing Resources Between Tests in the Same Test Suite + +GoogleTest creates a new test fixture object for each test in order to make +tests independent and easier to debug. However, sometimes tests use resources +that are expensive to set up, making the one-copy-per-test model prohibitively +expensive. + +If the tests don't change the resource, there's no harm in their sharing a +single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest +also supports per-test-suite set-up/tear-down. To use it: + +1. In your test fixture class (say `FooTest` ), declare as `static` some member + variables to hold the shared resources. +2. Outside your test fixture class (typically just below it), define those + member variables, optionally giving them initial values. +3. In the same test fixture class, define a public member function `static void + SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a + small `u`!) to set up the shared resources and a `static void + TearDownTestSuite()` function to tear them down. + +That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the +*first test* in the `FooTest` test suite (i.e. before creating the first +`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* +in it (i.e. after deleting the last `FooTest` object). In between, the tests can +use the shared resources. + +Remember that the test order is undefined, so your code can't depend on a test +preceding or following another. Also, the tests must either not modify the state +of any shared resource, or, if they do modify the state, they must restore the +state to its original value before passing control to the next test. + +Note that `SetUpTestSuite()` may be called multiple times for a test fixture +class that has derived classes, so you should not expect code in the function +body to be run only once. Also, derived classes still have access to shared +resources defined as static members, so careful consideration is needed when +managing shared resources to avoid memory leaks if shared resources are not +properly cleaned up in `TearDownTestSuite()`. + +Here's an example of per-test-suite set-up and tear-down: + +```c++ +class FooTest : public testing::Test { + protected: + // Per-test-suite set-up. + // Called before the first test in this test suite. + // Can be omitted if not needed. + static void SetUpTestSuite() { + shared_resource_ = new ...; + + // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`, + // reallocation should be prevented because `SetUpTestSuite()` may be called + // in subclasses of FooTest and lead to memory leak. + // + // if (shared_resource_ == nullptr) { + // shared_resource_ = new ...; + // } + } + + // Per-test-suite tear-down. + // Called after the last test in this test suite. + // Can be omitted if not needed. + static void TearDownTestSuite() { + delete shared_resource_; + shared_resource_ = nullptr; + } + + // You can define per-test set-up logic as usual. + void SetUp() override { ... } + + // You can define per-test tear-down logic as usual. + void TearDown() override { ... } + + // Some expensive resource shared by all tests. + static T* shared_resource_; +}; + +T* FooTest::shared_resource_ = nullptr; + +TEST_F(FooTest, Test1) { + ... you can refer to shared_resource_ here ... +} + +TEST_F(FooTest, Test2) { + ... you can refer to shared_resource_ here ... +} +``` + +{: .callout .note} +NOTE: Though the above code declares `SetUpTestSuite()` protected, it may +sometimes be necessary to declare it public, such as when using it with +`TEST_P`. + +## Global Set-Up and Tear-Down + +Just as you can do set-up and tear-down at the test level and the test suite +level, you can also do it at the test program level. Here's how. + +First, you subclass the `::testing::Environment` class to define a test +environment, which knows how to set-up and tear-down: + +```c++ +class Environment : public ::testing::Environment { + public: + ~Environment() override {} + + // Override this to define how to set up the environment. + void SetUp() override {} + + // Override this to define how to tear down the environment. + void TearDown() override {} +}; +``` + +Then, you register an instance of your environment class with GoogleTest by +calling the `::testing::AddGlobalTestEnvironment()` function: + +```c++ +Environment* AddGlobalTestEnvironment(Environment* env); +``` + +Now, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The +tests are then executed, provided that none of the environments have reported +fatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is +called. + +Note that `SetUp()` and `TearDown()` are only invoked if there is at least one +test to be performed. Importantly, `TearDown()` is executed even if the test is +not run due to a fatal failure or `GTEST_SKIP()`. + +Calling `SetUp()` and `TearDown()` for each iteration depends on the flag +`gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are +called for each environment object when the object is recreated for each +iteration. However, if test environments are not recreated for each iteration, +`SetUp()` is called only on the first iteration, and `TearDown()` is called only +on the last iteration. + +It's OK to register multiple environment objects. In this suite, their `SetUp()` +will be called in the order they are registered, and their `TearDown()` will be +called in the reverse order. + +Note that GoogleTest takes ownership of the registered environment objects. +Therefore **do not delete them** by yourself. + +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, +probably in `main()`. If you use `gtest_main`, you need to call this before +`main()` starts for it to take effect. One way to do this is to define a global +variable like this: + +```c++ +testing::Environment* const foo_env = + testing::AddGlobalTestEnvironment(new FooEnvironment); +``` + +However, we strongly recommend you to write your own `main()` and call +`AddGlobalTestEnvironment()` there, as relying on initialization of global +variables makes the code harder to read and may cause problems when you register +multiple environments from different translation units and the environments have +dependencies among them (remember that the compiler doesn't guarantee the order +in which global variables from different translation units are initialized). + +## Value-Parameterized Tests + +*Value-parameterized tests* allow you to test your code with different +parameters without writing multiple copies of the same test. This is useful in a +number of situations, for example: + +* You have a piece of code whose behavior is affected by one or more + command-line flags. You want to make sure your code performs correctly for + various values of those flags. +* You want to test different implementations of an OO interface. +* You want to test your code over various inputs (a.k.a. data-driven testing). + This feature is easy to abuse, so please exercise your good sense when doing + it! + +### How to Write Value-Parameterized Tests + +To write value-parameterized tests, first you should define a fixture class. It +must be derived from both `testing::Test` and `testing::WithParamInterface` +(the latter is a pure interface), where `T` is the type of your parameter +values. For convenience, you can just derive the fixture class from +`testing::TestWithParam`, which itself is derived from both `testing::Test` +and `testing::WithParamInterface`. `T` can be any copyable type. If it's a +raw pointer, you are responsible for managing the lifespan of the pointed +values. + +{: .callout .note} +NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` +they must be declared **public** rather than **protected** in order to use +`TEST_P`. + +```c++ +class FooTest : + public testing::TestWithParam { + // You can implement all the usual fixture class members here. + // To access the test parameter, call GetParam() from class + // TestWithParam. +}; + +// Or, when you want to add parameters to a pre-existing fixture class: +class BaseTest : public testing::Test { + ... +}; +class BarTest : public BaseTest, + public testing::WithParamInterface { + ... +}; +``` + +Then, use the `TEST_P` macro to define as many test patterns using this fixture +as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. + +```c++ +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} +``` + +Finally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the +test suite with any set of parameters you want. GoogleTest defines a number of +functions for generating test parameters—see details at +[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in +the Testing Reference. + +For example, the following statement will instantiate tests from the `FooTest` +test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the +[`Values`](reference/testing.md#param-generators) parameter generator: + +```c++ +INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, + FooTest, + testing::Values("meeny", "miny", "moe")); +``` + +{: .callout .note} +NOTE: The code above must be placed at global or namespace scope, not at +function scope. + +The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the +instantiation of the test suite. The next argument is the name of the test +pattern, and the last is the +[parameter generator](reference/testing.md#param-generators). + +The parameter generator expression is not evaluated until GoogleTest is +initialized (via `InitGoogleTest()`). Any prior initialization done in the +`main` function will be accessible from the parameter generator, for example, +the results of flag parsing. + +You can instantiate a test pattern more than once, so to distinguish different +instances of the pattern, the instantiation name is added as a prefix to the +actual test suite name. Remember to pick unique prefixes for different +instantiations. The tests from the instantiation above will have these names: + +* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"` + +You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests). + +The following statement will instantiate all tests from `FooTest` again, each +with parameter values `"cat"` and `"dog"` using the +[`ValuesIn`](reference/testing.md#param-generators) parameter generator: + +```c++ +constexpr absl::string_view kPets[] = {"cat", "dog"}; +INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets)); +``` + +The tests from the instantiation above will have these names: + +* `Pets/FooTest.DoesBlah/0` for `"cat"` +* `Pets/FooTest.DoesBlah/1` for `"dog"` +* `Pets/FooTest.HasBlahBlah/0` for `"cat"` +* `Pets/FooTest.HasBlahBlah/1` for `"dog"` + +Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the +given test suite, whether their definitions come before or *after* the +`INSTANTIATE_TEST_SUITE_P` statement. + +Additionally, by default, every `TEST_P` without a corresponding +`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite +`GoogleTestVerification`. If you have a test suite where that omission is not an +error, for example it is in a library that may be linked in for other reasons or +where the list of test cases is dynamic and may be empty, then this check can be +suppressed by tagging the test suite: + +```c++ +GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); +``` + +You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. + +[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example" +[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" + +### Creating Value-Parameterized Abstract Tests + +In the above, we define and instantiate `FooTest` in the *same* source file. +Sometimes you may want to define value-parameterized tests in a library and let +other people instantiate them later. This pattern is known as *abstract tests*. +As an example of its application, when you are designing an interface you can +write a standard suite of abstract tests (perhaps using a factory function as +the test parameter) that all implementations of the interface are expected to +pass. When someone implements the interface, they can instantiate your suite to +get all the interface-conformance tests for free. + +To define abstract tests, you should organize your code like this: + +1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) + in a header file, say `foo_param_test.h`. Think of this as *declaring* your + abstract tests. +2. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes + `foo_param_test.h`. Think of this as *implementing* your abstract tests. + +Once they are defined, you can instantiate them by including `foo_param_test.h`, +invoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that +contains `foo_param_test.cc`. You can instantiate the same abstract test suite +multiple times, possibly in different source files. + +### Specifying Names for Value-Parameterized Test Parameters + +The optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to +specify a function or functor that generates custom test name suffixes based on +the test parameters. The function should accept one argument of type +`testing::TestParamInfo`, and return `std::string`. + +`testing::PrintToStringParamName` is a builtin test suffix generator that +returns the value of `testing::PrintToString(GetParam())`. It does not work for +`std::string` or C strings. + +{: .callout .note} +NOTE: test names must be non-empty, unique, and may only contain ASCII +alphanumeric characters. In particular, they +[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore) + +```c++ +class MyTestSuite : public testing::TestWithParam {}; + +TEST_P(MyTestSuite, MyTest) +{ + std::cout << "Example Test Param: " << GetParam() << std::endl; +} + +INSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10), + testing::PrintToStringParamName()); +``` + +Providing a custom functor allows for more control over test parameter name +generation, especially for types where the automatic conversion does not +generate helpful parameter names (e.g. strings as demonstrated above). The +following example illustrates this for multiple parameters, an enumeration type +and a string, and also demonstrates how to combine generators. It uses a lambda +for conciseness: + +```c++ +enum class MyType { MY_FOO = 0, MY_BAR = 1 }; + +class MyTestSuite : public testing::TestWithParam> { +}; + +INSTANTIATE_TEST_SUITE_P( + MyGroup, MyTestSuite, + testing::Combine( + testing::Values(MyType::MY_FOO, MyType::MY_BAR), + testing::Values("A", "B")), + [](const testing::TestParamInfo& info) { + std::string name = absl::StrCat( + std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar", + std::get<1>(info.param)); + absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); + return name; + }); +``` + +## Typed Tests + +Suppose you have multiple implementations of the same interface and want to make +sure that all of them satisfy some common requirements. Or, you may have defined +several types that are supposed to conform to the same "concept" and you want to +verify it. In both cases, you want the same test logic repeated for different +types. + +While you can write one `TEST` or `TEST_F` for each type you want to test (and +you may even factor the test logic into a function template that you invoke from +the `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` +types, you'll end up writing `m*n` `TEST`s. + +*Typed tests* allow you to repeat the same test logic over a list of types. You +only need to write the test logic once, although you must know the type list +when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized by a type. +Remember to derive it from `::testing::Test`: + +```c++ +template +class FooTest : public testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +Next, associate a list of types with the test suite, which will be repeated for +each type in the list: + +```c++ +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(FooTest, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. Otherwise the compiler will think that each comma in +the type list introduces a new macro argument. + +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this +test suite. You can repeat this as many times as you want: + +```c++ +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } +``` + +You can see [sample6_unittest.cc] for a complete example. + +[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example" + +## Type-Parameterized Tests + +*Type-parameterized tests* are like typed tests, except that they don't require +you to know the list of types ahead of time. Instead, you can define the test +logic first and instantiate it with different type lists later. You can even +instantiate it more than once in the same program. + +If you are designing an interface or concept, you can define a suite of +type-parameterized tests to verify properties that any valid implementation of +the interface/concept should have. Then, the author of each implementation can +just instantiate the test suite with their type to verify that it conforms to +the requirements, without having to write similar tests repeatedly. Here's an +example: + +First, define a fixture class template, as we did with typed tests: + +```c++ +template +class FooTest : public testing::Test { + void DoSomethingInteresting(); + ... +}; +``` + +Next, declare that you will define a type-parameterized test suite: + +```c++ +TYPED_TEST_SUITE_P(FooTest); +``` + +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat +this as many times as you want: + +```c++ +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + + // You will need to use `this` explicitly to refer to fixture members. + this->DoSomethingInteresting() + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } +``` + +Now the tricky part: you need to register all test patterns using the +`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first +argument of the macro is the test suite name; the rest are the names of the +tests in this test suite: + +```c++ +REGISTER_TYPED_TEST_SUITE_P(FooTest, + DoesBlah, HasPropertyA); +``` + +Finally, you are free to instantiate the pattern with the types you want. If you +put the above code in a header file, you can `#include` it in multiple C++ +source files and instantiate it multiple times. + +```c++ +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); +``` + +To distinguish different instances of the pattern, the first argument to the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the +actual test suite name. Remember to pick unique prefixes for different +instances. + +In the special case where the type list contains only one type, you can write +that type directly without `::testing::Types<...>`, like this: + +```c++ +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); +``` + +You can see [sample6_unittest.cc] for a complete example. + +## Testing Private Code + +If you change your software's internal implementation, your tests should not +break as long as the change is not observable by users. Therefore, **per the +black-box testing principle, most of the time you should test your code through +its public interfaces.** + +**If you still find yourself needing to test internal implementation code, +consider if there's a better design.** The desire to test internal +implementation is often a sign that the class is doing too much. Consider +extracting an implementation class, and testing it. Then use that implementation +class in the original class. + +If you absolutely have to test non-public interface code though, you can. There +are two cases to consider: + +* Static functions ( *not* the same as static member functions!) or unnamed + namespaces, and +* Private or protected class members + +To test them, we use the following special techniques: + +* Both static functions and definitions/declarations in an unnamed namespace + are only visible within the same translation unit. To test them, you can + `#include` the entire `.cc` file being tested in your `*_test.cc` file. + (#including `.cc` files is not a good way to reuse code - you should not do + this in production code!) + + However, a better approach is to move the private code into the + `foo::internal` namespace, where `foo` is the namespace your project + normally uses, and put the private declarations in a `*-internal.h` file. + Your production `.cc` files and your tests are allowed to include this + internal header, but your clients are not. This way, you can fully test your + internal implementation without leaking it to your clients. + +* Private class members are only accessible from within the class or by + friends. To access a class' private members, you can declare your test + fixture as a friend to the class and define accessors in your fixture. Tests + using the fixture can then access the private members of your production + class via the accessors in the fixture. Note that even though your fixture + is a friend to your production class, your tests are not automatically + friends to it, as they are technically defined in sub-classes of the + fixture. + + Another way to test private members is to refactor them into an + implementation class, which is then declared in a `*-internal.h` file. Your + clients aren't allowed to include this header but your tests can. Such is + called the + [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) + (Private Implementation) idiom. + + Or, you can declare an individual test as a friend of your class by adding + this line in the class body: + + ```c++ + FRIEND_TEST(TestSuiteName, TestName); + ``` + + For example, + + ```c++ + // foo.h + class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); + + int Bar(void* x); + }; + + // foo_test.cc + ... + TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). + } + ``` + + Pay special attention when your class is defined in a namespace. If you want + your test fixtures and tests to be friends of your class, then they must be + defined in the exact same namespace (no anonymous or inline namespaces). + + For example, if the code to be tested looks like: + + ```c++ + namespace my_namespace { + + class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... definition of the class Foo ... + }; + + } // namespace my_namespace + ``` + + Your test code should be something like: + + ```c++ + namespace my_namespace { + + class FooTest : public testing::Test { + protected: + ... + }; + + TEST_F(FooTest, Bar) { ... } + TEST_F(FooTest, Baz) { ... } + + } // namespace my_namespace + ``` + +## "Catching" Failures + +If you are building a testing utility on top of GoogleTest, you'll want to test +your utility. What framework would you use to test it? GoogleTest, of course. + +The challenge is to verify that your testing utility reports failures correctly. +In frameworks that report a failure by throwing an exception, you could catch +the exception and assert on it. But GoogleTest doesn't use exceptions, so how do +we test that a piece of code generates an expected failure? + +`"gtest/gtest-spi.h"` contains some constructs to do this. +After #including this header, you can use + +```c++ + EXPECT_FATAL_FAILURE(statement, substring); +``` + +to assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the +current thread whose message contains the given `substring`, or use + +```c++ + EXPECT_NONFATAL_FAILURE(statement, substring); +``` + +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. + +Only failures in the current thread are checked to determine the result of this +type of expectations. If `statement` creates new threads, failures in these +threads are also ignored. If you want to catch failures in other threads as +well, use one of the following macros instead: + +```c++ + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); +``` + +{: .callout .note} +NOTE: Assertions from multiple threads are currently not supported on Windows. + +For technical reasons, there are some caveats: + +1. You cannot stream a failure message to either macro. + +2. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference + local non-static variables or non-static members of `this` object. + +3. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a + value. + +## Registering tests programmatically + +The `TEST` macros handle the vast majority of all use cases, but there are few +where runtime registration logic is required. For those cases, the framework +provides the `::testing::RegisterTest` that allows callers to register arbitrary +tests dynamically. + +This is an advanced API only to be used when the `TEST` macros are insufficient. +The macros should be preferred when possible, as they avoid most of the +complexity of calling this function. + +It provides the following signature: + +```c++ +template +TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory); +``` + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the Test object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` for it. + +Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is +undefined. + +Use case example: + +```c++ +class MyFixture : public testing::Test { + public: + // All of these optional, just like in regular macro usage. + static void SetUpTestSuite() { ... } + static void TearDownTestSuite() { ... } + void SetUp() override { ... } + void TearDown() override { ... } +}; + +class MyTest : public MyFixture { + public: + explicit MyTest(int data) : data_(data) {} + void TestBody() override { ... } + + private: + int data_; +}; + +void RegisterMyTests(const std::vector& values) { + for (int v : values) { + testing::RegisterTest( + "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, + std::to_string(v).c_str(), + __FILE__, __LINE__, + // Important to use the fixture type as the return type here. + [=]() -> MyFixture* { return new MyTest(v); }); + } +} +... +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + std::vector values_to_test = LoadValuesFromConfig(); + RegisterMyTests(values_to_test); + ... + return RUN_ALL_TESTS(); +} +``` + +## Getting the Current Test's Name + +Sometimes a function may need to know the name of the currently running test. +For example, you may be using the `SetUp()` method of your test fixture to set +the golden file name based on which test is running. The +[`TestInfo`](reference/testing.md#TestInfo) class has this information. + +To obtain a `TestInfo` object for the currently running test, call +`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest) +singleton object: + +```c++ + // Gets information about the currently running test. + // Do NOT delete the returned object - it's managed by the UnitTest class. + const testing::TestInfo* const test_info = + testing::UnitTest::GetInstance()->current_test_info(); + + printf("We are in test %s of test suite %s.\n", + test_info->name(), + test_info->test_suite_name()); +``` + +`current_test_info()` returns a null pointer if no test is running. In +particular, you cannot find the test suite name in `SetUpTestSuite()`, +`TearDownTestSuite()` (where you know the test suite name implicitly), or +functions called from them. + +## Extending GoogleTest by Handling Test Events + +GoogleTest provides an **event listener API** to let you receive notifications +about the progress of a test program and test failures. The events you can +listen to include the start and end of the test program, a test suite, or a test +method, among others. You may use this API to augment or replace the standard +console output, replace the XML output, or provide a completely different form +of output, such as a GUI or a database. You can also use test events as +checkpoints to implement a resource leak checker, for example. + +### Defining Event Listeners + +To define a event listener, you subclass either +[`testing::TestEventListener`](reference/testing.md#TestEventListener) or +[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener) +The former is an (abstract) interface, where *each pure virtual method can be +overridden to handle a test event* (For example, when a test starts, the +`OnTestStart()` method will be called.). The latter provides an empty +implementation of all methods in the interface, such that a subclass only needs +to override the methods it cares about. + +When an event is fired, its context is passed to the handler function as an +argument. The following argument types are used: + +* UnitTest reflects the state of the entire test program, +* TestSuite has information about a test suite, which can contain one or more + tests, +* TestInfo contains the state of a test, and +* TestPartResult represents the result of a test assertion. + +An event handler function can examine the argument it receives to find out +interesting information about the event and the test program's state. + +Here's an example: + +```c++ + class MinimalistPrinter : public testing::EmptyTestEventListener { + // Called before a test starts. + void OnTestStart(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s starting.\n", + test_info.test_suite_name(), test_info.name()); + } + + // Called after a failed assertion or a SUCCESS(). + void OnTestPartResult(const testing::TestPartResult& test_part_result) override { + printf("%s in %s:%d\n%s\n", + test_part_result.failed() ? "*** Failure" : "Success", + test_part_result.file_name(), + test_part_result.line_number(), + test_part_result.summary()); + } + + // Called after a test ends. + void OnTestEnd(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s ending.\n", + test_info.test_suite_name(), test_info.name()); + } + }; +``` + +### Using Event Listeners + +To use the event listener you have defined, add an instance of it to the +GoogleTest event listener list (represented by class +[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s" +at the end of the name) in your `main()` function, before calling +`RUN_ALL_TESTS()`: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + // Gets hold of the event listener list. + testing::TestEventListeners& listeners = + testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. GoogleTest takes the ownership. + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +} +``` + +There's only one problem: the default test result printer is still in effect, so +its output will mingle with the output from your minimalist printer. To suppress +the default printer, just release it from the event listener list and delete it. +You can do so by adding one line: + +```c++ + ... + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +``` + +Now, sit back and enjoy a completely different output from your tests. For more +details, see [sample9_unittest.cc]. + +[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example" + +You may append more than one listener to the list. When an `On*Start()` or +`OnTestPartResult()` event is fired, the listeners will receive it in the order +they appear in the list (since new listeners are added to the end of the list, +the default text printer and the default XML generator will receive the event +first). An `On*End()` event will be received by the listeners in the *reverse* +order. This allows output by listeners added later to be framed by output from +listeners added earlier. + +### Generating Failures in Listeners + +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) +when processing an event. There are some restrictions: + +1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will + cause `OnTestPartResult()` to be called recursively). +2. A listener that handles `OnTestPartResult()` is not allowed to generate any + failure. + +When you add listeners to the listener list, you should put listeners that +handle `OnTestPartResult()` *before* listeners that can generate failures. This +ensures that failures generated by the latter are attributed to the right test +by the former. + +See [sample10_unittest.cc] for an example of a failure-raising listener. + +[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example" + +## Running Test Programs: Advanced Options + +GoogleTest test programs are ordinary executables. Once built, you can run them +directly and affect their behavior via the following environment variables +and/or command line flags. For the flags to work, your programs must call +`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. + +To see a list of supported flags and their usage, please run your test program +with the `--help` flag. + +If an option is specified both by an environment variable and by a flag, the +latter takes precedence. + +### Selecting Tests + +#### Listing Test Names + +Sometimes it is necessary to list the available tests in a program before +running them so that a filter may be applied if needed. Including the flag +`--gtest_list_tests` overrides all other flags and lists tests in the following +format: + +```none +TestSuite1. + TestName1 + TestName2 +TestSuite2. + TestName +``` + +None of the tests listed are actually run if the flag is provided. There is no +corresponding environment variable for this flag. + +#### Running a Subset of the Tests + +By default, a GoogleTest program runs all tests the user has defined. Sometimes, +you want to run only a subset of the tests (e.g. for debugging or quickly +verifying a change). If you set the `GTEST_FILTER` environment variable or the +`--gtest_filter` flag to a filter string, GoogleTest will only run the tests +whose full names (in the form of `TestSuiteName.TestName`) match the filter. + +The format of a filter is a '`:`'-separated list of wildcard patterns (called +the *positive patterns*) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the *negative patterns*). A test matches +the filter if and only if it matches any of the positive patterns but does not +match any of the negative patterns. + +A pattern may contain `'*'` (matches any string) or `'?'` (matches any single +character). For convenience, the filter `'*-NegativePatterns'` can be also +written as `'-NegativePatterns'`. + +For example: + +* `./foo_test` Has no flag, and thus runs all its tests. +* `./foo_test --gtest_filter=*` Also runs everything, due to the single + match-everything `*` value. +* `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite + `FooTest` . +* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full + name contains either `"Null"` or `"Constructor"` . +* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. +* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test + suite `FooTest` except `FooTest.Bar`. +* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs + everything in test suite `FooTest` except `FooTest.Bar` and everything in + test suite `BarTest` except `BarTest.Foo`. + +#### Stop test execution upon first failure + +By default, a GoogleTest program runs all tests the user has defined. In some +cases (e.g. iterative test development & execution) it may be desirable stop +test execution upon first failure (trading improved latency for completeness). +If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, +the test runner will stop execution as soon as the first test failure is found. + +#### Temporarily Disabling Tests + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +If you need to disable all tests in a test suite, you can either add `DISABLED_` +to the front of the name of each test, or alternatively add it to the front of +the test suite name. + +For example, the following tests won't be run by GoogleTest, even though they +will still be compiled: + +```c++ +// Tests that Foo does Abc. +TEST(FooTest, DISABLED_DoesAbc) { ... } + +class DISABLED_BarTest : public testing::Test { ... }; + +// Tests that Bar does Xyz. +TEST_F(DISABLED_BarTest, DoesXyz) { ... } +``` + +{: .callout .note} +NOTE: This feature should only be used for temporary pain-relief. You still have +to fix the disabled tests at a later date. As a reminder, GoogleTest will print +a banner warning you if a test program contains any disabled tests. + +{: .callout .tip} +TIP: You can easily count the number of disabled tests you have using +`grep`. This number can be used as a metric for +improving your test quality. + +#### Temporarily Enabling Disabled Tests + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. +You can combine this with the `--gtest_filter` flag to further select which +disabled tests to run. + +### Enforcing Having At Least One Test Case + +A not uncommon programmer mistake is to write a test program that has no test +case linked in. This can happen, for example, when you put test case definitions +in a library and the library is not marked as "always link". + +To catch such mistakes, run the test program with the +`--gtest_fail_if_no_test_linked` flag or set the `GTEST_FAIL_IF_NO_TEST_LINKED` +environment variable to a value other than `0`. Now the program will fail if no +test case is linked in. + +Note that *any* test case linked in makes the program valid for the purpose of +this check. In particular, even a disabled test case suffices. + +### Repeating the Tests + +Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it +will fail only 1% of the time, making it rather hard to reproduce the bug under +a debugger. This can be a major source of frustration. + +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in +a program many times. Hopefully, a flaky test will eventually fail and give you +a chance to debug. Here's how to use it: + +```none +$ foo_test --gtest_repeat=1000 +Repeat foo_test 1000 times and don't stop at failures. + +$ foo_test --gtest_repeat=-1 +A negative count means repeating forever. + +$ foo_test --gtest_repeat=1000 --gtest_break_on_failure +Repeat foo_test 1000 times, stopping at the first failure. This +is especially useful when running under a debugger: when the test +fails, it will drop into the debugger and you can then inspect +variables and stacks. + +$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* +Repeat the tests whose name matches the filter 1000 times. +``` + +If your test program contains +[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be +repeated in each iteration as well, as the flakiness may be in it. To avoid +repeating global set-up/tear-down, specify +`--gtest_recreate_environments_when_repeating=false`{.nowrap}. + +You can also specify the repeat count by setting the `GTEST_REPEAT` environment +variable. + +### Shuffling the Tests + +You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` +environment variable to `1`) to run the tests in a program in a random order. +This helps to reveal bad dependencies between tests. + +By default, GoogleTest uses a random seed calculated from the current time. +Therefore you'll get a different order every time. The console output includes +the random seed value, such that you can reproduce an order-related test failure +later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` +flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an +integer in the range [0, 99999]. The seed value 0 is special: it tells +GoogleTest to do the default behavior of calculating the seed from the current +time. + +If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different +random seed and re-shuffle the tests in each iteration. + +### Distributing Test Functions to Multiple Machines + +If you have more than one machine you can use to run a test program, you might +want to run the test functions in parallel and get the result faster. We call +this technique *sharding*, where each machine is called a *shard*. + +GoogleTest is compatible with test sharding. To take advantage of this feature, +your test runner (not part of GoogleTest) needs to do the following: + +1. Allocate a number of machines (shards) to run the tests. +1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total + number of shards. It must be the same for all shards. +1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index + of the shard. Different shards must be assigned different indices, which + must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. +1. Run the same test program on all shards. When GoogleTest sees the above two + environment variables, it will select a subset of the test functions to run. + Across all shards, each test function in the program will be run exactly + once. +1. Wait for all shards to finish, then collect and report the results. + +Your project may have tests that were written without GoogleTest and thus don't +understand this protocol. In order for your test runner to figure out which test +supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` +to a non-existent file path. If a test program supports sharding, it will create +this file to acknowledge that fact; otherwise it will not create it. The actual +contents of the file are not important at this time, although we may put some +useful information in it in the future. + +Here's an example to make it clear. Suppose you have a test program `foo_test` +that contains the following 5 test functions: + +``` +TEST(A, V) +TEST(A, W) +TEST(B, X) +TEST(B, Y) +TEST(B, Z) +``` + +Suppose you have 3 machines at your disposal. To run the test functions in +parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set +`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would +run the same `foo_test` on each machine. + +GoogleTest reserves the right to change how the work is distributed across the +shards, but here's one possible scenario: + +* Machine #0 runs `A.V` and `B.X`. +* Machine #1 runs `A.W` and `B.Y`. +* Machine #2 runs `B.Z`. + +### Controlling Test Output + +#### Colored Terminal Output + +GoogleTest can use colors in its terminal output to make it easier to spot the +important information: + +
...
+[----------] 1 test from FooTest
+[ RUN      ] FooTest.DoesAbc
+[       OK ] FooTest.DoesAbc
+[----------] 2 tests from BarTest
+[ RUN      ] BarTest.HasXyzProperty
+[       OK ] BarTest.HasXyzProperty
+[ RUN      ] BarTest.ReturnsTrueOnSuccess
+... some error messages ...
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+...
+[==========] 30 tests from 14 test suites ran.
+[   PASSED ] 28 tests.
+[   FAILED ] 2 tests, listed below:
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+[   FAILED ] AnotherTest.DoesXyz
+
+ 2 FAILED TESTS
+
+ +You can set the `GTEST_COLOR` environment variable or the `--gtest_color` +command line flag to `yes`, `no`, or `auto` (the default) to enable colors, +disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest +will use colors if and only if the output goes to a terminal and (on non-Windows +platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. + +#### Suppressing test passes + +By default, GoogleTest prints 1 line of output for each test, indicating if it +passed or failed. To show only test failures, run the test program with +`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`. + +#### Suppressing the Elapsed Time + +By default, GoogleTest prints the time it takes to run each test. To disable +that, run the test program with the `--gtest_print_time=0` command line flag, or +set the GTEST_PRINT_TIME environment variable to `0`. + +#### Suppressing UTF-8 Text Output + +In case of assertion failures, GoogleTest prints expected and actual values of +type `string` both as hex-encoded strings as well as in readable UTF-8 text if +they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 +text because, for example, you don't have an UTF-8 compatible output medium, run +the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` +environment variable to `0`. + +#### Generating an XML Report + +GoogleTest can emit a detailed XML report to a file in addition to its normal +textual output. The report contains the duration of each test, and thus can help +you identify slow tests. + +To generate the XML report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will +create the file at the given location. You can also just use the string `"xml"`, +in which case the output can be found in the `test_detail.xml` file in the +current directory. + +If you specify a directory (for example, `"xml:output/directory/"` on Linux or +`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in +that directory, named after the test executable (e.g. `foo_test.xml` for test +program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left +over from a previous run), GoogleTest will pick a different name (e.g. +`foo_test_1.xml`) to avoid overwriting it. + +The report is based on the `junitreport` Ant task. Since that format was +originally intended for Java, a little interpretation is required to make it +apply to GoogleTest tests, as shown here: + +```xml + + + + + + + + + +``` + +* The root `` element corresponds to the entire test program. +* `` elements correspond to GoogleTest test suites. +* `` elements correspond to GoogleTest test functions. + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```xml + + + + + ... + ... + + + + + + + + + +``` + +Things to note: + +* The `tests` attribute of a `` or `` element tells how + many test functions the GoogleTest program or test suite contains, while the + `failures` attribute tells how many of them failed. + +* The `time` attribute expresses the duration of the test, test suite, or + entire test program in seconds. + +* The `timestamp` attribute records the local date and time of the test + execution. + +* The `file` and `line` attributes record the source file location, where the + test was defined. + +* Each `` element corresponds to a single failed GoogleTest + assertion. + +#### Generating a JSON Report + +GoogleTest can also emit a JSON report as an alternative format to XML. To +generate the JSON report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"json:path_to_output_file"`, which will +create the file at the given location. You can also just use the string +`"json"`, in which case the output can be found in the `test_detail.json` file +in the current directory. + +The report format conforms to the following JSON Schema: + +```json +{ + "$schema": "https://json-schema.org/schema#", + "type": "object", + "definitions": { + "TestCase": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "time": { "type": "string" }, + "testsuite": { + "type": "array", + "items": { + "$ref": "#/definitions/TestInfo" + } + } + } + }, + "TestInfo": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "file": { "type": "string" }, + "line": { "type": "integer" }, + "status": { + "type": "string", + "enum": ["RUN", "NOTRUN"] + }, + "time": { "type": "string" }, + "classname": { "type": "string" }, + "failures": { + "type": "array", + "items": { + "$ref": "#/definitions/Failure" + } + } + } + }, + "Failure": { + "type": "object", + "properties": { + "failures": { "type": "string" }, + "type": { "type": "string" } + } + } + }, + "properties": { + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "errors": { "type": "integer" }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "time": { "type": "string" }, + "name": { "type": "string" }, + "testsuites": { + "type": "array", + "items": { + "$ref": "#/definitions/TestCase" + } + } + } +} +``` + +The report uses the format that conforms to the following Proto3 using the +[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): + +```proto +syntax = "proto3"; + +package googletest; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; + +message UnitTest { + int32 tests = 1; + int32 failures = 2; + int32 disabled = 3; + int32 errors = 4; + google.protobuf.Timestamp timestamp = 5; + google.protobuf.Duration time = 6; + string name = 7; + repeated TestCase testsuites = 8; +} + +message TestCase { + string name = 1; + int32 tests = 2; + int32 failures = 3; + int32 disabled = 4; + int32 errors = 5; + google.protobuf.Duration time = 6; + repeated TestInfo testsuite = 7; +} + +message TestInfo { + string name = 1; + string file = 6; + int32 line = 7; + enum Status { + RUN = 0; + NOTRUN = 1; + } + Status status = 2; + google.protobuf.Duration time = 3; + string classname = 4; + message Failure { + string failures = 1; + string type = 2; + } + repeated Failure failures = 5; +} +``` + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```json +{ + "tests": 3, + "failures": 1, + "errors": 0, + "time": "0.035s", + "timestamp": "2011-10-31T18:52:42Z", + "name": "AllTests", + "testsuites": [ + { + "name": "MathTest", + "tests": 2, + "failures": 1, + "errors": 0, + "time": "0.015s", + "testsuite": [ + { + "name": "Addition", + "file": "test.cpp", + "line": 1, + "status": "RUN", + "time": "0.007s", + "classname": "", + "failures": [ + { + "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", + "type": "" + }, + { + "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", + "type": "" + } + ] + }, + { + "name": "Subtraction", + "file": "test.cpp", + "line": 2, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + }, + { + "name": "LogicTest", + "tests": 1, + "failures": 0, + "errors": 0, + "time": "0.005s", + "testsuite": [ + { + "name": "NonContradiction", + "file": "test.cpp", + "line": 3, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + } + ] +} +``` + +{: .callout .important} +IMPORTANT: The exact format of the JSON document is subject to change. + +### Controlling How Failures Are Reported + +#### Detecting Test Premature Exit + +Google Test implements the *premature-exit-file* protocol for test runners to +catch any kind of unexpected exits of test programs. Upon start, Google Test +creates the file which will be automatically deleted after all work has been +finished. Then, the test runner can check if this file exists. In case the file +remains undeleted, the inspected test has exited prematurely. + +This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment +variable has been set. + +#### Turning Assertion Failures into Break-Points + +When running test programs under a debugger, it's very convenient if the +debugger can catch an assertion failure and automatically drop into interactive +mode. GoogleTest's *break-on-failure* mode supports this behavior. + +To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value +other than `0`. Alternatively, you can use the `--gtest_break_on_failure` +command line flag. + +#### Disabling Catching Test-Thrown Exceptions + +GoogleTest can be used either with or without exceptions enabled. If a test +throws a C++ exception or (on Windows) a structured exception (SEH), by default +GoogleTest catches it, reports it as a test failure, and continues with the next +test method. This maximizes the coverage of a test run. Also, on Windows an +uncaught exception will cause a pop-up window, so catching the exceptions allows +you to run the tests automatically. + +When debugging the test failures, however, you may instead want the exceptions +to be handled by the debugger, such that you can examine the call stack when an +exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` +environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when +running the tests. + +### Sanitizer Integration + +The +[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), +[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer), +and +[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) +all provide weak functions that you can override to trigger explicit failures +when they detect sanitizer errors, such as creating a reference from `nullptr`. +To override these functions, place definitions for them in a source file that +you compile as part of your main binary: + +``` +extern "C" { +void __ubsan_on_report() { + FAIL() << "Encountered an undefined behavior sanitizer error"; +} +void __asan_on_error() { + FAIL() << "Encountered an address sanitizer error"; +} +void __tsan_on_report() { + FAIL() << "Encountered a thread sanitizer error"; +} +} // extern "C" +``` + +After compiling your project with one of the sanitizers enabled, if a particular +test triggers a sanitizer error, GoogleTest will report that it failed. diff --git a/sw/restatdesk_tests/googletest/docs/assets/css/style.scss b/sw/restatdesk_tests/googletest/docs/assets/css/style.scss new file mode 100644 index 0000000..bb30f41 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/assets/css/style.scss @@ -0,0 +1,5 @@ +--- +--- + +@import "jekyll-theme-primer"; +@import "main"; diff --git a/sw/restatdesk_tests/googletest/docs/community_created_documentation.md b/sw/restatdesk_tests/googletest/docs/community_created_documentation.md new file mode 100644 index 0000000..4569075 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/community_created_documentation.md @@ -0,0 +1,7 @@ +# Community-Created Documentation + +The following is a list, in no particular order, of links to documentation +created by the Googletest community. + +* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md), + by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy) diff --git a/sw/restatdesk_tests/googletest/docs/faq.md b/sw/restatdesk_tests/googletest/docs/faq.md new file mode 100644 index 0000000..4e95838 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/faq.md @@ -0,0 +1,658 @@ +# GoogleTest FAQ + +## Why should test suite names and test names not contain underscore? + +{: .callout .note} +Note: GoogleTest reserves underscore (`_`) for special-purpose keywords, such as +[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition +to the following rationale. + +Underscore (`_`) is special, as C++ reserves the following to be used by the +compiler and the standard library: + +1. any identifier that starts with an `_` followed by an upper-case letter, and +2. any identifier that contains two consecutive underscores (i.e. `__`) + *anywhere* in its name. + +User code is *prohibited* from using such identifiers. + +Now let's look at what this means for `TEST` and `TEST_F`. + +Currently `TEST(TestSuiteName, TestName)` generates a class named +`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName` +contains `_`? + +1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say, + `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus + invalid. +2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get + `Foo__TestName_Test`, which is invalid. +3. If `TestName` starts with an `_` (say, `_Bar`), we get + `TestSuiteName__Bar_Test`, which is invalid. +4. If `TestName` ends with an `_` (say, `Bar_`), we get + `TestSuiteName_Bar__Test`, which is invalid. + +So clearly `TestSuiteName` and `TestName` cannot start or end with `_` +(Actually, `TestSuiteName` can start with `_`—as long as the `_` isn't followed +by an upper-case letter. But that's getting complicated. So for simplicity we +just say that it cannot start with `_`.). + +It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the +middle. However, consider this: + +```c++ +TEST(Time, Flies_Like_An_Arrow) { ... } +TEST(Time_Flies, Like_An_Arrow) { ... } +``` + +Now, the two `TEST`s will both generate the same class +(`Time_Flies_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and +`TestName`. The rule is more constraining than necessary, but it's simple and +easy to remember. It also gives GoogleTest some wiggle room in case its +implementation needs to change in the future. + +If you violate the rule, there may not be immediate consequences, but your test +may (just may) break with a new compiler (or a new version of the compiler you +are using) or with a new version of GoogleTest. Therefore it's best to follow +the rule. + +## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? + +First of all, you can use `nullptr` with each of these macros, e.g. +`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`, +`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide +because `nullptr` does not have the type problems that `NULL` does. + +Due to some peculiarity of C++, it requires some non-trivial template meta +programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` +and `ASSERT_XX()` macros. Therefore we only do it where it's most needed +(otherwise we make the implementation of GoogleTest harder to maintain and more +error-prone than necessary). + +Historically, the `EXPECT_EQ()` macro took the *expected* value as its first +argument and the *actual* value as the second, though this argument order is now +discouraged. It was reasonable that someone wanted +to write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested +several times. Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion +fails, you already know that `ptr` must be `NULL`, so it doesn't add any +information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)` +works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to +support `EXPECT_NE(ptr, NULL)` as well. This means using the template meta +programming tricks twice in the implementation, making it even harder to +understand and maintain. We believe the benefit doesn't justify the cost. + +Finally, with the growth of the gMock matcher library, we are encouraging people +to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One +significant advantage of the matcher approach is that matchers can be easily +combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be +easily combined. Therefore we want to invest more in the matchers than in the +`EXPECT_XX()` macros. + +## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests? + +For testing various implementations of the same interface, either typed tests or +value-parameterized tests can get it done. It's really up to you the user to +decide which is more convenient for you, depending on your particular case. Some +rough guidelines: + +* Typed tests can be easier to write if instances of the different + implementations can be created the same way, modulo the type. For example, + if all these implementations have a public default constructor (such that + you can write `new TypeParam`), or if their factory functions have the same + form (e.g. `CreateInstance()`). +* Value-parameterized tests can be easier to write if you need different code + patterns to create different implementations' instances, e.g. `new Foo` vs + `new Bar(5)`. To accommodate for the differences, you can write factory + function wrappers and pass these function pointers to the tests as their + parameters. +* When a typed test fails, the default output includes the name of the type, + which can help you quickly identify which implementation is wrong. + Value-parameterized tests only show the number of the failed iteration by + default. You will need to define a function that returns the iteration name + and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more + useful output. +* When using typed tests, you need to make sure you are testing against the + interface type, not the concrete types (in other words, you want to make + sure `implicit_cast(my_concrete_impl)` works, not just that + `my_concrete_impl` works). It's less likely to make mistakes in this area + when using value-parameterized tests. + +I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give +both approaches a try. Practice is a much better way to grasp the subtle +differences between the two tools. Once you have some concrete experience, you +can much more easily decide which one to use the next time. + +## My death test modifies some state, but the change seems lost after the death test finishes. Why? + +Death tests (`EXPECT_DEATH`, etc.) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their respective +sub-processes, but not in the parent process. You can think of them as running +in a parallel universe, more or less. + +In particular, if you use mocking and the death test statement invokes some mock +methods, the parent process will think the calls have never occurred. Therefore, +you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` +macro. + +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug? + +Actually, the bug is in `htonl()`. + +According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to +use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as +a *macro*, which breaks this usage. + +Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not* +standard C++. That hacky implementation has some ad hoc limitations. In +particular, it prevents you from writing `Foo()`, where `Foo` +is a template that has an integral argument. + +The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a +template argument, and thus doesn't compile in opt mode when `a` contains a call +to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as +the solution must work with different compilers on various platforms. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? + +If your class has a static data member: + +```c++ +// foo.h +class Foo { + ... + static const int kBar = 100; +}; +``` + +you also need to define it *outside* of the class body in `foo.cc`: + +```c++ +const int Foo::kBar; // No initializer here. +``` + +Otherwise your code is **invalid C++**, and may break in unexpected ways. In +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc.) +will generate an "undefined reference" linker error. The fact that "it used to +work" doesn't mean it's valid. It just means that you were lucky. :-) + +If the declaration of the static data member is `constexpr` then it is +implicitly an `inline` definition, and a separate definition in `foo.cc` is not +needed: + +```c++ +// foo.h +class Foo { + ... + static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc. +}; +``` + +## Can I derive a test fixture from another? + +Yes. + +Each test fixture has a corresponding and same named test suite. This means only +one test suite can use a particular fixture. Sometimes, however, multiple test +cases may want to use the same or slightly different fixtures. For example, you +may want to make sure that all of a GUI library's test suites don't leak +important system resources like fonts and brushes. + +In GoogleTest, you share a fixture among test suites by putting the shared logic +in a base test fixture, then deriving from that base a separate fixture for each +test suite that wants to use this common logic. You then use `TEST_F()` to write +tests using each derived fixture. + +Typically, your code looks like this: + +```c++ +// Defines a base test fixture. +class BaseTest : public ::testing::Test { + protected: + ... +}; + +// Derives a fixture FooTest from BaseTest. +class FooTest : public BaseTest { + protected: + void SetUp() override { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + + void TearDown() override { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + + ... functions and variables for FooTest ... +}; + +// Tests that use the fixture FooTest. +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +... additional fixtures derived from BaseTest ... +``` + +If necessary, you can continue to derive test fixtures from a derived fixture. +GoogleTest has no limit on how deep the hierarchy can be. + +For a complete example using derived test fixtures, see +[sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc). + +## My compiler complains "void value not ignored as it ought to be." What does this mean? + +You're probably using an `ASSERT_*()` in a function that doesn't return `void`. +`ASSERT_*()` can only be used in `void` functions, due to exceptions being +disabled by our build system. Please see more details +[here](advanced.md#assertion-placement). + +## My death test hangs (or seg-faults). How do I fix it? + +In GoogleTest, death tests are run in a child process and the way they work is +delicate. To write death tests you really need to understand how they work—see +the details at [Death Assertions](reference/assertions.md#death) in the +Assertions Reference. + +In particular, death tests don't like having multiple threads in the parent +process. So the first thing you can try is to eliminate creating threads outside +of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects +instead of real ones in your tests. + +Sometimes this is impossible as some library you must use may be creating +threads before `main()` is even reached. In this case, you can try to minimize +the chance of conflicts by either moving as many activities as possible inside +`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or +leaving as few things as possible in it. Also, you can try to set the death test +style to `"threadsafe"`, which is safer but slower, and see if it helps. + +If you go with thread-safe death tests, remember that they rerun the test +program from the beginning in the child process. Therefore make sure your +program can run side-by-side with itself and is deterministic. + +In the end, this boils down to good concurrent programming. You have to make +sure that there are no race conditions or deadlocks in your program. No silver +bullet - sorry! + +## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp} + +The first thing to remember is that GoogleTest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, GoogleTest will create +a **fresh** test fixture object, immediately call `SetUp()`, run the test body, +call `TearDown()`, and then delete the test fixture object. + +When you need to write per-test set-up and tear-down logic, you have the choice +between using the test fixture constructor/destructor or `SetUp()`/`TearDown()`. +The former is usually preferred, as it has the following benefits: + +* By initializing a member variable in the constructor, we have the option to + make it `const`, which helps prevent accidental changes to its value and + makes the tests more obviously correct. +* In case we need to subclass the test fixture class, the subclass' + constructor is guaranteed to call the base class' constructor *first*, and + the subclass' destructor is guaranteed to call the base class' destructor + *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of + forgetting to call the base class' `SetUp()/TearDown()` or call them at the + wrong time. + +You may still want to use `SetUp()/TearDown()` in the following cases: + +* C++ does not allow virtual function calls in constructors and destructors. + You can call a method declared as virtual, but it will not use dynamic + dispatch. It will use the definition from the class the constructor of which + is currently executing. This is because calling a virtual method before the + derived class constructor has a chance to run is very dangerous - the + virtual method might operate on uninitialized data. Therefore, if you need + to call a method that will be overridden in a derived class, you have to use + `SetUp()/TearDown()`. +* In the body of a constructor (or destructor), it's not possible to use the + `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal + test failure that should prevent the test from running, it's necessary to + use `abort` and abort the whole test + executable, or to use `SetUp()` instead of a constructor. +* If the tear-down operation could throw an exception, you must use + `TearDown()` as opposed to the destructor, as throwing in a destructor leads + to undefined behavior and usually will kill your program right away. Note + that many standard libraries (like STL) may throw when exceptions are + enabled in the compiler. Therefore you should prefer `TearDown()` if you + want to write portable tests that work with or without exceptions. +* The GoogleTest team is considering making the assertion macros throw on + platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux + client-side), which will eliminate the need for the user to propagate + failures from a subroutine to its caller. Therefore, you shouldn't use + GoogleTest assertions in a destructor if your code could run on such a + platform. + +## The compiler complains "no matching function to call" when I use `ASSERT_PRED*`. How do I fix it? + +See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the +Assertions Reference. + +## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? + +Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, +instead of + +```c++ + return RUN_ALL_TESTS(); +``` + +they write + +```c++ + RUN_ALL_TESTS(); +``` + +This is **wrong and dangerous**. The testing services needs to see the return +value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your +`main()` function ignores it, your test will be considered successful even if it +has a GoogleTest assertion failure. Very bad. + +We have decided to fix this (thanks to Michael Chastain for the idea). Now, your +code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with +`gcc`. If you do so, you'll get a compiler error. + +If you see the compiler complaining about you ignoring the return value of +`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the +return value of `main()`. + +But how could we introduce a change that breaks existing tests? Well, in this +case, the code was already broken in the first place, so we didn't break it. :-) + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? + +Due to a peculiarity of C++, in order to support the syntax for streaming +messages to an `ASSERT_*`, e.g. + +```c++ + ASSERT_EQ(1, Foo()) << "blah blah" << foo; +``` + +we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and +`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the +content of your constructor/destructor to a private void member function, or +switch to `EXPECT_*()` if that works. This +[section](advanced.md#assertion-placement) in the user's guide explains it. + +## My SetUp() function is not called. Why? + +C++ is case-sensitive. Did you spell it as `Setup()`? + +Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and +wonder why it's never called. + +## I have several test suites which share the same test fixture logic; do I have to define a new test fixture class for each of them? This seems pretty tedious. + +You don't have to. Instead of + +```c++ +class FooTest : public BaseTest {}; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +class BarTest : public BaseTest {}; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +you can simply `typedef` the test fixtures: + +```c++ +typedef BaseTest FooTest; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef BaseTest BarTest; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +## GoogleTest output is buried in a whole bunch of LOG messages. What do I do? + +The GoogleTest output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the GoogleTest +output, making it hard to read. However, there is an easy solution to this +problem. + +Since `LOG` messages go to stderr, we decided to let GoogleTest output go to +stdout. This way, you can easily separate the two using redirection. For +example: + +```shell +$ ./my_test > gtest_output.txt +``` + +## Why should I prefer test fixtures over global variables? + +There are several good reasons: + +1. It's likely your test needs to change the states of its global variables. + This makes it difficult to keep side effects from escaping one test and + contaminating others, making debugging difficult. By using fixtures, each + test has a fresh set of variables that's different (but with the same + names). Thus, tests are kept independent of each other. +2. Global variables pollute the global namespace. +3. Test fixtures can be reused via subclassing, which cannot be done easily + with global variables. This is useful if many test suites have something in + common. + +## What can the statement argument in ASSERT_DEATH() be? + +`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used +wherever *`statement`* is valid. So basically *`statement`* can be any C++ +statement that makes sense in the current context. In particular, it can +reference global and/or local variables, and can be: + +* a simple function call (often the case), +* a complex expression, or +* a compound statement. + +Some examples are shown here: + +```c++ +// A death test can be a simple function call. +TEST(MyDeathTest, FunctionCall) { + ASSERT_DEATH(Xyz(5), "Xyz failed"); +} + +// Or a complex expression that references variables and functions. +TEST(MyDeathTest, ComplexExpression) { + const bool c = Condition(); + ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), + "(Func1|Method) failed"); +} + +// Death assertions can be used anywhere in a function. In +// particular, they can be inside a loop. +TEST(MyDeathTest, InsideLoop) { + // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. + for (int i = 0; i < 5; i++) { + EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", + ::testing::Message() << "where i is " << i); + } +} + +// A death assertion can contain a compound statement. +TEST(MyDeathTest, CompoundStatement) { + // Verifies that at lease one of Bar(0), Bar(1), ..., and + // Bar(4) dies. + ASSERT_DEATH({ + for (int i = 0; i < 5; i++) { + Bar(i); + } + }, + "Bar has \\d+ errors"); +} +``` + +## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? + +GoogleTest needs to be able to create objects of your test fixture class, so it +must have a default constructor. Normally the compiler will define one for you. +However, there are cases where you have to define your own: + +* If you explicitly declare a non-default constructor for class `FooTest` + (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a + default constructor, even if it would be empty. +* If `FooTest` has a const non-static data member, then you have to define the + default constructor *and* initialize the const member in the initializer + list of the constructor. (Early versions of `gcc` doesn't force you to + initialize the const member. It's a bug that has been fixed in `gcc 4`.) + +## Why does GoogleTest require the entire test suite, instead of individual tests, to be named `*DeathTest` when it uses `ASSERT_DEATH`? + +GoogleTest does not interleave tests from different test suites. That is, it +runs all tests in one test suite first, and then runs all tests in the next test +suite, and so on. GoogleTest does this because it needs to set up a test suite +before the first test in it is run, and tear it down afterwards. Splitting up +the test case would require multiple set-up and tear-down processes, which is +inefficient and makes the semantics unclean. + +If we were to determine the order of tests based on test name instead of test +case name, then we would have a problem with the following situation: + +```c++ +TEST_F(FooTest, AbcDeathTest) { ... } +TEST_F(FooTest, Uvw) { ... } + +TEST_F(BarTest, DefDeathTest) { ... } +TEST_F(BarTest, Xyz) { ... } +``` + +Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't +interleave tests from different test suites, we need to run all tests in the +`FooTest` case before running any test in the `BarTest` case. This contradicts +with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. + +## But I don't like calling my entire test suite `*DeathTest` when it contains both death tests and non-death tests. What do I do? + +You don't have to, but if you like, you may split up the test suite into +`FooTest` and `FooDeathTest`, where the names make it clear that they are +related: + +```c++ +class FooTest : public ::testing::Test { ... }; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +using FooDeathTest = FooTest; + +TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } +TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } +``` + +## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? + +Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` +makes it harder to search for real problems in the parent's log. Therefore, +GoogleTest only prints them when the death test has failed. + +If you really need to see such LOG messages, a workaround is to temporarily +break the death test (e.g. by changing the regex pattern it is expected to +match). Admittedly, this is a hack. We'll consider a more permanent solution +after the fork-and-exec-style death tests are implemented. + +## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives? + +If you use a user-defined type `FooType` in an assertion, you must make sure +there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function +defined such that we can print a value of `FooType`. + +In addition, if `FooType` is declared in a name space, the `<<` operator also +needs to be defined in the *same* name space. See +[Tip of the Week #49](https://abseil.io/tips/49) for details. + +## How do I suppress the memory leak messages on Windows? + +Since the statically initialized GoogleTest singleton requires allocations on +the heap, the Visual C++ memory leak detector will report memory leaks at the +end of the program run. The easiest way to avoid this is to use the +`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any +statically initialized heap objects. See MSDN for more details and additional +heap check/debug routines. + +## How can my code detect if it is running in a test? + +If you write code that sniffs whether it's running in a test and does different +things accordingly, you are leaking test-only logic into production code and +there is no easy way to ensure that the test-only code paths aren't run by +mistake in production. Such cleverness also leads to +[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly +advise against the practice, and GoogleTest doesn't provide a way to do it. + +In general, the recommended way to cause the code to behave differently under +test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject +different functionality from the test and from the production code. Since your +production code doesn't link in the for-test logic at all (the +[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure +that), there is no danger in accidentally running it. + +However, if you *really*, *really*, *really* have no choice, and if you follow +the rule of ending your test program names with `_test`, you can use the +*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know +whether the code is under test. + +## How do I temporarily disable a test? + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag. + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? + +Yes. + +The rule is **all test methods in the same test suite must use the same fixture +class**. This means that the following is **allowed** because both tests use the +same fixture class (`::testing::Test`). + +```c++ +namespace foo { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` + +However, the following code is **not allowed** and will produce a runtime error +from GoogleTest because the test methods are using different test fixture +classes with the same test suite name. + +```c++ +namespace foo { +class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` diff --git a/sw/restatdesk_tests/googletest/docs/gmock_cheat_sheet.md b/sw/restatdesk_tests/googletest/docs/gmock_cheat_sheet.md new file mode 100644 index 0000000..ddafaaa --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/gmock_cheat_sheet.md @@ -0,0 +1,241 @@ +# gMock Cheat Sheet + +## Defining a Mock Class + +### Mocking a Normal Class {#MockClass} + +Given + +```cpp +class Foo { + public: + virtual ~Foo(); + virtual int GetSize() const = 0; + virtual string Describe(const char* name) = 0; + virtual string Describe(int type) = 0; + virtual bool Process(Bar elem, int count) = 0; +}; +``` + +(note that `~Foo()` **must** be virtual) we can define its mock as + +```cpp +#include + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(string, Describe, (const char* name), (override)); + MOCK_METHOD(string, Describe, (int type), (override)); + MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); +}; +``` + +To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, +which warns on all uninteresting calls, or a "strict" mock, which treats them as +failures: + +```cpp +using ::testing::NiceMock; +using ::testing::NaggyMock; +using ::testing::StrictMock; + +NiceMock nice_foo; // The type is a subclass of MockFoo. +NaggyMock naggy_foo; // The type is a subclass of MockFoo. +StrictMock strict_foo; // The type is a subclass of MockFoo. +``` + +{: .callout .note} +**Note:** A mock object is currently naggy by default. We may make it nice by +default in the future. + +### Mocking a Class Template {#MockTemplate} + +Class templates can be mocked just like any class. + +To mock + +```cpp +template +class StackInterface { + public: + virtual ~StackInterface(); + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; +``` + +(note that all member functions that are mocked, including `~StackInterface()` +**must** be virtual). + +```cpp +template +class MockStack : public StackInterface { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Specifying Calling Conventions for Mock Functions + +If your mock function doesn't use the default calling convention, you can +specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. +For example, + +```cpp + MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); + MOCK_METHOD(int, Bar, (double x, double y), + (const, Calltype(STDMETHODCALLTYPE))); +``` + +where `STDMETHODCALLTYPE` is defined by `` on Windows. + +## Using Mocks in Tests {#UsingMocks} + +The typical work flow is: + +1. Import the gMock names you need to use. All gMock symbols are in the + `testing` namespace unless they are macros or otherwise noted. +2. Create the mock objects. +3. Optionally, set the default actions of the mock objects. +4. Set your expectations on the mock objects (How will they be called? What + will they do?). +5. Exercise code that uses the mock objects; if necessary, check the result + using googletest assertions. +6. When a mock object is destructed, gMock automatically verifies that all + expectations on it have been satisfied. + +Here's an example: + +```cpp +using ::testing::Return; // #1 + +TEST(BarTest, DoesThis) { + MockFoo foo; // #2 + + ON_CALL(foo, GetSize()) // #3 + .WillByDefault(Return(1)); + // ... other default actions ... + + EXPECT_CALL(foo, Describe(5)) // #4 + .Times(3) + .WillRepeatedly(Return("Category 5")); + // ... other expectations ... + + EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 +} // #6 +``` + +## Setting Default Actions {#OnCall} + +gMock has a **built-in default action** for any function that returns `void`, +`bool`, a numeric value, or a pointer. In C++11, it will additionally returns +the default-constructed value, if one exists for the given type. + +To customize the default action for functions with return type `T`, use +[`DefaultValue`](reference/mocking.md#DefaultValue). For example: + +```cpp + // Sets the default action for return type std::unique_ptr to + // creating a new Buzz every time. + DefaultValue>::SetFactory( + [] { return std::make_unique(AccessLevel::kInternal); }); + + // When this fires, the default action of MakeBuzz() will run, which + // will return a new Buzz object. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); + + auto buzz1 = mock_buzzer_.MakeBuzz("hello"); + auto buzz2 = mock_buzzer_.MakeBuzz("hello"); + EXPECT_NE(buzz1, nullptr); + EXPECT_NE(buzz2, nullptr); + EXPECT_NE(buzz1, buzz2); + + // Resets the default action for return type std::unique_ptr, + // to avoid interfere with other tests. + DefaultValue>::Clear(); +``` + +To customize the default action for a particular method of a specific mock +object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar +syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you +do not require that the mock method is called. See +[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed +discussion. + +## Setting Expectations {#ExpectCall} + +See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference. + +## Matchers {#MatcherList} + +See the [Matchers Reference](reference/matchers.md). + +## Actions {#ActionList} + +See the [Actions Reference](reference/actions.md). + +## Cardinalities {#CardinalityList} + +See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of +`EXPECT_CALL` in the Mocking Reference. + +## Expectation Order + +By default, expectations can be matched in *any* order. If some or all +expectations must be matched in a given order, you can use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) or +[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of +`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence). + +## Verifying and Resetting a Mock + +gMock will verify the expectations on a mock object when it is destructed, or +you can do it earlier: + +```cpp +using ::testing::Mock; +... +// Verifies and removes the expectations on mock_obj; +// returns true if and only if successful. +Mock::VerifyAndClearExpectations(&mock_obj); +... +// Verifies and removes the expectations on mock_obj; +// also removes the default actions set by ON_CALL(); +// returns true if and only if successful. +Mock::VerifyAndClear(&mock_obj); +``` + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +You can also tell gMock that a mock object can be leaked and doesn't need to be +verified: + +```cpp +Mock::AllowLeak(&mock_obj); +``` + +## Mock Classes + +gMock defines a convenient mock class template + +```cpp +class MockFunction { + public: + MOCK_METHOD(R, Call, (A1, ..., An)); +}; +``` + +See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of +it. + +## Flags + +| Flag | Description | +| :----------------------------- | :---------------------------------------- | +| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | +| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | diff --git a/sw/restatdesk_tests/googletest/docs/gmock_cook_book.md b/sw/restatdesk_tests/googletest/docs/gmock_cook_book.md new file mode 100644 index 0000000..9e59b4c --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/gmock_cook_book.md @@ -0,0 +1,4412 @@ +# gMock Cookbook + +You can find recipes for using gMock here. If you haven't yet, please read +[the dummy guide](gmock_for_dummies.md) first to make sure you understand the +basics. + +{: .callout .note} +**Note:** gMock lives in the `testing` name space. For readability, it is +recommended to write `using ::testing::Foo;` once in your file before using the +name `Foo` defined by gMock. We omit such `using` statements in this section for +brevity, but you should do it in your own code. + +## Creating Mock Classes + +Mock classes are defined as normal classes, using the `MOCK_METHOD` macro to +generate mocked methods. The macro gets 3 or 4 parameters: + +```cpp +class MyMock { + public: + MOCK_METHOD(ReturnType, MethodName, (Args...)); + MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...)); +}; +``` + +The first 3 parameters are simply the method declaration, split into 3 parts. +The 4th parameter accepts a closed list of qualifiers, which affect the +generated method: + +* **`const`** - Makes the mocked method a `const` method. Required if + overriding a `const` method. +* **`override`** - Marks the method with `override`. Recommended if overriding + a `virtual` method. +* **`noexcept`** - Marks the method with `noexcept`. Required if overriding a + `noexcept` method. +* **`Calltype(...)`** - Sets the call type for the method (e.g. to + `STDMETHODCALLTYPE`), useful in Windows. +* **`ref(...)`** - Marks the method with the reference qualification + specified. Required if overriding a method that has reference + qualifications. Eg `ref(&)` or `ref(&&)`. + +### Dealing with unprotected commas + +Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent +`MOCK_METHOD` from parsing its arguments correctly: + +{: .bad} +```cpp +class MockFoo { + public: + MOCK_METHOD(std::pair, GetPair, ()); // Won't compile! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Won't compile! +}; +``` + +Solution 1 - wrap with parentheses: + +{: .good} +```cpp +class MockFoo { + public: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); +}; +``` + +Note that wrapping a return or argument type with parentheses is, in general, +invalid C++. `MOCK_METHOD` removes the parentheses. + +Solution 2 - define an alias: + +{: .good} +```cpp +class MockFoo { + public: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +### Mocking Private or Protected Methods + +You must always put a mock method definition (`MOCK_METHOD`) in a `public:` +section of the mock class, regardless of the method being mocked being `public`, +`protected`, or `private` in the base class. This allows `ON_CALL` and +`EXPECT_CALL` to reference the mock function from outside of the mock class. +(Yes, C++ allows a subclass to change the access level of a virtual function in +the base class.) Example: + +```cpp +class Foo { + public: + ... + virtual bool Transform(Gadget* g) = 0; + + protected: + virtual void Resume(); + + private: + virtual int GetTimeOut(); +}; + +class MockFoo : public Foo { + public: + ... + MOCK_METHOD(bool, Transform, (Gadget* g), (override)); + + // The following must be in the public section, even though the + // methods are protected or private in the base class. + MOCK_METHOD(void, Resume, (), (override)); + MOCK_METHOD(int, GetTimeOut, (), (override)); +}; +``` + +### Mocking Overloaded Methods + +You can mock overloaded functions as usual. No special attention is required: + +```cpp +class Foo { + ... + + // Must be virtual as we'll inherit from Foo. + virtual ~Foo(); + + // Overloaded on the types and/or numbers of arguments. + virtual int Add(Element x); + virtual int Add(int times, Element x); + + // Overloaded on the const-ness of this object. + virtual Bar& GetBar(); + virtual const Bar& GetBar() const; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(int, Add, (Element x), (override)); + MOCK_METHOD(int, Add, (int times, Element x), (override)); + + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; +``` + +{: .callout .note} +**Note:** if you don't mock all versions of the overloaded method, the compiler +will give you a warning about some methods in the base class being hidden. To +fix that, use `using` to bring them in scope: + +```cpp +class MockFoo : public Foo { + ... + using Foo::Add; + MOCK_METHOD(int, Add, (Element x), (override)); + // We don't want to mock int Add(int times, Element x); + ... +}; +``` + +### Mocking Class Templates + +You can mock class templates just like any class. + +```cpp +template +class StackInterface { + ... + // Must be virtual as we'll inherit from StackInterface. + virtual ~StackInterface(); + + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; + +template +class MockStack : public StackInterface { + ... + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Mocking Non-virtual Methods {#MockingNonVirtualMethods} + +gMock can mock non-virtual functions to be used in Hi-perf dependency injection. + +In this case, instead of sharing a common base class with the real class, your +mock class will be *unrelated* to the real class, but contain methods with the +same signatures. The syntax for mocking non-virtual methods is the *same* as +mocking virtual methods (just don't add `override`): + +```cpp +// A simple packet stream class. None of its members is virtual. +class ConcretePacketStream { + public: + void AppendPacket(Packet* new_packet); + const Packet* GetPacket(size_t packet_number) const; + size_t NumberOfPackets() const; + ... +}; + +// A mock packet stream class. It inherits from no other, but defines +// GetPacket() and NumberOfPackets(). +class MockPacketStream { + public: + MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const)); + MOCK_METHOD(size_t, NumberOfPackets, (), (const)); + ... +}; +``` + +Note that the mock class doesn't define `AppendPacket()`, unlike the real class. +That's fine as long as the test doesn't need to call it. + +Next, you need a way to say that you want to use `ConcretePacketStream` in +production code, and use `MockPacketStream` in tests. Since the functions are +not virtual and the two classes are unrelated, you must specify your choice at +*compile time* (as opposed to run time). + +One way to do it is to templatize your code that needs to use a packet stream. +More specifically, you will give your code a template type argument for the type +of the packet stream. In production, you will instantiate your template with +`ConcretePacketStream` as the type argument. In tests, you will instantiate the +same template with `MockPacketStream`. For example, you may write: + +```cpp +template +void CreateConnection(PacketStream* stream) { ... } + +template +class PacketReader { + public: + void ReadPackets(PacketStream* stream, size_t packet_num); +}; +``` + +Then you can use `CreateConnection()` and +`PacketReader` in production code, and use +`CreateConnection()` and `PacketReader` in +tests. + +```cpp + MockPacketStream mock_stream; + EXPECT_CALL(mock_stream, ...)...; + .. set more expectations on mock_stream ... + PacketReader reader(&mock_stream); + ... exercise reader ... +``` + +### Mocking Free Functions + +It is not possible to directly mock a free function (i.e. a C-style function or +a static method). If you need to, you can rewrite your code to use an interface +(abstract class). + +Instead of calling a free function (say, `OpenFile`) directly, introduce an +interface for it and have a concrete subclass that calls the free function: + +```cpp +class FileInterface { + public: + ... + virtual bool Open(const char* path, const char* mode) = 0; +}; + +class File : public FileInterface { + public: + ... + bool Open(const char* path, const char* mode) override { + return OpenFile(path, mode); + } +}; +``` + +Your code should talk to `FileInterface` to open a file. Now it's easy to mock +out the function. + +This may seem like a lot of hassle, but in practice you often have multiple +related functions that you can put in the same interface, so the per-function +syntactic overhead will be much lower. + +If you are concerned about the performance overhead incurred by virtual +functions, and profiling confirms your concern, you can combine this with the +recipe for [mocking non-virtual methods](#MockingNonVirtualMethods). + +Alternatively, instead of introducing a new interface, you can rewrite your code +to accept a std::function instead of the free function, and then use +[MockFunction](#MockFunction) to mock the std::function. + +### Old-Style `MOCK_METHODn` Macros + +Before the generic `MOCK_METHOD` macro +[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2), +mocks where created using a family of macros collectively called `MOCK_METHODn`. +These macros are still supported, though migration to the new `MOCK_METHOD` is +recommended. + +The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`: + +* The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`, + instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`. +* The number `n` must equal the number of arguments. +* When mocking a const method, one must use `MOCK_CONST_METHODn`. +* When mocking a class template, the macro name must be suffixed with `_T`. +* In order to specify the call type, the macro name must be suffixed with + `_WITH_CALLTYPE`, and the call type is the first macro argument. + +Old macros and their new equivalents: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Simple
OldMOCK_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method
OldMOCK_CONST_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method in a Class Template
OldMOCK_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method in a Class Template
OldMOCK_CONST_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method with Call Type
OldMOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type
OldMOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
Method with Call Type in a Class Template
OldMOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type in a Class Template
OldMOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
+ +### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} + +If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an +"uninteresting call", and the default action (which can be specified using +`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will +also by default cause gMock to print a warning. + +However, sometimes you may want to ignore these uninteresting calls, and +sometimes you may want to treat them as errors. gMock lets you make the decision +on a per-mock-object basis. + +Suppose your test uses a mock class `MockFoo`: + +```cpp +TEST(...) { + MockFoo mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +If a method of `mock_foo` other than `DoThis()` is called, you will get a +warning. However, if you rewrite your test to use `NiceMock` instead, +you can suppress the warning: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +`NiceMock` is a subclass of `MockFoo`, so it can be used wherever +`MockFoo` is accepted. + +It also works if `MockFoo`'s constructor takes some arguments, as +`NiceMock` "inherits" `MockFoo`'s constructors: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +The usage of `StrictMock` is similar, except that it makes all uninteresting +calls failures: + +```cpp +using ::testing::StrictMock; + +TEST(...) { + StrictMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... + + // The test will fail if a method of mock_foo other than DoThis() + // is called. +} +``` + +{: .callout .note} +NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of +*methods* with no expectations); they do not affect *unexpected* calls (calls of +methods with expectations, but they don't match). See +[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected). + +There are some caveats though (sadly they are side effects of C++'s +limitations): + +1. `NiceMock` and `StrictMock` only work for mock methods + defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class. + If a mock method is defined in a **base class** of `MockFoo`, the "nice" or + "strict" modifier may not affect it, depending on the compiler. In + particular, nesting `NiceMock` and `StrictMock` (e.g. + `NiceMock >`) is **not** supported. +2. `NiceMock` and `StrictMock` may not work correctly if the + destructor of `MockFoo` is not virtual. We would like to fix this, but it + requires cleaning up existing tests. + +Finally, you should be **very cautious** about when to use naggy or strict +mocks, as they tend to make tests more brittle and harder to maintain. When you +refactor your code without changing its externally visible behavior, ideally you +shouldn't need to update any tests. If your code interacts with a naggy mock, +however, you may start to get spammed with warnings as the result of your +change. Worse, if your code interacts with a strict mock, your tests may start +to fail and you'll be forced to fix them. Our general recommendation is to use +nice mocks (not yet the default) most of the time, use naggy mocks (the current +default) when developing or debugging tests, and use strict mocks only as the +last resort. + +### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces} + +Sometimes a method has a long list of arguments that is mostly uninteresting. +For example: + +```cpp +class LogSink { + public: + ... + virtual void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const struct tm* tm_time, + const char* message, size_t message_len) = 0; +}; +``` + +This method's argument list is lengthy and hard to work with (the `message` +argument is not even 0-terminated). If we mock it as is, using the mock will be +awkward. If, however, we try to simplify this interface, we'll need to fix all +clients depending on it, which is often infeasible. + +The trick is to redispatch the method in the mock class: + +```cpp +class ScopedMockLog : public LogSink { + public: + ... + void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, const tm* tm_time, + const char* message, size_t message_len) override { + // We are only interested in the log severity, full file name, and + // log message. + Log(severity, full_filename, std::string(message, message_len)); + } + + // Implements the mock method: + // + // void Log(LogSeverity severity, + // const string& file_path, + // const string& message); + MOCK_METHOD(void, Log, + (LogSeverity severity, const string& file_path, + const string& message)); +}; +``` + +By defining a new mock method with a trimmed argument list, we make the mock +class more user-friendly. + +This technique may also be applied to make overloaded methods more amenable to +mocking. For example, when overloads have been used to implement default +arguments: + +```cpp +class MockTurtleFactory : public TurtleFactory { + public: + Turtle* MakeTurtle(int length, int weight) override { ... } + Turtle* MakeTurtle(int length, int weight, int speed) override { ... } + + // the above methods delegate to this one: + MOCK_METHOD(Turtle*, DoMakeTurtle, ()); +}; +``` + +This allows tests that don't care which overload was invoked to avoid specifying +argument matchers: + +```cpp +ON_CALL(factory, DoMakeTurtle) + .WillByDefault(Return(MakeMockTurtle())); +``` + +### Alternative to Mocking Concrete Classes + +Often you may find yourself using classes that don't implement interfaces. In +order to test your code that uses such a class (let's call it `Concrete`), you +may be tempted to make the methods of `Concrete` virtual and then mock it. + +Try not to do that. + +Making a non-virtual function virtual is a big decision. It creates an extension +point where subclasses can tweak your class' behavior. This weakens your control +on the class because now it's harder to maintain the class invariants. You +should make a function virtual only when there is a valid reason for a subclass +to override it. + +Mocking concrete classes directly is problematic as it creates a tight coupling +between the class and the tests - any small change in the class may invalidate +your tests and make test maintenance a pain. + +To avoid such problems, many programmers have been practicing "coding to +interfaces": instead of talking to the `Concrete` class, your code would define +an interface and talk to it. Then you implement that interface as an adaptor on +top of `Concrete`. In tests, you can easily mock that interface to observe how +your code is doing. + +This technique incurs some overhead: + +* You pay the cost of virtual function calls (usually not a problem). +* There is more abstraction for the programmers to learn. + +However, it can also bring significant benefits in addition to better +testability: + +* `Concrete`'s API may not fit your problem domain very well, as you may not + be the only client it tries to serve. By designing your own interface, you + have a chance to tailor it to your need - you may add higher-level + functionalities, rename stuff, etc instead of just trimming the class. This + allows you to write your code (user of the interface) in a more natural way, + which means it will be more readable, more maintainable, and you'll be more + productive. +* If `Concrete`'s implementation ever has to change, you don't have to rewrite + everywhere it is used. Instead, you can absorb the change in your + implementation of the interface, and your other code and tests will be + insulated from this change. + +Some people worry that if everyone is practicing this technique, they will end +up writing lots of redundant code. This concern is totally understandable. +However, there are two reasons why it may not be the case: + +* Different projects may need to use `Concrete` in different ways, so the best + interfaces for them will be different. Therefore, each of them will have its + own domain-specific interface on top of `Concrete`, and they will not be the + same code. +* If enough projects want to use the same interface, they can always share it, + just like they have been sharing `Concrete`. You can check in the interface + and the adaptor somewhere near `Concrete` (perhaps in a `contrib` + sub-directory) and let many projects use it. + +You need to weigh the pros and cons carefully for your particular problem, but +I'd like to assure you that the Java community has been practicing this for a +long time and it's a proven effective technique applicable in a wide variety of +situations. :-) + +### Delegating Calls to a Fake {#DelegatingToFake} + +Some times you have a non-trivial fake implementation of an interface. For +example: + +```cpp +class Foo { + public: + virtual ~Foo() {} + virtual char DoThis(int n) = 0; + virtual void DoThat(const char* s, int* p) = 0; +}; + +class FakeFoo : public Foo { + public: + char DoThis(int n) override { + return (n > 0) ? '+' : + (n < 0) ? '-' : '0'; + } + + void DoThat(const char* s, int* p) override { + *p = strlen(s); + } +}; +``` + +Now you want to mock this interface such that you can set expectations on it. +However, you also want to use `FakeFoo` for the default behavior, as duplicating +it in the mock object is, well, a lot of work. + +When you define the mock class using gMock, you can have it delegate its default +action to a fake class you already have, using this pattern: + +```cpp +class MockFoo : public Foo { + public: + // Normal mock method definitions using gMock. + MOCK_METHOD(char, DoThis, (int n), (override)); + MOCK_METHOD(void, DoThat, (const char* s, int* p), (override)); + + // Delegates the default actions of the methods to a FakeFoo object. + // This must be called *before* the custom ON_CALL() statements. + void DelegateToFake() { + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return fake_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + fake_.DoThat(s, p); + }); + } + + private: + FakeFoo fake_; // Keeps an instance of the fake in the mock. +}; +``` + +With that, you can use `MockFoo` in your tests as usual. Just remember that if +you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the +fake will be called upon to do it.: + +```cpp +using ::testing::_; + +TEST(AbcTest, Xyz) { + MockFoo foo; + + foo.DelegateToFake(); // Enables the fake for delegation. + + // Put your ON_CALL(foo, ...)s here, if any. + + // No action specified, meaning to use the default action. + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(foo, DoThat(_, _)); + + int n = 0; + EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked. + foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. + EXPECT_EQ(n, 2); +} +``` + +**Some tips:** + +* If you want, you can still override the default action by providing your own + `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. +* In `DelegateToFake()`, you only need to delegate the methods whose fake + implementation you intend to use. + +* The general technique discussed here works for overloaded methods, but + you'll need to tell the compiler which version you mean. To disambiguate a + mock function (the one you specify inside the parentheses of `ON_CALL()`), + use [this technique](#SelectOverload); to disambiguate a fake function (the + one you place inside `Invoke()`), use a `static_cast` to specify the + function's type. For instance, if class `Foo` has methods `char DoThis(int + n)` and `bool DoThis(double x) const`, and you want to invoke the latter, + you need to write `Invoke(&fake_, static_cast(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` + (The strange-looking thing inside the angled brackets of `static_cast` is + the type of a function pointer to the second `DoThis()` method.). + +* Having to mix a mock and a fake is often a sign of something gone wrong. + Perhaps you haven't got used to the interaction-based way of testing yet. Or + perhaps your interface is taking on too many roles and should be split up. + Therefore, **don't abuse this**. We would only recommend to do it as an + intermediate step when you are refactoring your code. + +Regarding the tip on mixing a mock and a fake, here's an example on why it may +be a bad sign: Suppose you have a class `System` for low-level system +operations. In particular, it does file and I/O operations. And suppose you want +to test how your code uses `System` to do I/O, and you just want the file +operations to work normally. If you mock out the entire `System` class, you'll +have to provide a fake implementation for the file operation part, which +suggests that `System` is taking on too many roles. + +Instead, you can define a `FileOps` interface and an `IOOps` interface and split +`System`'s functionalities into the two. Then you can mock `IOOps` without +mocking `FileOps`. + +### Delegating Calls to a Real Object + +When using testing doubles (mocks, fakes, stubs, and etc), sometimes their +behaviors will differ from those of the real objects. This difference could be +either intentional (as in simulating an error such that you can test the error +handling code) or unintentional. If your mocks have different behaviors than the +real objects by mistake, you could end up with code that passes the tests but +fails in production. + +You can use the *delegating-to-real* technique to ensure that your mock has the +same behavior as the real object while retaining the ability to validate calls. +This technique is very similar to the [delegating-to-fake](#DelegatingToFake) +technique, the difference being that we use a real object instead of a fake. +Here's an example: + +```cpp +using ::testing::AtLeast; + +class MockFoo : public Foo { + public: + MockFoo() { + // By default, all calls are delegated to the real object. + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return real_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + real_.DoThat(s, p); + }); + ... + } + MOCK_METHOD(char, DoThis, ...); + MOCK_METHOD(void, DoThat, ...); + ... + private: + Foo real_; +}; + +... + MockFoo mock; + EXPECT_CALL(mock, DoThis()) + .Times(3); + EXPECT_CALL(mock, DoThat("Hi")) + .Times(AtLeast(1)); + ... use mock in test ... +``` + +With this, gMock will verify that your code made the right calls (with the right +arguments, in the right order, called the right number of times, etc), and a +real object will answer the calls (so the behavior will be the same as in +production). This gives you the best of both worlds. + +### Delegating Calls to a Parent Class + +Ideally, you should code to interfaces, whose methods are all pure virtual. In +reality, sometimes you do need to mock a virtual method that is not pure (i.e, +it already has an implementation). For example: + +```cpp +class Foo { + public: + virtual ~Foo(); + + virtual void Pure(int n) = 0; + virtual int Concrete(const char* str) { ... } +}; + +class MockFoo : public Foo { + public: + // Mocking a pure method. + MOCK_METHOD(void, Pure, (int n), (override)); + // Mocking a concrete method. Foo::Concrete() is shadowed. + MOCK_METHOD(int, Concrete, (const char* str), (override)); +}; +``` + +Sometimes you may want to call `Foo::Concrete()` instead of +`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or +perhaps your test doesn't need to mock `Concrete()` at all (but it would be +oh-so painful to have to define a new mock class whenever you don't need to mock +one of its methods). + +You can call `Foo::Concrete()` inside an action by: + +```cpp +... + EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +or tell the mock object that you don't want to mock `Concrete()`: + +```cpp +... + ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +(Why don't we just write `{ return foo.Concrete(str); }`? If you do that, +`MockFoo::Concrete()` will be called (and cause an infinite recursion) since +`Foo::Concrete()` is virtual. That's just how C++ works.) + +## Using Matchers + +### Matching Argument Values Exactly + +You can specify exactly which arguments a mock method is expecting: + +```cpp +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(5)) + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", bar)); +``` + +### Using Simple Matchers + +You can use matchers to match arguments that have a certain property: + +```cpp +using ::testing::NotNull; +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", NotNull())); + // The second argument must not be NULL. +``` + +A frequently used matcher is `_`, which matches anything: + +```cpp + EXPECT_CALL(foo, DoThat(_, NotNull())); +``` + +### Combining Matchers {#CombiningMatchers} + +You can build complex matchers from existing ones using `AllOf()`, +`AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`: + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::HasSubstr; +using ::testing::Ne; +using ::testing::Not; +... + // The argument must be > 5 and != 10. + EXPECT_CALL(foo, DoThis(AllOf(Gt(5), + Ne(10)))); + + // The first argument must not contain sub-string "blah". + EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), + NULL)); +``` + +Matchers are function objects, and parametrized matchers can be composed just +like any other function. However because their types can be long and rarely +provide meaningful information, it can be easier to express them with C++14 +generic lambdas to avoid specifying types. For example, + +```cpp +using ::testing::Contains; +using ::testing::Property; + +inline constexpr auto HasFoo = [](const auto& f) { + return Property("foo", &MyClass::foo, Contains(f)); +}; +... + EXPECT_THAT(x, HasFoo("blah")); +``` + +### Casting Matchers {#SafeMatcherCast} + +gMock matchers are statically typed, meaning that the compiler can catch your +mistake if you use a matcher of the wrong type (for example, if you use `Eq(5)` +to match a `string` argument). Good for you! + +Sometimes, however, you know what you're doing and want the compiler to give you +some slack. One example is that you have a matcher for `long` and the argument +you want to match is `int`. While the two types aren't exactly the same, there +is nothing really wrong with using a `Matcher` to match an `int` - after +all, we can first convert the `int` argument to a `long` losslessly before +giving it to the matcher. + +To support this need, gMock gives you the `SafeMatcherCast(m)` function. It +casts a matcher `m` to type `Matcher`. To ensure safety, gMock checks that +(let `U` be the type `m` accepts : + +1. Type `T` can be *implicitly* cast to type `U`; +2. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and + floating-point numbers), the conversion from `T` to `U` is not lossy (in + other words, any value representable by `T` can also be represented by `U`); + and +3. When `U` is a non-const reference, `T` must also be a reference (as the + underlying matcher may be interested in the address of the `U` value). + +The code won't compile if any of these conditions isn't met. + +Here's one example: + +```cpp +using ::testing::SafeMatcherCast; + +// A base class and a child class. +class Base { ... }; +class Derived : public Base { ... }; + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, DoThis, (Derived* derived), (override)); +}; + +... + MockFoo foo; + // m is a Matcher we got from somewhere. + EXPECT_CALL(foo, DoThis(SafeMatcherCast(m))); +``` + +If you find `SafeMatcherCast(m)` too limiting, you can use a similar function +`MatcherCast(m)`. The difference is that `MatcherCast` works as long as you +can `static_cast` type `T` to type `U`. + +`MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't +always safe as it could throw away information, for example), so be careful not +to misuse/abuse it. + +### Selecting Between Overloaded Functions {#SelectOverload} + +If you expect an overloaded function to be called, the compiler may need some +help on which overloaded version it is. + +To disambiguate functions overloaded on the const-ness of this object, use the +`Const()` argument wrapper. + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + ... + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; + +... + MockFoo foo; + Bar bar1, bar2; + EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). + .WillOnce(ReturnRef(bar1)); + EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). + .WillOnce(ReturnRef(bar2)); +``` + +(`Const()` is defined by gMock and returns a `const` reference to its argument.) + +To disambiguate overloaded functions with the same number of arguments but +different argument types, you may need to specify the exact type of a matcher, +either by wrapping your matcher in `Matcher()`, or using a matcher whose +type is fixed (`TypedEq`, `An()`, etc): + +```cpp +using ::testing::An; +using ::testing::Matcher; +using ::testing::TypedEq; + +class MockPrinter : public Printer { + public: + MOCK_METHOD(void, Print, (int n), (override)); + MOCK_METHOD(void, Print, (char c), (override)); +}; + +TEST(PrinterTest, Print) { + MockPrinter printer; + + EXPECT_CALL(printer, Print(An())); // void Print(int); + EXPECT_CALL(printer, Print(Matcher(Lt(5)))); // void Print(int); + EXPECT_CALL(printer, Print(TypedEq('a'))); // void Print(char); + + printer.Print(3); + printer.Print(6); + printer.Print('a'); +} +``` + +### Performing Different Actions Based on the Arguments + +When a mock method is called, the *last* matching expectation that's still +active will be selected (think "newer overrides older"). So, you can make a +method do different things depending on its argument values like this: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... + // The default case. + EXPECT_CALL(foo, DoThis(_)) + .WillRepeatedly(Return('b')); + // The more specific case. + EXPECT_CALL(foo, DoThis(Lt(5))) + .WillRepeatedly(Return('a')); +``` + +Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will be +returned; otherwise `'b'` will be returned. + +### Matching Multiple Arguments as a Whole + +Sometimes it's not enough to match the arguments individually. For example, we +may want to say that the first argument must be less than the second argument. +The `With()` clause allows us to match all arguments of a mock function as a +whole. For example, + +```cpp +using ::testing::_; +using ::testing::Ne; +using ::testing::Lt; +... + EXPECT_CALL(foo, InRange(Ne(0), _)) + .With(Lt()); +``` + +says that the first argument of `InRange()` must not be 0, and must be less than +the second argument. + +The expression inside `With()` must be a matcher of type `Matcher>`, where `A1`, ..., `An` are the types of the function arguments. + +You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms +are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. + +You can use `Args(m)` to match the `n` selected arguments (as a +tuple) against `m`. For example, + +```cpp +using ::testing::_; +using ::testing::AllOf; +using ::testing::Args; +using ::testing::Lt; +... + EXPECT_CALL(foo, Blah) + .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); +``` + +says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y < +z`. Note that in this example, it wasn't necessary to specify the positional +matchers. + +As a convenience and example, gMock provides some matchers for 2-tuples, +including the `Lt()` matcher above. See +[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the +complete list. + +Note that if you want to pass the arguments to a predicate of your own (e.g. +`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to +take a `std::tuple` as its argument; gMock will pass the `n` selected arguments +as *one* single tuple to the predicate. + +### Using Matchers as Predicates + +Have you noticed that a matcher is just a fancy predicate that also knows how to +describe itself? Many existing algorithms take predicates as arguments (e.g. +those defined in STL's `` header), and it would be a shame if gMock +matchers were not allowed to participate. + +Luckily, you can use a matcher where a unary predicate functor is expected by +wrapping it inside the `Matches()` function. For example, + +```cpp +#include +#include + +using ::testing::Matches; +using ::testing::Ge; + +vector v; +... +// How many elements in v are >= 10? +const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); +``` + +Since you can build complex matchers from simpler ones easily using gMock, this +gives you a way to conveniently construct composite predicates (doing the same +using STL's `` header is just painful). For example, here's a +predicate that's satisfied by any number that is >= 0, <= 100, and != 50: + +```cpp +using ::testing::AllOf; +using ::testing::Ge; +using ::testing::Le; +using ::testing::Matches; +using ::testing::Ne; +... +Matches(AllOf(Ge(0), Le(100), Ne(50))) +``` + +### Using Matchers in googletest Assertions + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### Using Predicates as Matchers + +gMock provides a set of built-in matchers for matching arguments with expected +values—see the [Matchers Reference](reference/matchers.md) for more information. +In case you find the built-in set lacking, you can use an arbitrary unary +predicate function or functor as a matcher - as long as the predicate accepts a +value of the type you want. You do this by wrapping the predicate inside the +`Truly()` function, for example: + +```cpp +using ::testing::Truly; + +int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } +... + // Bar() must be called with an even number. + EXPECT_CALL(foo, Bar(Truly(IsEven))); +``` + +Note that the predicate function / functor doesn't have to return `bool`. It +works as long as the return value can be used as the condition in the statement +`if (condition) ...`. + +### Matching Arguments that Are Not Copyable + +When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of +`bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with +the saved copy of `bar`. This way, you don't need to worry about `bar` being +modified or destroyed after the `EXPECT_CALL()` is executed. The same is true +when you use matchers like `Eq(bar)`, `Le(bar)`, and so on. + +But what if `bar` cannot be copied (i.e. has no copy constructor)? You could +define your own matcher function or callback and use it with `Truly()`, as the +previous couple of recipes have shown. Or, you may be able to get away from it +if you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is +executed. Just tell gMock that it should save a reference to `bar`, instead of a +copy of it. Here's how: + +```cpp +using ::testing::Eq; +using ::testing::Lt; +... + // Expects that Foo()'s argument == bar. + EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar)))); + + // Expects that Foo()'s argument < bar. + EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar)))); +``` + +Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the +result is undefined. + +### Validating a Member of an Object + +Often a mock function takes a reference to object as an argument. When matching +the argument, you may not want to compare the entire object against a fixed +object, as that may be over-specification. Instead, you may need to validate a +certain member variable or the result of a certain getter method of the object. +You can do this with `Field()` and `Property()`. More specifically, + +```cpp +Field(&Foo::bar, m) +``` + +is a matcher that matches a `Foo` object whose `bar` member variable satisfies +matcher `m`. + +```cpp +Property(&Foo::baz, m) +``` + +is a matcher that matches a `Foo` object whose `baz()` method returns a value +that satisfies matcher `m`. + +For example: + +| Expression | Description | +| :--------------------------- | :--------------------------------------- | +| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | + +Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument +and be declared as `const`. Don't use `Property()` against member functions that +you do not own, because taking addresses of functions is fragile and generally +not part of the contract of the function. + +`Field()` and `Property()` can also match plain pointers to objects. For +instance, + +```cpp +using ::testing::Field; +using ::testing::Ge; +... +Field(&Foo::number, Ge(3)) +``` + +matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match +will always fail regardless of the inner matcher. + +What if you want to validate more than one members at the same time? Remember +that there are [`AllOf()` and `AllOfArray()`](#CombiningMatchers). + +Finally `Field()` and `Property()` provide overloads that take the field or +property names as the first argument to include it in the error message. This +can be useful when creating combined matchers. + +```cpp +using ::testing::AllOf; +using ::testing::Field; +using ::testing::Matcher; +using ::testing::SafeMatcherCast; + +Matcher IsFoo(const Foo& foo) { + return AllOf(Field("some_field", &Foo::some_field, foo.some_field), + Field("other_field", &Foo::other_field, foo.other_field), + Field("last_field", &Foo::last_field, foo.last_field)); +} +``` + +### Validating the Value Pointed to by a Pointer Argument + +C++ functions often take pointers as arguments. You can use matchers like +`IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but +what if you want to make sure the value *pointed to* by the pointer, instead of +the pointer itself, has a certain property? Well, you can use the `Pointee(m)` +matcher. + +`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer +points to. For example: + +```cpp +using ::testing::Ge; +using ::testing::Pointee; +... + EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); +``` + +expects `foo.Bar()` to be called with a pointer that points to a value greater +than or equal to 3. + +One nice thing about `Pointee()` is that it treats a `NULL` pointer as a match +failure, so you can write `Pointee(m)` instead of + +```cpp +using ::testing::AllOf; +using ::testing::NotNull; +using ::testing::Pointee; +... + AllOf(NotNull(), Pointee(m)) +``` + +without worrying that a `NULL` pointer will crash your test. + +Also, did we tell you that `Pointee()` works with both raw pointers **and** +smart pointers (`std::unique_ptr`, `std::shared_ptr`, etc)? + +What if you have a pointer to pointer? You guessed it - you can use nested +`Pointee()` to probe deeper inside the value. For example, +`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points +to a number less than 3 (what a mouthful...). + +### Defining a Custom Matcher Class {#CustomMatcherClass} + +Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers), +which are terse and flexible, and produce good error messages. However, these +macros are not very explicit about the interfaces they create and are not always +suitable, especially for matchers that will be widely reused. + +For more advanced cases, you may need to define your own matcher class. A custom +matcher allows you to test a specific invariant property of that object. Let's +take a look at how to do so. + +Imagine you have a mock function that takes an object of type `Foo`, which has +an `int bar()` method and an `int baz()` method. You want to constrain that the +argument's `bar()` value plus its `baz()` value is a given number. (This is an +invariant.) Here's how we can write and use a matcher class to do so: + +```cpp +class BarPlusBazEqMatcher { + public: + using is_gtest_matcher = void; + + explicit BarPlusBazEqMatcher(int expected_sum) + : expected_sum_(expected_sum) {} + + bool MatchAndExplain(const Foo& foo, + std::ostream* /* listener */) const { + return (foo.bar() + foo.baz()) == expected_sum_; + } + + void DescribeTo(std::ostream* os) const { + *os << "bar() + baz() equals " << expected_sum_; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "bar() + baz() does not equal " << expected_sum_; + } + private: + const int expected_sum_; +}; + +::testing::Matcher BarPlusBazEq(int expected_sum) { + return BarPlusBazEqMatcher(expected_sum); +} + +... + Foo foo; + EXPECT_THAT(foo, BarPlusBazEq(5))...; +``` + +### Matching Containers + +Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock +function and you may want to validate it. Since most STL containers support the +`==` operator, you can write `Eq(expected_container)` or simply +`expected_container` to match a container exactly. + +Sometimes, though, you may want to be more flexible (for example, the first +element must be an exact match, but the second element can be any positive +number, and so on). Also, containers used in tests often have a small number of +elements, and having to define the expected container out-of-line is a bit of a +hassle. + +You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such +cases: + +```cpp +using ::testing::_; +using ::testing::ElementsAre; +using ::testing::Gt; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); +``` + +The above matcher says that the container must have 4 elements, which must be 1, +greater than 0, anything, and 5 respectively. + +If you instead write: + +```cpp +using ::testing::_; +using ::testing::Gt; +using ::testing::UnorderedElementsAre; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); +``` + +It means that the container must have 4 elements, which (under some permutation) +must be 1, greater than 0, anything, and 5 respectively. + +As an alternative you can place the arguments in a C-style array and use +`ElementsAreArray()` or `UnorderedElementsAreArray()` instead: + +```cpp +using ::testing::ElementsAreArray; +... + // ElementsAreArray accepts an array of element values. + const int expected_vector1[] = {1, 5, 2, 4, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); + + // Or, an array of element matchers. + Matcher expected_vector2[] = {1, Gt(2), _, 3, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); +``` + +In case the array needs to be dynamically created (and therefore the array size +cannot be inferred by the compiler), you can give `ElementsAreArray()` an +additional argument to specify the array size: + +```cpp +using ::testing::ElementsAreArray; +... + int* const expected_vector3 = new int[count]; + ... fill expected_vector3 with values ... + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); +``` + +Use `Pair` when comparing maps or other associative containers. + +{% raw %} + +```cpp +using ::testing::UnorderedElementsAre; +using ::testing::Pair; +... + absl::flat_hash_map m = {{"a", 1}, {"b", 2}, {"c", 3}}; + EXPECT_THAT(m, UnorderedElementsAre( + Pair("a", 1), Pair("b", 2), Pair("c", 3))); +``` + +{% endraw %} + +**Tips:** + +* `ElementsAre*()` can be used to match *any* container that implements the + STL iterator pattern (i.e. it has a `const_iterator` type and supports + `begin()/end()`), not just the ones defined in STL. It will even work with + container types yet to be written - as long as they follows the above + pattern. +* You can use nested `ElementsAre*()` to match nested (multi-dimensional) + containers. +* If the container is passed by pointer instead of by reference, just write + `Pointee(ElementsAre*(...))`. +* The order of elements *matters* for `ElementsAre*()`. If you are using it + with containers whose element order are undefined (such as a + `std::unordered_map`) you should use `UnorderedElementsAre`. + +### Sharing Matchers + +Under the hood, a gMock matcher object consists of a pointer to a ref-counted +implementation object. Copying matchers is allowed and very efficient, as only +the pointer is copied. When the last matcher that references the implementation +object dies, the implementation object will be deleted. + +Therefore, if you have some complex matcher that you want to use again and +again, there is no need to build it every time. Just assign it to a matcher +variable and use that variable repeatedly! For example, + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Le; +using ::testing::Matcher; +... + Matcher in_range = AllOf(Gt(5), Le(10)); + ... use in_range as a matcher in multiple EXPECT_CALLs ... +``` + +### Matchers must have no side-effects {#PureMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be *purely functional*: they cannot have +any side effects, and the match result must not depend on anything other than +the matcher's parameters and the value being matched. + +This requirement must be satisfied no matter how a matcher is defined (e.g., if +it is one of the standard matchers, or a custom matcher). In particular, a +matcher can never call a mock function, as that will affect the state of the +mock object and gMock. + +## Setting Expectations + +### Knowing When to Expect {#UseOnCall} + +**`ON_CALL`** is likely the *single most under-utilized construct* in gMock. + +There are basically two constructs for defining the behavior of a mock object: +`ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when +a mock method is called, but doesn't imply any expectation on the method +being called. `EXPECT_CALL` not only defines the behavior, but also sets an +expectation that the method will be called with the given arguments, for the +given number of times (and *in the given order* when you specify the order +too). + +Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every +`EXPECT_CALL` adds a constraint on the behavior of the code under test. Having +more constraints than necessary is *baaad* - even worse than not having enough +constraints. + +This may be counter-intuitive. How could tests that verify more be worse than +tests that verify less? Isn't verification the whole point of tests? + +The answer lies in *what* a test should verify. **A good test verifies the +contract of the code.** If a test over-specifies, it doesn't leave enough +freedom to the implementation. As a result, changing the implementation without +breaking the contract (e.g. refactoring and optimization), which should be +perfectly fine to do, can break such tests. Then you have to spend time fixing +them, only to see them broken again the next time the implementation is changed. + +Keep in mind that one doesn't have to verify more than one property in one test. +In fact, **it's a good style to verify only one thing in one test.** If you do +that, a bug will likely break only one or two tests instead of dozens (which +case would you rather debug?). If you are also in the habit of giving tests +descriptive names that tell what they verify, you can often easily guess what's +wrong just from the test log itself. + +So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend +to verify that the call is made. For example, you may have a bunch of `ON_CALL`s +in your test fixture to set the common mock behavior shared by all tests in the +same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s +to verify different aspects of the code's behavior. Compared with the style +where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more +resilient to implementational changes (and thus less likely to require +maintenance) and makes the intent of the tests more obvious (so they are easier +to maintain when you do need to maintain them). + +If you are bothered by the "Uninteresting mock function call" message printed +when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` +instead to suppress all such messages for the mock object, or suppress the +message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO +NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test +that's a pain to maintain. + +### Ignoring Uninteresting Calls + +If you are not interested in how a mock method is called, just don't say +anything about it. In this case, if the method is ever called, gMock will +perform its default action to allow the test program to continue. If you are not +happy with the default action taken by gMock, you can override it using +`DefaultValue::Set()` (described [here](#DefaultValue)) or `ON_CALL()`. + +Please note that once you expressed interest in a particular mock method (via +`EXPECT_CALL()`), all invocations to it must match some expectation. If this +function is called but the arguments don't match any `EXPECT_CALL()` statement, +it will be an error. + +### Disallowing Unexpected Calls + +If a mock method shouldn't be called at all, explicitly say so: + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +If some calls to the method are allowed, but the rest are not, just list all the +expected calls: + +```cpp +using ::testing::AnyNumber; +using ::testing::Gt; +... + EXPECT_CALL(foo, Bar(5)); + EXPECT_CALL(foo, Bar(Gt(10))) + .Times(AnyNumber()); +``` + +A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements +will be an error. + +### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected} + +*Uninteresting* calls and *unexpected* calls are different concepts in gMock. +*Very* different. + +A call `x.Y(...)` is **uninteresting** if there's *not even a single* +`EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the +`x.Y()` method at all, as evident in that the test doesn't care to say anything +about it. + +A call `x.Y(...)` is **unexpected** if there are *some* `EXPECT_CALL(x, +Y(...))`s set, but none of them matches the call. Put another way, the test is +interested in the `x.Y()` method (therefore it explicitly sets some +`EXPECT_CALL` to verify how it's called); however, the verification fails as the +test doesn't expect this particular call to happen. + +**An unexpected call is always an error,** as the code under test doesn't behave +the way the test expects it to behave. + +**By default, an uninteresting call is not an error,** as it violates no +constraint specified by the test. (gMock's philosophy is that saying nothing +means there is no constraint.) However, it leads to a warning, as it *might* +indicate a problem (e.g. the test author might have forgotten to specify a +constraint). + +In gMock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or +"strict". How does this affect uninteresting calls and unexpected calls? + +A **nice mock** suppresses uninteresting call *warnings*. It is less chatty than +the default mock, but otherwise is the same. If a test fails with a default +mock, it will also fail using a nice mock instead. And vice versa. Don't expect +making a mock nice to change the test's result. + +A **strict mock** turns uninteresting call warnings into errors. So making a +mock strict may change the test's result. + +Let's look at an example: + +```cpp +TEST(...) { + NiceMock mock_registry; + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); + + // Use mock_registry in code under test. + ... &mock_registry ... +} +``` + +The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have +`"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it +will be an unexpected call, and thus an error. *Having a nice mock doesn't +change the severity of an unexpected call.* + +So how do we tell gMock that `GetDomainOwner()` can be called with some other +arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: + +```cpp + EXPECT_CALL(mock_registry, GetDomainOwner(_)) + .Times(AnyNumber()); // catches all other calls to this method. + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); +``` + +Remember that `_` is the wildcard matcher that matches anything. With this, if +`GetDomainOwner("google.com")` is called, it will do what the second +`EXPECT_CALL` says; if it is called with a different argument, it will do what +the first `EXPECT_CALL` says. + +Note that the order of the two `EXPECT_CALL`s is important, as a newer +`EXPECT_CALL` takes precedence over an older one. + +For more on uninteresting calls, nice mocks, and strict mocks, read +["The Nice, the Strict, and the Naggy"](#NiceStrictNaggy). + +### Ignoring Uninteresting Arguments {#ParameterlessExpectations} + +If your test doesn't care about the parameters (it only cares about the number +or order of calls), you can often simply omit the parameter list: + +```cpp + // Expect foo.Bar( ... ) twice with any arguments. + EXPECT_CALL(foo, Bar).Times(2); + + // Delegate to the given method whenever the factory is invoked. + ON_CALL(foo_factory, MakeFoo) + .WillByDefault(&BuildFooForTest); +``` + +This functionality is only available when a method is not overloaded; to prevent +unexpected behavior it is a compilation error to try to set an expectation on a +method where the specific overload is ambiguous. You can work around this by +supplying a [simpler mock interface](#SimplerInterfaces) than the mocked class +provides. + +This pattern is also useful when the arguments are interesting, but match logic +is substantially complex. You can leave the argument list unspecified and use +SaveArg actions to [save the values for later verification](#SaveArgVerify). If +you do that, you can easily differentiate calling the method the wrong number of +times from calling it with the wrong arguments. + +### Expecting Ordered Calls {#OrderedCalls} + +Although an `EXPECT_CALL()` statement defined later takes precedence when gMock +tries to match a function call with an expectation, by default calls don't have +to happen in the order `EXPECT_CALL()` statements are written. For example, if +the arguments match the matchers in the second `EXPECT_CALL()`, but not those in +the first and third, then the second expectation will be used. + +If you would rather have all calls occur in the order of the expectations, put +the `EXPECT_CALL()` statements in a block where you define a variable of type +`InSequence`: + +```cpp +using ::testing::_; +using ::testing::InSequence; + + { + InSequence s; + + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(bar, DoThat(_)) + .Times(2); + EXPECT_CALL(foo, DoThis(6)); + } +``` + +In this example, we expect a call to `foo.DoThis(5)`, followed by two calls to +`bar.DoThat()` where the argument can be anything, which are in turn followed by +a call to `foo.DoThis(6)`. If a call occurred out-of-order, gMock will report an +error. + +### Expecting Partially Ordered Calls {#PartialOrder} + +Sometimes requiring everything to occur in a predetermined order can lead to +brittle tests. For example, we may care about `A` occurring before both `B` and +`C`, but aren't interested in the relative order of `B` and `C`. In this case, +the test should reflect our real intent, instead of being overly constraining. + +gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the +calls. One way to express the DAG is to use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`. + +Another way is via the `InSequence()` clause (not the same as the `InSequence` +class), which we borrowed from jMock 2. It's less flexible than `After()`, but +more convenient when you have long chains of sequential calls, as it doesn't +require you to come up with different names for the expectations in the chains. +Here's how it works: + +If we view `EXPECT_CALL()` statements as nodes in a graph, and add an edge from +node A to node B wherever A must occur before B, we can get a DAG. We use the +term "sequence" to mean a directed path in this DAG. Now, if we decompose the +DAG into sequences, we just need to know which sequences each `EXPECT_CALL()` +belongs to in order to be able to reconstruct the original DAG. + +So, to specify the partial order on the expectations we need to do two things: +first to define some `Sequence` objects, and then for each `EXPECT_CALL()` say +which `Sequence` objects it is part of. + +Expectations in the same sequence must occur in the order they are written. For +example, + +```cpp +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(foo, A()) + .InSequence(s1, s2); + EXPECT_CALL(bar, B()) + .InSequence(s1); + EXPECT_CALL(bar, C()) + .InSequence(s2); + EXPECT_CALL(foo, D()) + .InSequence(s2); +``` + +specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): + +```text + +---> B + | + A ---| + | + +---> C ---> D +``` + +This means that A must occur before B and C, and C must occur before D. There's +no restriction about the order other than these. + +### Controlling When an Expectation Retires + +When a mock method is called, gMock only considers expectations that are still +active. An expectation is active when created, and becomes inactive (aka +*retires*) when a call that has to occur later has occurred. For example, in + +```cpp +using ::testing::_; +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 + .Times(AnyNumber()) + .InSequence(s1, s2); + EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 + .InSequence(s1); + EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 + .InSequence(s2); +``` + +as soon as either #2 or #3 is matched, #1 will retire. If a warning `"File too +large."` is logged after this, it will be an error. + +Note that an expectation doesn't retire automatically when it's saturated. For +example, + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 +``` + +says that there will be exactly one warning with the message `"File too +large."`. If the second warning contains this message too, #2 will match again +and result in an upper-bound-violated error. + +If this is not what you want, you can ask an expectation to retire as soon as it +becomes saturated: + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 + .RetiresOnSaturation(); +``` + +Here #2 can be used only once, so if you have two warnings with the message +`"File too large."`, the first will match #2 and the second will match #1 - +there will be no error. + +## Using Actions + +### Returning References from Mock Methods + +If a mock function's return type is a reference, you need to use `ReturnRef()` +instead of `Return()` to return a result: + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar&, GetBar, (), (override)); +}; +... + MockFoo foo; + Bar bar; + EXPECT_CALL(foo, GetBar()) + .WillOnce(ReturnRef(bar)); +... +``` + +### Returning Live Values from Mock Methods + +The `Return(x)` action saves a copy of `x` when the action is created, and +always returns the same value whenever it's executed. Sometimes you may want to +instead return the *live* value of `x` (i.e. its value at the time when the +action is *executed*.). Use either `ReturnRef()` or `ReturnPointee()` for this +purpose. + +If the mock function's return type is a reference, you can do it using +`ReturnRef(x)`, as shown in the previous recipe ("Returning References from Mock +Methods"). However, gMock doesn't let you use `ReturnRef()` in a mock function +whose return type is not a reference, as doing that usually indicates a user +error. So, what shall you do? + +Though you may be tempted, DO NOT use `std::ref()`: + +```cpp +using ::testing::Return; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetValue, (), (override)); +}; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(Return(std::ref(x))); // Wrong! + x = 42; + EXPECT_EQ(foo.GetValue(), 42); +``` + +Unfortunately, it doesn't work here. The above code will fail with error: + +```text +Value of: foo.GetValue() + Actual: 0 +Expected: 42 +``` + +The reason is that `Return(*value*)` converts `value` to the actual return type +of the mock function at the time when the action is *created*, not when it is +*executed*. (This behavior was chosen for the action to be safe when `value` is +a proxy object that references some temporary objects.) As a result, +`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when +the expectation is set, and `Return(std::ref(x))` will always return 0. + +`ReturnPointee(pointer)` was provided to solve this problem specifically. It +returns the value pointed to by `pointer` at the time the action is *executed*: + +```cpp +using ::testing::ReturnPointee; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(ReturnPointee(&x)); // Note the & here. + x = 42; + EXPECT_EQ(foo.GetValue(), 42); // This will succeed now. +``` + +### Combining Actions + +Want to do more than one thing when a function is called? That's fine. `DoAll()` +allows you to do a sequence of actions every time. Only the return value of the +last action in the sequence will be used. + +```cpp +using ::testing::_; +using ::testing::DoAll; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, Bar, (int n), (override)); +}; +... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(DoAll(action_1, + action_2, + ... + action_n)); +``` + +The return value of the last action **must** match the return type of the mocked +method. In the example above, `action_n` could be `Return(true)`, or a lambda +that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the +signature of `DoAll` would not match the signature expected by `WillOnce`, which +is the signature of the mocked method, and it wouldn't compile. + +### Verifying Complex Arguments {#SaveArgVerify} + +If you want to verify that a method is called with a particular argument but the +match criteria is complex, it can be difficult to distinguish between +cardinality failures (calling the method the wrong number of times) and argument +match failures. Similarly, if you are matching multiple parameters, it may not +be easy to distinguishing which argument failed to match. For example: + +```cpp + // Not ideal: this could fail because of a problem with arg1 or arg2, or maybe + // just the method wasn't called. + EXPECT_CALL(foo, SendValues(_, ElementsAre(1, 4, 4, 7), EqualsProto( ... ))); +``` + +You can instead save the arguments and test them individually: + +```cpp + EXPECT_CALL(foo, SendValues) + .WillOnce(DoAll(SaveArg<1>(&actual_array), SaveArg<2>(&actual_proto))); + ... run the test + EXPECT_THAT(actual_array, ElementsAre(1, 4, 4, 7)); + EXPECT_THAT(actual_proto, EqualsProto( ... )); +``` + +### Mocking Side Effects {#MockingSideEffects} + +Sometimes a method exhibits its effect not via returning a value but via side +effects. For example, it may change some global state or modify an output +argument. To mock side effects, in general you can define your own action by +implementing `::testing::ActionInterface`. + +If all you need to do is to change an output argument, the built-in +`SetArgPointee()` action is convenient: + +```cpp +using ::testing::_; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + MOCK_METHOD(void, Mutate, (bool mutate, int* value), (override)); + ... +} +... + MockMutator mutator; + EXPECT_CALL(mutator, Mutate(true, _)) + .WillOnce(SetArgPointee<1>(5)); +``` + +In this example, when `mutator.Mutate()` is called, we will assign 5 to the +`int` variable pointed to by argument #1 (0-based). + +`SetArgPointee()` conveniently makes an internal copy of the value you pass to +it, removing the need to keep the value in scope and alive. The implication +however is that the value must have a copy constructor and assignment operator. + +If the mock method also needs to return a value as well, you can chain +`SetArgPointee()` with `Return()` using `DoAll()`, remembering to put the +`Return()` statement last: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + ... + MOCK_METHOD(bool, MutateInt, (int* value), (override)); +} +... + MockMutator mutator; + EXPECT_CALL(mutator, MutateInt(_)) + .WillOnce(DoAll(SetArgPointee<0>(5), + Return(true))); +``` + +Note, however, that if you use the `ReturnOKWith()` method, it will override the +values provided by `SetArgPointee()` in the response parameters of your function +call. + +If the output argument is an array, use the `SetArrayArgument(first, last)` +action instead. It copies the elements in source range `[first, last)` to the +array pointed to by the `N`-th (0-based) argument: + +```cpp +using ::testing::NotNull; +using ::testing::SetArrayArgument; + +class MockArrayMutator : public ArrayMutator { + public: + MOCK_METHOD(void, Mutate, (int* values, int num_values), (override)); + ... +} +... + MockArrayMutator mutator; + int values[5] = {1, 2, 3, 4, 5}; + EXPECT_CALL(mutator, Mutate(NotNull(), 5)) + .WillOnce(SetArrayArgument<0>(values, values + 5)); +``` + +This also works when the argument is an output iterator: + +```cpp +using ::testing::_; +using ::testing::SetArrayArgument; + +class MockRolodex : public Rolodex { + public: + MOCK_METHOD(void, GetNames, (std::back_insert_iterator>), + (override)); + ... +} +... + MockRolodex rolodex; + vector names = {"George", "John", "Thomas"}; + EXPECT_CALL(rolodex, GetNames(_)) + .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); +``` + +### Changing a Mock Object's Behavior Based on the State + +If you expect a call to change the behavior of a mock object, you can use +`::testing::InSequence` to specify different behaviors before and after the +call: + +```cpp +using ::testing::InSequence; +using ::testing::Return; + +... + { + InSequence seq; + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(my_mock, Flush()); + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(false)); + } + my_mock.FlushIfDirty(); +``` + +This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called +and return `false` afterwards. + +If the behavior change is more complex, you can store the effects in a variable +and make a mock method get its return value from that variable: + +```cpp +using ::testing::_; +using ::testing::SaveArg; +using ::testing::Return; + +ACTION_P(ReturnPointee, p) { return *p; } +... + int previous_value = 0; + EXPECT_CALL(my_mock, GetPrevValue) + .WillRepeatedly(ReturnPointee(&previous_value)); + EXPECT_CALL(my_mock, UpdateValue) + .WillRepeatedly(SaveArg<0>(&previous_value)); + my_mock.DoSomethingToUpdateValue(); +``` + +Here `my_mock.GetPrevValue()` will always return the argument of the last +`UpdateValue()` call. + +### Setting the Default Value for a Return Type {#DefaultValue} + +If a mock method's return type is a built-in C++ type or pointer, by default it +will return 0 when invoked. Also, in C++ 11 and above, a mock method whose +return type has a default constructor will return a default-constructed value by +default. You only need to specify an action if this default value doesn't work +for you. + +Sometimes, you may want to change this default value, or you may want to specify +a default value for types gMock doesn't know about. You can do this using the +`::testing::DefaultValue` class template: + +```cpp +using ::testing::DefaultValue; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar, CalculateBar, (), (override)); +}; + + +... + Bar default_bar; + // Sets the default return value for type Bar. + DefaultValue::Set(default_bar); + + MockFoo foo; + + // We don't need to specify an action here, as the default + // return value works for us. + EXPECT_CALL(foo, CalculateBar()); + + foo.CalculateBar(); // This should return default_bar. + + // Unsets the default return value. + DefaultValue::Clear(); +``` + +Please note that changing the default value for a type can make your tests hard +to understand. We recommend you to use this feature judiciously. For example, +you may want to make sure the `Set()` and `Clear()` calls are right next to the +code that uses your mock. + +### Setting the Default Actions for a Mock Method + +You've learned how to change the default value of a given type. However, this +may be too coarse for your purpose: perhaps you have two mock methods with the +same return type and you want them to have different behaviors. The `ON_CALL()` +macro allows you to customize your mock's behavior at the method level: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +using ::testing::Gt; +using ::testing::Return; +... + ON_CALL(foo, Sign(_)) + .WillByDefault(Return(-1)); + ON_CALL(foo, Sign(0)) + .WillByDefault(Return(0)); + ON_CALL(foo, Sign(Gt(0))) + .WillByDefault(Return(1)); + + EXPECT_CALL(foo, Sign(_)) + .Times(AnyNumber()); + + foo.Sign(5); // This should return 1. + foo.Sign(-9); // This should return -1. + foo.Sign(0); // This should return 0. +``` + +As you may have guessed, when there are more than one `ON_CALL()` statements, +the newer ones in the order take precedence over the older ones. In other words, +the **last** one that matches the function arguments will be used. This matching +order allows you to set up the common behavior in a mock object's constructor or +the test fixture's set-up phase and specialize the mock's behavior later. + +Note that both `ON_CALL` and `EXPECT_CALL` have the same "later statements take +precedence" rule, but they don't interact. That is, `EXPECT_CALL`s have their +own precedence order distinct from the `ON_CALL` precedence order. + +### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} + +If the built-in actions don't suit you, you can use an existing callable +(function, `std::function`, method, functor, lambda) as an action. + +```cpp +using ::testing::_; using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, Sum, (int x, int y), (override)); + MOCK_METHOD(bool, ComplexJob, (int x), (override)); +}; + +int CalculateSum(int x, int y) { return x + y; } +int Sum3(int x, int y, int z) { return x + y + z; } + +class Helper { + public: + bool ComplexJob(int x); +}; + +... + MockFoo foo; + Helper helper; + EXPECT_CALL(foo, Sum(_, _)) + .WillOnce(&CalculateSum) + .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce(Invoke(&helper, &Helper::ComplexJob)) + .WillOnce([] { return true; }) + .WillRepeatedly([](int x) { return x > 0; }); + + foo.Sum(5, 6); // Invokes CalculateSum(5, 6). + foo.Sum(2, 3); // Invokes Sum3(1, 2, 3). + foo.ComplexJob(10); // Invokes helper.ComplexJob(10). + foo.ComplexJob(-1); // Invokes the inline lambda. +``` + +The only requirement is that the type of the function, etc must be *compatible* +with the signature of the mock function, meaning that the latter's arguments (if +it takes any) can be implicitly converted to the corresponding arguments of the +former, and the former's return type can be implicitly converted to that of the +latter. So, you can invoke something whose type is *not* exactly the same as the +mock function, as long as it's safe to do so - nice, huh? + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::Invoke; + ... + ResultCallback* is_ok = ...; + ... Invoke(is_ok) ...; // This works. + + BlockingClosure* done = new BlockingClosure; + ... Invoke(implicit_cast(done)) ...; // The cast is necessary. + ``` + +### Using Functions with Extra Info as Actions + +The function or functor you call using `Invoke()` must have the same number of +arguments as the mock function you use it for. Sometimes you may have a function +that takes more arguments, and you are willing to pass in the extra arguments +yourself to fill the gap. You can do this in gMock using callbacks with +pre-bound arguments. Here's an example: + +```cpp +using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(char, DoThis, (int n), (override)); +}; + +char SignOfSum(int x, int y) { + const int sum = x + y; + return (sum > 0) ? '+' : (sum < 0) ? '-' : '0'; +} + +TEST_F(FooTest, Test) { + MockFoo foo; + + EXPECT_CALL(foo, DoThis(2)) + .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); + EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2). +} +``` + +### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments + +`Invoke()` passes the mock function's arguments to the function, etc being +invoked such that the callee has the full context of the call to work with. If +the invoked function is not interested in some or all of the arguments, it can +simply ignore them. + +Yet, a common pattern is that a test author wants to invoke a function without +the arguments of the mock function. She could do that using a wrapper function +that throws away the arguments before invoking an underlining nullary function. +Needless to say, this can be tedious and obscures the intent of the test. + +There are two solutions to this problem. First, you can pass any callable of +zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like +`Invoke()` except that it doesn't pass the mock function's arguments to the +callee. Here's an example of each: + +```cpp +using ::testing::_; +using ::testing::InvokeWithoutArgs; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, ComplexJob, (int n), (override)); +}; + +bool Job1() { ... } +bool Job2(int n, char c) { ... } + +... + MockFoo foo; + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce([] { Job1(); }); + .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a'))); + + foo.ComplexJob(10); // Invokes Job1(). + foo.ComplexJob(20); // Invokes Job2(5, 'a'). +``` + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::InvokeWithoutArgs; + ... + ResultCallback* is_ok = ...; + ... InvokeWithoutArgs(is_ok) ...; // This works. + + BlockingClosure* done = ...; + ... InvokeWithoutArgs(implicit_cast(done)) ...; + // The cast is necessary. + ``` + +### Invoking an Argument of the Mock Function + +Sometimes a mock function will receive a function pointer, a functor (in other +words, a "callable") as an argument, e.g. + +```cpp +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, DoThis, (int n, (ResultCallback1* callback)), + (override)); +}; +``` + +and you may want to invoke this callable argument: + +```cpp +using ::testing::_; +... + MockFoo foo; + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(...); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +{: .callout .note} +NOTE: The section below is legacy documentation from before C++ had lambdas: + +Arghh, you need to refer to a mock function argument but C++ has no lambda +(yet), so you have to define your own action. :-( Or do you really? + +Well, gMock has an action to solve *exactly* this problem: + +```cpp +InvokeArgument(arg_1, arg_2, ..., arg_m) +``` + +will invoke the `N`-th (0-based) argument the mock function receives, with +`arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is a function +pointer, a functor, or a callback. gMock handles them all. + +With that, you could write: + +```cpp +using ::testing::_; +using ::testing::InvokeArgument; +... + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(InvokeArgument<1>(5)); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +What if the callable takes an argument by reference? No problem - just wrap it +inside `std::ref()`: + +```cpp + ... + MOCK_METHOD(bool, Bar, + ((ResultCallback2* callback)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + Helper helper; + ... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(InvokeArgument<0>(5, std::ref(helper))); + // std::ref(helper) guarantees that a reference to helper, not a copy of + // it, will be passed to the callback. +``` + +What if the callable takes an argument by reference and we do **not** wrap the +argument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the +argument, and pass a *reference to the copy*, instead of a reference to the +original value, to the callable. This is especially handy when the argument is a +temporary value: + +```cpp + ... + MOCK_METHOD(bool, DoThat, (bool (*f)(const double& x, const string& s)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + ... + EXPECT_CALL(foo, DoThat(_)) + .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); + // Will execute (*f)(5.0, string("Hi")), where f is the function pointer + // DoThat() receives. Note that the values 5.0 and string("Hi") are + // temporary and dead once the EXPECT_CALL() statement finishes. Yet + // it's fine to perform this action later, since a copy of the values + // are kept inside the InvokeArgument action. +``` + +### Ignoring an Action's Result + +Sometimes you have an action that returns *something*, but you need an action +that returns `void` (perhaps you want to use it in a mock function that returns +`void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the +list). `IgnoreResult()` lets you do that. For example: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::IgnoreResult; +using ::testing::Return; + +int Process(const MyData& data); +string DoSomething(); + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, Abc, (const MyData& data), (override)); + MOCK_METHOD(bool, Xyz, (), (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, Abc(_)) + // .WillOnce(Invoke(Process)); + // The above line won't compile as Process() returns int but Abc() needs + // to return void. + .WillOnce(IgnoreResult(Process)); + EXPECT_CALL(foo, Xyz()) + .WillOnce(DoAll(IgnoreResult(DoSomething), + // Ignores the string DoSomething() returns. + Return(true))); +``` + +Note that you **cannot** use `IgnoreResult()` on an action that already returns +`void`. Doing so will lead to ugly compiler errors. + +### Selecting an Action's Arguments {#SelectingArgs} + +Say you have a mock function `Foo()` that takes seven arguments, and you have a +custom action that you want to invoke when `Foo()` is called. Trouble is, the +custom action only wants three arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... + MOCK_METHOD(bool, Foo, + (bool visible, const string& name, int x, int y, + (const map>), double& weight, double min_weight, + double max_wight)); +... +bool IsVisibleInQuadrant1(bool visible, int x, int y) { + return visible && x >= 0 && y >= 0; +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( +``` + +To please the compiler God, you need to define an "adaptor" that has the same +signature as `Foo()` and calls the custom action with the right arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... +bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, + const map, double>& weight, + double min_weight, double max_wight) { + return IsVisibleInQuadrant1(visible, x, y); +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. +``` + +But isn't this awkward? + +gMock provides a generic *action adaptor*, so you can spend your time minding +more important business than writing your own adaptors. Here's the syntax: + +```cpp +WithArgs(action) +``` + +creates an action that passes the arguments of the mock function at the given +indices (0-based) to the inner `action` and performs it. Using `WithArgs`, our +original example can be written as: + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::WithArgs; +... + EXPECT_CALL(mock, Foo) + .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); // No need to define your own adaptor. +``` + +For better readability, gMock also gives you: + +* `WithoutArgs(action)` when the inner `action` takes *no* argument, and +* `WithArg(action)` (no `s` after `Arg`) when the inner `action` takes + *one* argument. + +As you may have realized, `InvokeWithoutArgs(...)` is just syntactic sugar for +`WithoutArgs(Invoke(...))`. + +Here are more tips: + +* The inner action used in `WithArgs` and friends does not have to be + `Invoke()` -- it can be anything. +* You can repeat an argument in the argument list if necessary, e.g. + `WithArgs<2, 3, 3, 5>(...)`. +* You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. +* The types of the selected arguments do *not* have to match the signature of + the inner action exactly. It works as long as they can be implicitly + converted to the corresponding arguments of the inner action. For example, + if the 4-th argument of the mock function is an `int` and `my_action` takes + a `double`, `WithArg<4>(my_action)` will work. + +### Ignoring Arguments in Action Functions + +The [selecting-an-action's-arguments](#SelectingArgs) recipe showed us one way +to make a mock function and an action with incompatible argument lists fit +together. The downside is that wrapping the action in `WithArgs<...>()` can get +tedious for people writing the tests. + +If you are defining a function (or method, functor, lambda, callback) to be used +with `Invoke*()`, and you are not interested in some of its arguments, an +alternative to `WithArgs` is to declare the uninteresting arguments as `Unused`. +This makes the definition less cluttered and less fragile in case the types of +the uninteresting arguments change. It could also increase the chance the action +function can be reused. For example, given + +```cpp + public: + MOCK_METHOD(double, Foo, double(const string& label, double x, double y), + (override)); + MOCK_METHOD(double, Bar, (int index, double x, double y), (override)); +``` + +instead of + +```cpp +using ::testing::_; +using ::testing::Invoke; + +double DistanceToOriginWithLabel(const string& label, double x, double y) { + return sqrt(x*x + y*y); +} +double DistanceToOriginWithIndex(int index, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOriginWithLabel)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOriginWithIndex)); +``` + +you could write + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::Unused; + +double DistanceToOrigin(Unused, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOrigin)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOrigin)); +``` + +### Sharing Actions + +Just like matchers, a gMock action object consists of a pointer to a ref-counted +implementation object. Therefore copying actions is also allowed and very +efficient. When the last action that references the implementation object dies, +the implementation object will be deleted. + +If you have some complex action that you want to use again and again, you may +not have to build it from scratch every time. If the action doesn't have an +internal state (i.e. if it always does the same thing no matter how many times +it has been called), you can assign it to an action variable and use that +variable repeatedly. For example: + +```cpp +using ::testing::Action; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; +... + Action set_flag = DoAll(SetArgPointee<0>(5), + Return(true)); + ... use set_flag in .WillOnce() and .WillRepeatedly() ... +``` + +However, if the action has its own state, you may be surprised if you share the +action object. Suppose you have an action factory `IncrementCounter(init)` which +creates an action that increments and returns a counter whose initial value is +`init`, using two actions created from the same expression and using a shared +action will exhibit different behaviors. Example: + +```cpp + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(IncrementCounter(0)); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(IncrementCounter(0)); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 1 - DoThat() uses a different + // counter than DoThis()'s. +``` + +versus + +```cpp +using ::testing::Action; +... + Action increment = IncrementCounter(0); + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(increment); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(increment); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 3 - the counter is shared. +``` + +### Testing Asynchronous Behavior + +One oft-encountered problem with gMock is that it can be hard to test +asynchronous behavior. Suppose you had a `EventQueue` class that you wanted to +test, and you created a separate `EventDispatcher` interface so that you could +easily mock it out. However, the implementation of the class fired all the +events on a background thread, which made test timings difficult. You could just +insert `sleep()` statements and hope for the best, but that makes your test +behavior nondeterministic. A better way is to use gMock actions and +`Notification` objects to force your asynchronous test to behave synchronously. + +```cpp +class MockEventDispatcher : public EventDispatcher { + MOCK_METHOD(bool, DispatchEvent, (int32), (override)); +}; + +TEST(EventQueueTest, EnqueueEventTest) { + MockEventDispatcher mock_event_dispatcher; + EventQueue event_queue(&mock_event_dispatcher); + + const int32 kEventId = 321; + absl::Notification done; + EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId)) + .WillOnce([&done] { done.Notify(); }); + + event_queue.EnqueueEvent(kEventId); + done.WaitForNotification(); +} +``` + +In the example above, we set our normal gMock expectations, but then add an +additional action to notify the `Notification` object. Now we can just call +`Notification::WaitForNotification()` in the main thread to wait for the +asynchronous call to finish. After that, our test suite is complete and we can +safely exit. + +{: .callout .note} +Note: this example has a downside: namely, if the expectation is not satisfied, +our test will run forever. It will eventually time-out and fail, but it will +take longer and be slightly harder to debug. To alleviate this problem, you can +use `WaitForNotificationWithTimeout(ms)` instead of `WaitForNotification()`. + +## Misc Recipes on Using gMock + +### Mocking Methods That Use Move-Only Types + +C++11 introduced *move-only types*. A move-only-typed value can be moved from +one object to another, but cannot be copied. `std::unique_ptr` is probably +the most commonly used move-only type. + +Mocking a method that takes and/or returns move-only types presents some +challenges, but nothing insurmountable. This recipe shows you how you can do it. +Note that the support for move-only method arguments was only introduced to +gMock in April 2017; in older code, you may find more complex +[workarounds](#LegacyMoveOnly) for lack of this feature. + +Let’s say we are working on a fictional project that lets one post and share +snippets called “buzzes”. Your code uses these types: + +```cpp +enum class AccessLevel { kInternal, kPublic }; + +class Buzz { + public: + explicit Buzz(AccessLevel access) { ... } + ... +}; + +class Buzzer { + public: + virtual ~Buzzer() {} + virtual std::unique_ptr MakeBuzz(StringPiece text) = 0; + virtual bool ShareBuzz(std::unique_ptr buzz, int64_t timestamp) = 0; + ... +}; +``` + +A `Buzz` object represents a snippet being posted. A class that implements the +`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in +`Buzzer` may return a `unique_ptr` or take a `unique_ptr`. Now we +need to mock `Buzzer` in our tests. + +To mock a method that accepts or returns move-only types, you just use the +familiar `MOCK_METHOD` syntax as usual: + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(std::unique_ptr, MakeBuzz, (StringPiece text), (override)); + MOCK_METHOD(bool, ShareBuzz, (std::unique_ptr buzz, int64_t timestamp), + (override)); +}; +``` + +Now that we have the mock class defined, we can use it in tests. In the +following code examples, we assume that we have defined a `MockBuzzer` object +named `mock_buzzer_`: + +```cpp + MockBuzzer mock_buzzer_; +``` + +First let’s see how we can set expectations on the `MakeBuzz()` method, which +returns a `unique_ptr`. + +As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or +`.WillRepeatedly()` clause), when that expectation fires, the default action for +that method will be taken. Since `unique_ptr<>` has a default constructor that +returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an +action: + +```cpp +using ::testing::IsNull; +... + // Use the default action. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); + + // Triggers the previous EXPECT_CALL. + EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull()); +``` + +If you are not happy with the default action, you can tweak it as usual; see +[Setting Default Actions](#OnCall). + +If you just need to return a move-only value, you can use it in combination with +`WillOnce`. For example: + +```cpp + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")) + .WillOnce(Return(std::make_unique(AccessLevel::kInternal))); + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello")); +``` + +Quiz time! What do you think will happen if a `Return` action is performed more +than once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come +think of it, after the first time the action runs, the source value will be +consumed (since it’s a move-only value), so the next time around, there’s no +value to move from -- you’ll get a run-time error that `Return(std::move(...))` +can only be run once. + +If you need your mock method to do more than just moving a pre-defined value, +remember that you can always use a lambda or a callable object, which can do +pretty much anything you want: + +```cpp + EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) + .WillRepeatedly([](StringPiece text) { + return std::make_unique(AccessLevel::kInternal); + }); + + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); +``` + +Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be created +and returned. You cannot do this with `Return(std::make_unique<...>(...))`. + +That covers returning move-only values; but how do we work with methods +accepting move-only arguments? The answer is that they work normally, although +some actions will not compile when any of method's arguments are move-only. You +can always use `Return`, or a [lambda or functor](#FunctionsAsActions): + +```cpp + using ::testing::Unused; + + EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true)); + EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal)), + 0); + + EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce( + [](std::unique_ptr buzz, Unused) { return buzz != nullptr; }); + EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); +``` + +Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) +could in principle support move-only arguments, but the support for this is not +implemented yet. If this is blocking you, please file a bug. + +A few actions (e.g. `DoAll`) copy their arguments internally, so they can never +work with non-copyable objects; you'll have to use functors instead. + +#### Legacy workarounds for move-only types {#LegacyMoveOnly} + +Support for move-only function arguments was only introduced to gMock in April +of 2017. In older code, you may encounter the following workaround for the lack +of this feature (it is no longer necessary - we're including it just for +reference): + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(bool, DoShareBuzz, (Buzz* buzz, Time timestamp)); + bool ShareBuzz(std::unique_ptr buzz, Time timestamp) override { + return DoShareBuzz(buzz.get(), timestamp); + } +}; +``` + +The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call +it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of +setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock +method: + +```cpp + MockBuzzer mock_buzzer_; + EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); + + // When one calls ShareBuzz() on the MockBuzzer like this, the call is + // forwarded to DoShareBuzz(), which is mocked. Therefore this statement + // will trigger the above EXPECT_CALL. + mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal), 0); +``` + +### Making the Compilation Faster + +Believe it or not, the *vast majority* of the time spent on compiling a mock +class is in generating its constructor and destructor, as they perform +non-trivial tasks (e.g. verification of the expectations). What's more, mock +methods with different signatures have different types and thus their +constructors/destructors need to be generated by the compiler separately. As a +result, if you mock many different types of methods, compiling your mock class +can get really slow. + +If you are experiencing slow compilation, you can move the definition of your +mock class' constructor and destructor out of the class body and into a `.cc` +file. This way, even if you `#include` your mock class in N files, the compiler +only needs to generate its constructor and destructor once, resulting in a much +faster compilation. + +Let's illustrate the idea using an example. Here's the definition of a mock +class before applying this recipe: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // Since we don't declare the constructor or the destructor, + // the compiler will generate them in every translation unit + // where this mock class is used. + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +After the change, it would look like: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // The constructor and destructor are declared, but not defined, here. + MockFoo(); + virtual ~MockFoo(); + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +and + +```cpp +// File mock_foo.cc. +#include "path/to/mock_foo.h" + +// The definitions may appear trivial, but the functions actually do a +// lot of things through the constructors/destructors of the member +// variables used to implement the mock methods. +MockFoo::MockFoo() {} +MockFoo::~MockFoo() {} +``` + +### Forcing a Verification + +When it's being destroyed, your friendly mock object will automatically verify +that all expectations on it have been satisfied, and will generate googletest +failures if not. This is convenient as it leaves you with one less thing to +worry about. That is, unless you are not sure if your mock object will be +destroyed. + +How could it be that your mock object won't eventually be destroyed? Well, it +might be created on the heap and owned by the code you are testing. Suppose +there's a bug in that code and it doesn't delete the mock object properly - you +could end up with a passing test when there's actually a bug. + +Using a heap checker is a good idea and can alleviate the concern, but its +implementation is not 100% reliable. So, sometimes you do want to *force* gMock +to verify a mock object before it is (hopefully) destructed. You can do this +with `Mock::VerifyAndClearExpectations(&mock_object)`: + +```cpp +TEST(MyServerTest, ProcessesRequest) { + using ::testing::Mock; + + MockFoo* const foo = new MockFoo; + EXPECT_CALL(*foo, ...)...; + // ... other expectations ... + + // server now owns foo. + MyServer server(foo); + server.ProcessRequest(...); + + // In case that server's destructor will forget to delete foo, + // this will verify the expectations anyway. + Mock::VerifyAndClearExpectations(foo); +} // server is destroyed when it goes out of scope here. +``` + +{: .callout .tip} +**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to +indicate whether the verification was successful (`true` for yes), so you can +wrap that function call inside a `ASSERT_TRUE()` if there is no point going +further when the verification has failed. + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +### Using Checkpoints {#UsingCheckPoints} + +Sometimes you might want to test a mock object's behavior in phases whose sizes +are each manageable, or you might want to set more detailed expectations about +which API calls invoke which mock functions. + +A technique you can use is to put the expectations in a sequence and insert +calls to a dummy "checkpoint" function at specific places. Then you can verify +that the mock function calls do happen at the right time. For example, if you +are exercising the code: + +```cpp + Foo(1); + Foo(2); + Foo(3); +``` + +and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but +`Foo(2)` doesn't invoke anything, you can write: + +```cpp +using ::testing::MockFunction; + +TEST(FooTest, InvokesBarCorrectly) { + MyMock mock; + // Class MockFunction has exactly one mock method. It is named + // Call() and has type F. + MockFunction check; + { + InSequence s; + + EXPECT_CALL(mock, Bar("a")); + EXPECT_CALL(check, Call("1")); + EXPECT_CALL(check, Call("2")); + EXPECT_CALL(mock, Bar("a")); + } + Foo(1); + check.Call("1"); + Foo(2); + check.Call("2"); + Foo(3); +} +``` + +The expectation spec says that the first `Bar("a")` call must happen before +checkpoint "1", the second `Bar("a")` call must happen after checkpoint "2", and +nothing should happen between the two checkpoints. The explicit checkpoints make +it clear which `Bar("a")` is called by which call to `Foo()`. + +### Mocking Destructors + +Sometimes you want to make sure a mock object is destructed at the right time, +e.g. after `bar->A()` is called but before `bar->B()` is called. We already know +that you can specify constraints on the [order](#OrderedCalls) of mock function +calls, so all we need to do is to mock the destructor of the mock function. + +This sounds simple, except for one problem: a destructor is a special function +with special syntax and special semantics, and the `MOCK_METHOD` macro doesn't +work for it: + +```cpp +MOCK_METHOD(void, ~MockFoo, ()); // Won't compile! +``` + +The good news is that you can use a simple pattern to achieve the same effect. +First, add a mock function `Die()` to your mock class and call it in the +destructor, like this: + +```cpp +class MockFoo : public Foo { + ... + // Add the following two lines to the mock class. + MOCK_METHOD(void, Die, ()); + ~MockFoo() override { Die(); } +}; +``` + +(If the name `Die()` clashes with an existing symbol, choose another name.) Now, +we have translated the problem of testing when a `MockFoo` object dies to +testing when its `Die()` method is called: + +```cpp + MockFoo* foo = new MockFoo; + MockBar* bar = new MockBar; + ... + { + InSequence s; + + // Expects *foo to die after bar->A() and before bar->B(). + EXPECT_CALL(*bar, A()); + EXPECT_CALL(*foo, Die()); + EXPECT_CALL(*bar, B()); + } +``` + +And that's that. + +### Using gMock and Threads {#UsingThreads} + +In a **unit** test, it's best if you could isolate and test a piece of code in a +single-threaded context. That avoids race conditions and dead locks, and makes +debugging your test much easier. + +Yet most programs are multi-threaded, and sometimes to test something we need to +pound on it from more than one thread. gMock works for this purpose too. + +Remember the steps for using a mock: + +1. Create a mock object `foo`. +2. Set its default actions and expectations using `ON_CALL()` and + `EXPECT_CALL()`. +3. The code under test calls methods of `foo`. +4. Optionally, verify and reset the mock. +5. Destroy the mock yourself, or let the code under test destroy it. The + destructor will automatically verify it. + +If you follow the following simple rules, your mocks and threads can live +happily together: + +* Execute your *test code* (as opposed to the code being tested) in *one* + thread. This makes your test easy to follow. +* Obviously, you can do step #1 without locking. +* When doing step #2 and #5, make sure no other thread is accessing `foo`. + Obvious too, huh? +* #3 and #4 can be done either in one thread or in multiple threads - anyway + you want. gMock takes care of the locking, so you don't have to do any - + unless required by your test logic. + +If you violate the rules (for example, if you set expectations on a mock while +another thread is calling its methods), you get undefined behavior. That's not +fun, so don't do it. + +gMock guarantees that the action for a mock function is done in the same thread +that called the mock function. For example, in + +```cpp + EXPECT_CALL(mock, Foo(1)) + .WillOnce(action1); + EXPECT_CALL(mock, Foo(2)) + .WillOnce(action2); +``` + +if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, gMock will +execute `action1` in thread 1 and `action2` in thread 2. + +gMock does *not* impose a sequence on actions performed in different threads +(doing so may create deadlocks as the actions may need to cooperate). This means +that the execution of `action1` and `action2` in the above example *may* +interleave. If this is a problem, you should add proper synchronization logic to +`action1` and `action2` to make the test thread-safe. + +Also, remember that `DefaultValue` is a global resource that potentially +affects *all* living mock objects in your program. Naturally, you won't want to +mess with it from multiple threads or when there still are mocks in action. + +### Controlling How Much Information gMock Prints + +When gMock sees something that has the potential of being an error (e.g. a mock +function with no expectation is called, a.k.a. an uninteresting call, which is +allowed but perhaps you forgot to explicitly ban the call), it prints some +warning messages, including the arguments of the function, the return value, and +the stack trace. Hopefully this will remind you to take a look and see if there +is indeed a problem. + +Sometimes you are confident that your tests are correct and may not appreciate +such friendly messages. Some other times, you are debugging your tests or +learning about the behavior of the code you are testing, and wish you could +observe every mock call that happens (including argument values, the return +value, and the stack trace). Clearly, one size doesn't fit all. + +You can control how much gMock tells you using the `--gmock_verbose=LEVEL` +command-line flag, where `LEVEL` is a string with three possible values: + +* `info`: gMock will print all informational messages, warnings, and errors + (most verbose). At this setting, gMock will also log any calls to the + `ON_CALL/EXPECT_CALL` macros. It will include a stack trace in + "uninteresting call" warnings. +* `warning`: gMock will print both warnings and errors (less verbose); it will + omit the stack traces in "uninteresting call" warnings. This is the default. +* `error`: gMock will print errors only (least verbose). + +Alternatively, you can adjust the value of that flag from within your tests like +so: + +```cpp + ::testing::FLAGS_gmock_verbose = "error"; +``` + +If you find gMock printing too many stack frames with its informational or +warning messages, remember that you can control their amount with the +`--gtest_stack_trace_depth=max_depth` flag. + +Now, judiciously use the right flag to enable gMock serve you better! + +### Gaining Super Vision into Mock Calls + +You have a test using gMock. It fails: gMock tells you some expectations aren't +satisfied. However, you aren't sure why: Is there a typo somewhere in the +matchers? Did you mess up the order of the `EXPECT_CALL`s? Or is the code under +test doing something wrong? How can you find out the cause? + +Won't it be nice if you have X-ray vision and can actually see the trace of all +`EXPECT_CALL`s and mock method calls as they are made? For each call, would you +like to see its actual argument values and which `EXPECT_CALL` gMock thinks it +matches? If you still need some help to figure out who made these calls, how +about being able to see the complete stack trace at each mock call? + +You can unlock this power by running your test with the `--gmock_verbose=info` +flag. For example, given the test program: + +```cpp +#include + +using ::testing::_; +using ::testing::HasSubstr; +using ::testing::Return; + +class MockFoo { + public: + MOCK_METHOD(void, F, (const string& x, const string& y)); +}; + +TEST(Foo, Bar) { + MockFoo mock; + EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(mock, F("a", "b")); + EXPECT_CALL(mock, F("c", HasSubstr("d"))); + + mock.F("a", "good"); + mock.F("a", "b"); +} +``` + +if you run it with `--gmock_verbose=info`, you will see this output: + +```shell +[ RUN ] Foo.Bar + +foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked +Stack trace: ... + +foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked +Stack trace: ... + +foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked +Stack trace: ... + +foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... + Function call: F(@0x7fff7c8dad40"a",@0x7fff7c8dad10"good") +Stack trace: ... + +foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... + Function call: F(@0x7fff7c8dada0"a",@0x7fff7c8dad70"b") +Stack trace: ... + +foo_test.cc:16: Failure +Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... + Expected: to be called once + Actual: never called - unsatisfied and active +[ FAILED ] Foo.Bar +``` + +Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo and +should actually be `"a"`. With the above message, you should see that the actual +`F("a", "good")` call is matched by the first `EXPECT_CALL`, not the third as +you thought. From that it should be obvious that the third `EXPECT_CALL` is +written wrong. Case solved. + +If you are interested in the mock call trace but not the stack traces, you can +combine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test +command line. + +### Running Tests in Emacs + +If you build and run your tests in Emacs using the `M-x google-compile` command +(as many googletest users do), the source file locations of gMock and googletest +errors will be highlighted. Just press `` on one of them and you'll be +taken to the offending line. Or, you can just type `C-x`` to jump to the next +error. + +To make it even easier, you can add the following lines to your `~/.emacs` file: + +```text +(global-set-key "\M-m" 'google-compile) ; m is for make +(global-set-key [M-down] 'next-error) +(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) +``` + +Then you can type `M-m` to start a build (if you want to run the test as well, +just make sure `foo_test.run` or `runtests` is in the build command you supply +after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors. + +## Extending gMock + +### Writing New Matchers Quickly {#NewMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be functionally pure. See +[this section](#PureMatchers) for more details. + +The `MATCHER*` family of macros can be used to define custom matchers easily. +The syntax: + +```cpp +MATCHER(name, description_string_expression) { statements; } +``` + +will define a matcher with the given name that executes the statements, which +must return a `bool` to indicate if the match succeeds. Inside the statements, +you can refer to the value being matched by `arg`, and refer to its type by +`arg_type`. + +The *description string* is a `string`-typed expression that documents what the +matcher does, and is used to generate the failure message when the match fails. +It can (and should) reference the special `bool` variable `negation`, and should +evaluate to the description of the matcher when `negation` is `false`, or that +of the matcher's negation when `negation` is `true`. + +For convenience, we allow the description string to be empty (`""`), in which +case gMock will use the sequence of words in the matcher name as the +description. + +#### Basic Example + +```cpp +MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } +``` + +allows you to write + +```cpp + // Expects mock_foo.Bar(n) to be called where n is divisible by 7. + EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); +``` + +or, + +```cpp + using ::testing::Not; + ... + // Verifies that a value is divisible by 7 and the other is not. + EXPECT_THAT(some_expression, IsDivisibleBy7()); + EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); +``` + +If the above assertions fail, they will print something like: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 + ... + Value of: some_other_expression + Expected: not (is divisible by 7) + Actual: 21 +``` + +where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are +automatically calculated from the matcher name `IsDivisibleBy7`. + +#### Adding Custom Failure Messages + +As you may have noticed, the auto-generated descriptions (especially those for +the negation) may not be so great. You can always override them with a `string` +expression of your own: + +```cpp +MATCHER(IsDivisibleBy7, + absl::StrCat(negation ? "isn't" : "is", " divisible by 7")) { + return (arg % 7) == 0; +} +``` + +Optionally, you can stream additional information to a hidden argument named +`result_listener` to explain the match result. For example, a better definition +of `IsDivisibleBy7` is: + +```cpp +MATCHER(IsDivisibleBy7, "") { + if ((arg % 7) == 0) + return true; + + *result_listener << "the remainder is " << (arg % 7); + return false; +} +``` + +With this definition, the above assertion will give a better message: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 (the remainder is 6) +``` + +#### Using EXPECT_ Statements in Matchers + +You can also use `EXPECT_...` statements inside custom matcher definitions. In +many cases, this allows you to write your matcher more concisely while still +providing an informative error message. For example: + +```cpp +MATCHER(IsDivisibleBy7, "") { + const auto remainder = arg % 7; + EXPECT_EQ(remainder, 0); + return true; +} +``` + +If you write a test that includes the line `EXPECT_THAT(27, IsDivisibleBy7());`, +you will get an error something like the following: + +```shell +Expected equality of these values: + remainder + Which is: 6 + 0 +``` + +#### `MatchAndExplain` + +You should let `MatchAndExplain()` print *any additional information* that can +help a user understand the match result. Note that it should explain why the +match succeeds in case of a success (unless it's obvious) - this is useful when +the matcher is used inside `Not()`. There is no need to print the argument value +itself, as gMock already prints it for you. + +#### Argument Types + +The type of the value being matched (`arg_type`) is determined by the context in +which you use the matcher and is supplied to you by the compiler, so you don't +need to worry about declaring it (nor can you). This allows the matcher to be +polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where +the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the +`Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, +`arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be +`unsigned long`; and so on. + +### Writing New Parameterized Matchers Quickly + +Sometimes you'll want to define a matcher that has parameters. For that you can +use the macro: + +```cpp +MATCHER_P(name, param_name, description_string) { statements; } +``` + +where the description string can be either `""` or a `string` expression that +references `negation` and `param_name`. + +For example: + +```cpp +MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +``` + +will allow you to write: + +```cpp + EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +``` + +which may lead to this message (assuming `n` is 10): + +```shell + Value of: Blah("a") + Expected: has absolute value 10 + Actual: -9 +``` + +Note that both the matcher description and its parameter are printed, making the +message human-friendly. + +In the matcher definition body, you can write `foo_type` to reference the type +of a parameter named `foo`. For example, in the body of +`MATCHER_P(HasAbsoluteValue, value)` above, you can write `value_type` to refer +to the type of `value`. + +gMock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to +support multi-parameter matchers: + +```cpp +MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } +``` + +Please note that the custom description string is for a particular *instance* of +the matcher, where the parameters have been bound to actual values. Therefore +usually you'll want the parameter values to be part of the description. gMock +lets you do that by referencing the matcher parameters in the description string +expression. + +For example, + +```cpp +using ::testing::PrintToString; +MATCHER_P2(InClosedRange, low, hi, + absl::StrFormat("%s in range [%s, %s]", negation ? "isn't" : "is", + PrintToString(low), PrintToString(hi))) { + return low <= arg && arg <= hi; +} +... +EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the message: + +```shell + Expected: is in range [4, 6] +``` + +If you specify `""` as the description, the failure message will contain the +sequence of words in the matcher name followed by the parameter values printed +as a tuple. For example, + +```cpp + MATCHER_P2(InClosedRange, low, hi, "") { ... } + ... + EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the text: + +```shell + Expected: in closed range (4, 6) +``` + +For the purpose of typing, you can view + +```cpp +MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +``` + +as shorthand for + +```cpp +template +FooMatcherPk +Foo(p1_type p1, ..., pk_type pk) { ... } +``` + +When you write `Foo(v1, ..., vk)`, the compiler infers the types of the +parameters `v1`, ..., and `vk` for you. If you are not happy with the result of +the type inference, you can specify the types by explicitly instantiating the +template, as in `Foo(5, false)`. As said earlier, you don't get to +(or need to) specify `arg_type` as that's determined by the context in which the +matcher is used. + +You can assign the result of expression `Foo(p1, ..., pk)` to a variable of type +`FooMatcherPk`. This can be useful when composing +matchers. Matchers that don't have a parameter or have only one parameter have +special types: you can assign `Foo()` to a `FooMatcher`-typed variable, and +assign `Foo(p)` to a `FooMatcherP`-typed variable. + +While you can instantiate a matcher template with reference types, passing the +parameters by pointer usually makes your code more readable. If, however, you +still want to pass a parameter by reference, be aware that in the failure +message generated by the matcher you will see the value of the referenced object +but not its address. + +You can overload matchers with different numbers of parameters: + +```cpp +MATCHER_P(Blah, a, description_string_1) { ... } +MATCHER_P2(Blah, a, b, description_string_2) { ... } +``` + +While it's tempting to always use the `MATCHER*` macros when defining a new +matcher, you should also consider implementing the matcher interface directly +instead (see the recipes that follow), especially if you need to use the matcher +a lot. While these approaches require more work, they give you more control on +the types of the value being matched and the matcher parameters, which in +general leads to better compiler error messages that pay off in the long run. +They also allow overloading matchers based on parameter types (as opposed to +just based on the number of parameters). + +### Writing New Monomorphic Matchers + +A matcher of type `testing::Matcher` implements the matcher interface for `T` +and does two things: it tests whether a value of type `T` matches the matcher, +and can describe what kind of values it matches. The latter ability is used for +generating readable error messages when expectations are violated. Some matchers +can even explain why it matches or doesn't match a certain value, which can be +helpful when the reason isn't obvious. + +Because a matcher of type `testing::Matcher` for a particular type `T` can +only be used to match a value of type `T`, we call it "monomorphic." + +A matcher of `T` must declare a typedef like: + +```cpp +using is_gtest_matcher = void; +``` + +and supports the following operations: + +```cpp +// Match a value and optionally explain into an ostream. +bool matched = matcher.MatchAndExplain(value, maybe_os); +// where `value` is of type `T` and +// `maybe_os` is of type `std::ostream*`, where it can be null if the caller +// is not interested in there textual explanation. + +matcher.DescribeTo(os); +matcher.DescribeNegationTo(os); +// where `os` is of type `std::ostream*`. +``` + +If you need a custom matcher but `Truly()` is not a good option (for example, +you may not be happy with the way `Truly(predicate)` describes itself, or you +may want your matcher to be polymorphic as `Eq(value)` is), you can define a +matcher to do whatever you want in two steps: first implement the matcher +interface, and then define a factory function to create a matcher instance. The +second step is not strictly needed but it makes the syntax of using the matcher +nicer. + +For example, you can define a matcher to test whether an `int` is divisible by 7 +and then use it like this: + +```cpp +using ::testing::Matcher; + +class DivisibleBy7Matcher { + public: + using is_gtest_matcher = void; + + bool MatchAndExplain(int n, std::ostream*) const { + return (n % 7) == 0; + } + + void DescribeTo(std::ostream* os) const { + *os << "is divisible by 7"; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is not divisible by 7"; + } +}; + +Matcher DivisibleBy7() { + return DivisibleBy7Matcher(); +} + +... + EXPECT_CALL(foo, Bar(DivisibleBy7())); +``` + +You may improve the matcher message by streaming additional information to the +`os` argument in `MatchAndExplain()`: + +```cpp +class DivisibleBy7Matcher { + public: + bool MatchAndExplain(int n, std::ostream* os) const { + const int remainder = n % 7; + if (remainder != 0 && os != nullptr) { + *os << "the remainder is " << remainder; + } + return remainder == 0; + } + ... +}; +``` + +Then, `EXPECT_THAT(x, DivisibleBy7());` may generate a message like this: + +```shell +Value of: x +Expected: is divisible by 7 + Actual: 23 (the remainder is 2) +``` + +{: .callout .tip} +Tip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*` +instead of `std::ostream*`. + +### Writing New Polymorphic Matchers + +Unlike a monomorphic matcher, which can only be used to match a value of a +particular type, a *polymorphic* matcher is one that can be used to match values +of multiple types. For example, `Eq(5)` is a polymorhpic matcher as it can be +used to match an `int`, a `double`, a `float`, and so on. You should think of a +polymorphic matcher as a *matcher factory* as opposed to a +`testing::Matcher` - itself is not an actual matcher, but can be +implicitly converted to a `testing::Matcher` depending on the context. + +Expanding what we learned above to polymorphic matchers is now as simple as +adding templates in the right place. + +```cpp + +class NotNullMatcher { + public: + using is_gtest_matcher = void; + + // To implement a polymorphic matcher, we just need to make MatchAndExplain a + // template on its first argument. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, std::ostream*) const { + return p != nullptr; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +NotNullMatcher NotNull() { + return NotNullMatcher(); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +### Legacy Matcher Implementation + +Defining matchers used to be somewhat more complicated, in which it required +several supporting classes and virtual functions. To implement a matcher for +type `T` using the legacy API you have to derive from `MatcherInterface` and +call `MakeMatcher` to construct the object. + +The interface looks like this: + +```cpp +class MatchResultListener { + public: + ... + // Streams x to the underlying ostream; does nothing if the ostream + // is NULL. + template + MatchResultListener& operator<<(const T& x); + + // Returns the underlying ostream. + std::ostream* stream(); +}; + +template +class MatcherInterface { + public: + virtual ~MatcherInterface(); + + // Returns true if and only if the matcher matches x; also explains the match + // result to 'listener'. + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; + + // Describes this matcher to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; + + // Describes the negation of this matcher to an ostream. + virtual void DescribeNegationTo(std::ostream* os) const; +}; +``` + +Fortunately, most of the time you can define a polymorphic matcher easily with +the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as +an example: + +```cpp +using ::testing::MakePolymorphicMatcher; +using ::testing::MatchResultListener; +using ::testing::PolymorphicMatcher; + +class NotNullMatcher { + public: + // To implement a polymorphic matcher, first define a COPYABLE class + // that has three members MatchAndExplain(), DescribeTo(), and + // DescribeNegationTo(), like the following. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, + MatchResultListener* /* listener */) const { + return p != NULL; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +// To construct a polymorphic matcher, pass an instance of the class +// to MakePolymorphicMatcher(). Note the return type. +PolymorphicMatcher NotNull() { + return MakePolymorphicMatcher(NotNullMatcher()); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +{: .callout .note} +**Note:** Your polymorphic matcher class does **not** need to inherit from +`MatcherInterface` or any other class, and its methods do **not** need to be +virtual. + +Like in a monomorphic matcher, you may explain the match result by streaming +additional information to the `listener` argument in `MatchAndExplain()`. + +### Implementing Composite Matchers {#CompositeMatchers} + +Sometimes we want to define a matcher that takes other matchers as parameters. +For example, `DistanceFrom(target, m)` is a polymorphic matcher that takes a +matcher `m` as a parameter. It tests that the distance from `target` to the +value being matched satisfies sub-matcher `m`. + +If you are implementing such a composite matcher, you'll need to generate the +description of the matcher based on the description(s) of its sub-matcher(s). +You can see the implementation of `DistanceFrom()` in +`googlemock/include/gmock/gmock-matchers.h` for an example. In particular, pay +attention to `DistanceFromMatcherImpl`. Notice that it stores the sub-matcher as +a `const Matcher distance_matcher_` instead of a polymorphic +matcher - this allows it to call `distance_matcher_.DescribeTo(os)` to describe +the sub-matcher. If the sub-matcher is stored as a polymorphic matcher instead, +it would not be possible to get its description as in general polymorphic +matchers don't know how to describe themselves - they are matcher factories +instead of actual matchers; only after being converted to `Matcher` +can they be described. + +### Writing New Cardinalities + +A cardinality is used in `Times()` to tell gMock how many times you expect a +call to occur. It doesn't have to be exact. For example, you can say +`AtLeast(5)` or `Between(2, 4)`. + +If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities +doesn't suit you, you are free to define your own by implementing the following +interface (in namespace `testing`): + +```cpp +class CardinalityInterface { + public: + virtual ~CardinalityInterface(); + + // Returns true if and only if call_count calls will satisfy this cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; +}; +``` + +For example, to specify that a call must occur even number of times, you can +write + +```cpp +using ::testing::Cardinality; +using ::testing::CardinalityInterface; +using ::testing::MakeCardinality; + +class EvenNumberCardinality : public CardinalityInterface { + public: + bool IsSatisfiedByCallCount(int call_count) const override { + return (call_count % 2) == 0; + } + + bool IsSaturatedByCallCount(int call_count) const override { + return false; + } + + void DescribeTo(std::ostream* os) const { + *os << "called even number of times"; + } +}; + +Cardinality EvenNumber() { + return MakeCardinality(new EvenNumberCardinality); +} + +... + EXPECT_CALL(foo, Bar(3)) + .Times(EvenNumber()); +``` + +### Writing New Actions {#QuickNewActions} + +If the built-in actions don't work for you, you can easily define your own one. +All you need is a call operator with a signature compatible with the mocked +function. So you can use a lambda: + +```cpp +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); +EXPECT_EQ(mock.AsStdFunction()(2), 14); +``` + +Or a struct with a call operator (even a templated one): + +```cpp +struct MultiplyBy { + template + T operator()(T arg) { return arg * multiplier; } + + int multiplier; +}; + +// Then use: +// EXPECT_CALL(...).WillOnce(MultiplyBy{7}); +``` + +It's also fine for the callable to take no arguments, ignoring the arguments +supplied to the mock function: + +```cpp +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); +EXPECT_EQ(mock.AsStdFunction()(0), 17); +``` + +When used with `WillOnce`, the callable can assume it will be called at most +once and is allowed to be a move-only type: + +```cpp +// An action that contains move-only types and has an &&-qualified operator, +// demanding in the type system that it be called at most once. This can be +// used with WillOnce, but the compiler will reject it if handed to +// WillRepeatedly. +struct MoveOnlyAction { + std::unique_ptr move_only_state; + std::unique_ptr operator()() && { return std::move(move_only_state); } +}; + +MockFunction()> mock; +EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique(17)}); +EXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17))); +``` + +More generally, to use with a mock function whose signature is `R(Args...)` the +object can be anything convertible to `OnceAction` or +`Action. The difference between the two is that `OnceAction` has +weaker requirements (`Action` requires a copy-constructible input that can be +called repeatedly whereas `OnceAction` requires only move-constructible and +supports `&&`-qualified call operators), but can be used only with `WillOnce`. +`OnceAction` is typically relevant only when supporting move-only types or +actions that want a type-system guarantee that they will be called at most once. + +Typically the `OnceAction` and `Action` templates need not be referenced +directly in your actions: a struct or class with a call operator is sufficient, +as in the examples above. But fancier polymorphic actions that need to know the +specific return type of the mock function can define templated conversion +operators to make that possible. See `gmock-actions.h` for examples. + +#### Legacy macro-based Actions + +Before C++11, the functor-based actions were not supported; the old way of +writing actions was through a set of `ACTION*` macros. We suggest to avoid them +in new code; they hide a lot of logic behind the macro, potentially leading to +harder-to-understand compiler errors. Nevertheless, we cover them here for +completeness. + +By writing + +```cpp +ACTION(name) { statements; } +``` + +in a namespace scope (i.e. not inside a class or function), you will define an +action with the given name that executes the statements. The value returned by +`statements` will be used as the return value of the action. Inside the +statements, you can refer to the K-th (0-based) argument of the mock function as +`argK`. For example: + +```cpp +ACTION(IncrementArg1) { return ++(*arg1); } +``` + +allows you to write + +```cpp +... WillOnce(IncrementArg1()); +``` + +Note that you don't need to specify the types of the mock function arguments. +Rest assured that your code is type-safe though: you'll get a compiler error if +`*arg1` doesn't support the `++` operator, or if the type of `++(*arg1)` isn't +compatible with the mock function's return type. + +Another example: + +```cpp +ACTION(Foo) { + (*arg2)(5); + Blah(); + *arg1 = 0; + return arg0; +} +``` + +defines an action `Foo()` that invokes argument #2 (a function pointer) with 5, +calls function `Blah()`, sets the value pointed to by argument #1 to 0, and +returns argument #0. + +For more convenience and flexibility, you can also use the following pre-defined +symbols in the body of `ACTION`: + +`argK_type` | The type of the K-th (0-based) argument of the mock function +:-------------- | :----------------------------------------------------------- +`args` | All arguments of the mock function as a tuple +`args_type` | The type of all arguments of the mock function as a tuple +`return_type` | The return type of the mock function +`function_type` | The type of the mock function + +For example, when using an `ACTION` as a stub action for mock function: + +```cpp +int DoSomething(bool flag, int* ptr); +``` + +we have: + +Pre-defined Symbol | Is Bound To +------------------ | --------------------------------- +`arg0` | the value of `flag` +`arg0_type` | the type `bool` +`arg1` | the value of `ptr` +`arg1_type` | the type `int*` +`args` | the tuple `(flag, ptr)` +`args_type` | the type `std::tuple` +`return_type` | the type `int` +`function_type` | the type `int(bool, int*)` + +#### Legacy macro-based parameterized Actions + +Sometimes you'll want to parameterize an action you define. For that we have +another macro + +```cpp +ACTION_P(name, param) { statements; } +``` + +For example, + +```cpp +ACTION_P(Add, n) { return arg0 + n; } +``` + +will allow you to write + +```cpp +// Returns argument #0 + 5. +... WillOnce(Add(5)); +``` + +For convenience, we use the term *arguments* for the values used to invoke the +mock function, and the term *parameters* for the values used to instantiate an +action. + +Note that you don't need to provide the type of the parameter either. Suppose +the parameter is named `param`, you can also use the gMock-defined symbol +`param_type` to refer to the type of the parameter as inferred by the compiler. +For example, in the body of `ACTION_P(Add, n)` above, you can write `n_type` for +the type of `n`. + +gMock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter +actions. For example, + +```cpp +ACTION_P2(ReturnDistanceTo, x, y) { + double dx = arg0 - x; + double dy = arg1 - y; + return sqrt(dx*dx + dy*dy); +} +``` + +lets you write + +```cpp +... WillOnce(ReturnDistanceTo(5.0, 26.5)); +``` + +You can view `ACTION` as a degenerated parameterized action where the number of +parameters is 0. + +You can also easily define actions overloaded on the number of parameters: + +```cpp +ACTION_P(Plus, a) { ... } +ACTION_P2(Plus, a, b) { ... } +``` + +### Restricting the Type of an Argument or Parameter in an ACTION + +For maximum brevity and reusability, the `ACTION*` macros don't ask you to +provide the types of the mock function arguments and the action parameters. +Instead, we let the compiler infer the types for us. + +Sometimes, however, we may want to be more explicit about the types. There are +several tricks to do that. For example: + +```cpp +ACTION(Foo) { + // Makes sure arg0 can be converted to int. + int n = arg0; + ... use n instead of arg0 here ... +} + +ACTION_P(Bar, param) { + // Makes sure the type of arg1 is const char*. + ::testing::StaticAssertTypeEq(); + + // Makes sure param can be converted to bool. + bool flag = param; +} +``` + +where `StaticAssertTypeEq` is a compile-time assertion in googletest that +verifies two types are the same. + +### Writing New Action Templates Quickly + +Sometimes you want to give an action explicit template parameters that cannot be +inferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be +viewed as an extension to `ACTION()` and `ACTION_P*()`. + +The syntax: + +```cpp +ACTION_TEMPLATE(ActionName, + HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), + AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } +``` + +defines an action template that takes *m* explicit template parameters and *n* +value parameters, where *m* is in [1, 10] and *n* is in [0, 10]. `name_i` is the +name of the *i*-th template parameter, and `kind_i` specifies whether it's a +`typename`, an integral constant, or a template. `p_i` is the name of the *i*-th +value parameter. + +Example: + +```cpp +// DuplicateArg(output) converts the k-th argument of the mock +// function to type T and copies it to *output. +ACTION_TEMPLATE(DuplicateArg, + // Note the comma between int and k: + HAS_2_TEMPLATE_PARAMS(int, k, typename, T), + AND_1_VALUE_PARAMS(output)) { + *output = T(std::get(args)); +} +``` + +To create an instance of an action template, write: + +```cpp +ActionName(v1, ..., v_n) +``` + +where the `t`s are the template arguments and the `v`s are the value arguments. +The value argument types are inferred by the compiler. For example: + +```cpp +using ::testing::_; +... + int n; + EXPECT_CALL(mock, Foo).WillOnce(DuplicateArg<1, unsigned char>(&n)); +``` + +If you want to explicitly specify the value argument types, you can provide +additional template arguments: + +```cpp +ActionName(v1, ..., v_n) +``` + +where `u_i` is the desired type of `v_i`. + +`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the number of +value parameters, but not on the number of template parameters. Without the +restriction, the meaning of the following is unclear: + +```cpp + OverloadedAction(x); +``` + +Are we using a single-template-parameter action where `bool` refers to the type +of `x`, or a two-template-parameter action where the compiler is asked to infer +the type of `x`? + +### Using the ACTION Object's Type + +If you are writing a function that returns an `ACTION` object, you'll need to +know its type. The type depends on the macro used to define the action and the +parameter types. The rule is relatively simple: + + +| Given Definition | Expression | Has Type | +| ----------------------------- | ------------------- | --------------------- | +| `ACTION(Foo)` | `Foo()` | `FooAction` | +| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo()` | `FooAction` | +| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | +| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar(int_value)` | `BarActionP` | +| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz(bool_value, int_value)` | `BazActionP2` | +| ... | ... | ... | + + +Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, +and etc) for actions with different numbers of value parameters, or the action +definitions cannot be overloaded on the number of them. + +### Writing New Monomorphic Actions {#NewMonoActions} + +While the `ACTION*` macros are very convenient, sometimes they are +inappropriate. For example, despite the tricks shown in the previous recipes, +they don't let you directly specify the types of the mock function arguments and +the action parameters, which in general leads to unoptimized compiler error +messages that can baffle unfamiliar users. They also don't allow overloading +actions based on parameter types without jumping through some hoops. + +An alternative to the `ACTION*` macros is to implement +`::testing::ActionInterface`, where `F` is the type of the mock function in +which the action will be used. For example: + +```cpp +template +class ActionInterface { + public: + virtual ~ActionInterface(); + + // Performs the action. Result is the return type of function type + // F, and ArgumentTuple is the tuple of arguments of F. + // + + // For example, if F is int(bool, const string&), then Result would + // be int, and ArgumentTuple would be std::tuple. + virtual Result Perform(const ArgumentTuple& args) = 0; +}; +``` + +```cpp +using ::testing::_; +using ::testing::Action; +using ::testing::ActionInterface; +using ::testing::MakeAction; + +typedef int IncrementMethod(int*); + +class IncrementArgumentAction : public ActionInterface { + public: + int Perform(const std::tuple& args) override { + int* p = std::get<0>(args); // Grabs the first argument. + return *p++; + } +}; + +Action IncrementArgument() { + return MakeAction(new IncrementArgumentAction); +} + +... + EXPECT_CALL(foo, Baz(_)) + .WillOnce(IncrementArgument()); + + int n = 5; + foo.Baz(&n); // Should return 5 and change n to 6. +``` + +### Writing New Polymorphic Actions {#NewPolyActions} + +The previous recipe showed you how to define your own action. This is all good, +except that you need to know the type of the function in which the action will +be used. Sometimes that can be a problem. For example, if you want to use the +action in functions with *different* types (e.g. like `Return()` and +`SetArgPointee()`). + +If an action can be used in several types of mock functions, we say it's +*polymorphic*. The `MakePolymorphicAction()` function template makes it easy to +define such an action: + +```cpp +namespace testing { +template +PolymorphicAction MakePolymorphicAction(const Impl& impl); +} // namespace testing +``` + +As an example, let's define an action that returns the second argument in the +mock function's argument list. The first step is to define an implementation +class: + +```cpp +class ReturnSecondArgumentAction { + public: + template + Result Perform(const ArgumentTuple& args) const { + // To get the i-th (0-based) argument, use std::get(args). + return std::get<1>(args); + } +}; +``` + +This implementation class does *not* need to inherit from any particular class. +What matters is that it must have a `Perform()` method template. This method +template takes the mock function's arguments as a tuple in a **single** +argument, and returns the result of the action. It can be either `const` or not, +but must be invocable with exactly one template argument, which is the result +type. In other words, you must be able to call `Perform(args)` where `R` is +the mock function's return type and `args` is its arguments in a tuple. + +Next, we use `MakePolymorphicAction()` to turn an instance of the implementation +class into the polymorphic action we need. It will be convenient to have a +wrapper for this: + +```cpp +using ::testing::MakePolymorphicAction; +using ::testing::PolymorphicAction; + +PolymorphicAction ReturnSecondArgument() { + return MakePolymorphicAction(ReturnSecondArgumentAction()); +} +``` + +Now, you can use this polymorphic action the same way you use the built-in ones: + +```cpp +using ::testing::_; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, DoThis, (bool flag, int n), (override)); + MOCK_METHOD(string, DoThat, (int x, const char* str1, const char* str2), + (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, DoThis).WillOnce(ReturnSecondArgument()); + EXPECT_CALL(foo, DoThat).WillOnce(ReturnSecondArgument()); + ... + foo.DoThis(true, 5); // Will return 5. + foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". +``` + +### Teaching gMock How to Print Your Values + +When an uninteresting or unexpected call occurs, gMock prints the argument +values and the stack trace to help you debug. Assertion macros like +`EXPECT_THAT` and `EXPECT_EQ` also print the values in question when the +assertion fails. gMock and googletest do this using googletest's user-extensible +value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. +[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values) +explains how to extend the printer to do a better job at printing your +particular type than to dump the bytes. + +## Useful Mocks Created Using gMock + + + + +### Mock std::function {#MockFunction} + +`std::function` is a general function type introduced in C++11. It is a +preferred way of passing callbacks to new interfaces. Functions are copyable, +and are not usually passed around by pointer, which makes them tricky to mock. +But fear not - `MockFunction` can help you with that. + +`MockFunction` has a mock method `Call()` with the signature: + +```cpp + R Call(T1, ..., Tn); +``` + +It also has a `AsStdFunction()` method, which creates a `std::function` proxy +forwarding to Call: + +```cpp + std::function AsStdFunction(); +``` + +To use `MockFunction`, first create `MockFunction` object and set up +expectations on its `Call` method. Then pass proxy obtained from +`AsStdFunction()` to the code you are testing. For example: + +```cpp +TEST(FooTest, RunsCallbackWithBarArgument) { + // 1. Create a mock object. + MockFunction mock_function; + + // 2. Set expectations on Call() method. + EXPECT_CALL(mock_function, Call("bar")).WillOnce(Return(1)); + + // 3. Exercise code that uses std::function. + Foo(mock_function.AsStdFunction()); + // Foo's signature can be either of: + // void Foo(const std::function& fun); + // void Foo(std::function fun); + + // 4. All expectations will be verified when mock_function + // goes out of scope and is destroyed. +} +``` + +Remember that function objects created with `AsStdFunction()` are just +forwarders. If you create multiple of them, they will share the same set of +expectations. + +Although `std::function` supports unlimited number of arguments, `MockFunction` +implementation is limited to ten. If you ever hit that limit... well, your +callback has bigger problems than being mockable. :-) diff --git a/sw/restatdesk_tests/googletest/docs/gmock_faq.md b/sw/restatdesk_tests/googletest/docs/gmock_faq.md new file mode 100644 index 0000000..8f220bf --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/gmock_faq.md @@ -0,0 +1,390 @@ +# Legacy gMock FAQ + +### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? + +In order for a method to be mocked, it must be *virtual*, unless you use the +[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods). + +### Can I mock a variadic function? + +You cannot mock a variadic function (i.e. a function taking ellipsis (`...`) +arguments) directly in gMock. + +The problem is that in general, there is *no way* for a mock object to know how +many arguments are passed to the variadic method, and what the arguments' types +are. Only the *author of the base class* knows the protocol, and we cannot look +into his or her head. + +Therefore, to mock such a function, the *user* must teach the mock object how to +figure out the number of arguments and their types. One way to do it is to +provide overloaded versions of the function. + +Ellipsis arguments are inherited from C and not really a C++ feature. They are +unsafe to use and don't work with arguments that have constructors or +destructors. Therefore we recommend to avoid them in C++ as much as possible. + +### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? + +If you compile this using Microsoft Visual C++ 2005 SP1: + +```cpp +class Foo { + ... + virtual void Bar(const int i) = 0; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(void, Bar, (const int i), (override)); +}; +``` + +You may get the following warning: + +```shell +warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier +``` + +This is a MSVC bug. The same code compiles fine with gcc, for example. If you +use Visual C++ 2008 SP1, you would get the warning: + +```shell +warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers +``` + +In C++, if you *declare* a function with a `const` parameter, the `const` +modifier is ignored. Therefore, the `Foo` base class above is equivalent to: + +```cpp +class Foo { + ... + virtual void Bar(int i) = 0; // int or const int? Makes no difference. +}; +``` + +In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a +`const int` parameter. The compiler will still match them up. + +Since making a parameter `const` is meaningless in the method declaration, we +recommend to remove it in both `Foo` and `MockFoo`. That should workaround the +VC bug. + +Note that we are talking about the *top-level* `const` modifier here. If the +function parameter is passed by pointer or reference, declaring the pointee or +referee as `const` is still meaningful. For example, the following two +declarations are *not* equivalent: + +```cpp +void Bar(int* p); // Neither p nor *p is const. +void Bar(const int* p); // p is not const, but *p is. +``` + +### I can't figure out why gMock thinks my expectations are not satisfied. What should I do? + +You might want to run your test with `--gmock_verbose=info`. This flag lets +gMock print a trace of every mock function call it receives. By studying the +trace, you'll gain insights on why the expectations you set are not met. + +If you see the message "The mock function has no default action set, and its +return type has no default value set.", then try +[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue, +unexpected calls on mocks without default actions don't print out a detailed +comparison between the actual arguments and the expected arguments. + +### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug? + +gMock and `ScopedMockLog` are likely doing the right thing here. + +When a test crashes, the failure signal handler will try to log a lot of +information (the stack trace, and the address map, for example). The messages +are compounded if you have many threads with depth stacks. When `ScopedMockLog` +intercepts these messages and finds that they don't match any expectations, it +prints an error for each of them. + +You can learn to ignore the errors, or you can rewrite your expectations to make +your test more robust, for example, by adding something like: + +```cpp +using ::testing::AnyNumber; +using ::testing::Not; +... + // Ignores any log not done by us. + EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _)) + .Times(AnyNumber()); +``` + +### How can I assert that a function is NEVER called? + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? + +When gMock detects a failure, it prints relevant information (the mock function +arguments, the state of relevant expectations, and etc) to help the user debug. +If another failure is detected, gMock will do the same, including printing the +state of relevant expectations. + +Sometimes an expectation's state didn't change between two failures, and you'll +see the same description of the state twice. They are however *not* redundant, +as they refer to *different points in time*. The fact they are the same *is* +interesting information. + +### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong? + +Does the class (hopefully a pure interface) you are mocking have a virtual +destructor? + +Whenever you derive from a base class, make sure its destructor is virtual. +Otherwise Bad Things will happen. Consider the following code: + +```cpp +class Base { + public: + // Not virtual, but should be. + ~Base() { ... } + ... +}; + +class Derived : public Base { + public: + ... + private: + std::string value_; +}; + +... + Base* p = new Derived; + ... + delete p; // Surprise! ~Base() will be called, but ~Derived() will not + // - value_ is leaked. +``` + +By changing `~Base()` to virtual, `~Derived()` will be correctly called when +`delete p` is executed, and the heap checker will be happy. + +### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that? + +When people complain about this, often they are referring to code like: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. However, I have to write the expectations in the + // reverse order. This sucks big time!!! + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); +``` + +The problem, is that they didn't pick the **best** way to express the test's +intent. + +By default, expectations don't have to be matched in *any* particular order. If +you want them to match in a certain order, you need to be explicit. This is +gMock's (and jMock's) fundamental philosophy: it's easy to accidentally +over-specify your tests, and we want to make it harder to do so. + +There are two better ways to write the test spec. You could either put the +expectations in sequence: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. Using a sequence, we can write the expectations + // in their natural order. + { + InSequence s; + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + } +``` + +or you can put the sequence of actions in the same expectation: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .RetiresOnSaturation(); +``` + +Back to the original questions: why does gMock search the expectations (and +`ON_CALL`s) from back to front? Because this allows a user to set up a mock's +behavior for the common case early (e.g. in the mock's constructor or the test +fixture's set-up phase) and customize it with more specific rules later. If +gMock searches from front to back, this very useful pattern won't be possible. + +### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case? + +When choosing between being neat and being safe, we lean toward the latter. So +the answer is that we think it's better to show the warning. + +Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as +the default behavior rarely changes from test to test. Then in the test body +they set the expectations, which are often different for each test. Having an +`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected. +If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If +we quietly let the call go through without notifying the user, bugs may creep in +unnoticed. + +If, however, you are sure that the calls are OK, you can write + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .WillRepeatedly(...); +``` + +instead of + +```cpp +using ::testing::_; +... + ON_CALL(foo, Bar(_)) + .WillByDefault(...); +``` + +This tells gMock that you do expect the calls and no warning should be printed. + +Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other +values are `info` and `warning`. If you find the output too noisy when +debugging, just choose a less verbose level. + +### How can I delete the mock function's argument in an action? + +If your mock function takes a pointer argument and you want to delete that +argument, you can use testing::DeleteArg() to delete the N'th (zero-indexed) +argument: + +```cpp +using ::testing::_; + ... + MOCK_METHOD(void, Bar, (X* x, const Y& y)); + ... + EXPECT_CALL(mock_foo_, Bar(_, _)) + .WillOnce(testing::DeleteArg<0>())); +``` + +### How can I perform an arbitrary action on a mock function's argument? + +If you find yourself needing to perform some action that's not supported by +gMock directly, remember that you can define your own actions using +[`MakeAction()`](#NewMonoActions) or +[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function +and invoke it using [`Invoke()`](#FunctionsAsActions). + +```cpp +using ::testing::_; +using ::testing::Invoke; + ... + MOCK_METHOD(void, Bar, (X* p)); + ... + EXPECT_CALL(mock_foo_, Bar(_)) + .WillOnce(Invoke(MyAction(...))); +``` + +### My code calls a static/global function. Can I mock it? + +You can, but you need to make some changes. + +In general, if you find yourself needing to mock a static function, it's a sign +that your modules are too tightly coupled (and less flexible, less reusable, +less testable, etc). You are probably better off defining a small interface and +call the function through that interface, which then can be easily mocked. It's +a bit of work initially, but usually pays for itself quickly. + +This Google Testing Blog +[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it +excellently. Check it out. + +### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks! + +I know it's not a question, but you get an answer for free any way. :-) + +With gMock, you can create mocks in C++ easily. And people might be tempted to +use them everywhere. Sometimes they work great, and sometimes you may find them, +well, a pain to use. So, what's wrong in the latter case? + +When you write a test without using mocks, you exercise the code and assert that +it returns the correct value or that the system is in an expected state. This is +sometimes called "state-based testing". + +Mocks are great for what some call "interaction-based" testing: instead of +checking the system state at the very end, mock objects verify that they are +invoked the right way and report an error as soon as it arises, giving you a +handle on the precise context in which the error was triggered. This is often +more effective and economical to do than state-based testing. + +If you are doing state-based testing and using a test double just to simulate +the real object, you are probably better off using a fake. Using a mock in this +case causes pain, as it's not a strong point for mocks to perform complex +actions. If you experience this and think that mocks suck, you are just not +using the right tool for your problem. Or, you might be trying to solve the +wrong problem. :-) + +### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? + +By all means, NO! It's just an FYI. :-) + +What it means is that you have a mock function, you haven't set any expectations +on it (by gMock's rule this means that you are not interested in calls to this +function and therefore it can be called any number of times), and it is called. +That's OK - you didn't say it's not OK to call the function! + +What if you actually meant to disallow this function to be called, but forgot to +write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the +user's fault, gMock tries to be nice and prints you a note. + +So, when you see the message and believe that there shouldn't be any +uninteresting calls, you should investigate what's going on. To make your life +easier, gMock dumps the stack trace when an uninteresting call is encountered. +From that you can figure out which mock function it is, and how it is called. + +### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface? + +Either way is fine - you want to choose the one that's more convenient for your +circumstance. + +Usually, if your action is for a particular function type, defining it using +`Invoke()` should be easier; if your action can be used in functions of +different types (e.g. if you are defining `Return(*value*)`), +`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what +types of functions the action can be used in, and implementing `ActionInterface` +is the way to go here. See the implementation of `Return()` in `gmock-actions.h` +for an example. + +### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean? + +You got this error as gMock has no idea what value it should return when the +mock method is called. `SetArgPointee()` says what the side effect is, but +doesn't say what the return value should be. You need `DoAll()` to chain a +`SetArgPointee()` with a `Return()` that provides a value appropriate to the API +being mocked. + +See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and +an example. + +### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? + +We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6 +times as much memory when compiling a mock class. We suggest to avoid `/clr` +when compiling native C++ mocks. diff --git a/sw/restatdesk_tests/googletest/docs/gmock_for_dummies.md b/sw/restatdesk_tests/googletest/docs/gmock_for_dummies.md new file mode 100644 index 0000000..ed2297c --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/gmock_for_dummies.md @@ -0,0 +1,702 @@ +# gMock for Dummies + +## What Is gMock? + +When you write a prototype or test, often it's not feasible or wise to rely on +real objects entirely. A **mock object** implements the same interface as a real +object (so it can be used as one), but lets you specify at run time how it will +be used and what it should do (which methods will be called? in which order? how +many times? with what arguments? what will they return? etc). + +It is easy to confuse the term *fake objects* with mock objects. Fakes and mocks +actually mean very different things in the Test-Driven Development (TDD) +community: + +* **Fake** objects have working implementations, but usually take some + shortcut (perhaps to make the operations less expensive), which makes them + not suitable for production. An in-memory file system would be an example of + a fake. +* **Mocks** are objects pre-programmed with *expectations*, which form a + specification of the calls they are expected to receive. + +If all this seems too abstract for you, don't worry - the most important thing +to remember is that a mock allows you to check the *interaction* between itself +and code that uses it. The difference between fakes and mocks shall become much +clearer once you start to use mocks. + +**gMock** is a library (sometimes we also call it a "framework" to make it sound +cool) for creating mock classes and using them. It does to C++ what +jMock/EasyMock does to Java (well, more or less). + +When using gMock, + +1. first, you use some simple macros to describe the interface you want to + mock, and they will expand to the implementation of your mock class; +2. next, you create some mock objects and specify its expectations and behavior + using an intuitive syntax; +3. then you exercise code that uses the mock objects. gMock will catch any + violation to the expectations as soon as it arises. + +## Why gMock? + +While mock objects help you remove unnecessary dependencies in tests and make +them fast and reliable, using mocks manually in C++ is *hard*: + +* Someone has to implement the mocks. The job is usually tedious and + error-prone. No wonder people go great distance to avoid it. +* The quality of those manually written mocks is a bit, uh, unpredictable. You + may see some really polished ones, but you may also see some that were + hacked up in a hurry and have all sorts of ad hoc restrictions. +* The knowledge you gained from using one mock doesn't transfer to the next + one. + +In contrast, Java and Python programmers have some fine mock frameworks (jMock, +EasyMock, etc), which automate the creation of mocks. As a result, mocking is a +proven effective technique and widely adopted practice in those communities. +Having the right tool absolutely makes the difference. + +gMock was built to help C++ programmers. It was inspired by jMock and EasyMock, +but designed with C++'s specifics in mind. It is your friend if any of the +following problems is bothering you: + +* You are stuck with a sub-optimal design and wish you had done more + prototyping before it was too late, but prototyping in C++ is by no means + "rapid". +* Your tests are slow as they depend on too many libraries or use expensive + resources (e.g. a database). +* Your tests are brittle as some resources they use are unreliable (e.g. the + network). +* You want to test how your code handles a failure (e.g. a file checksum + error), but it's not easy to cause one. +* You need to make sure that your module interacts with other modules in the + right way, but it's hard to observe the interaction; therefore you resort to + observing the side effects at the end of the action, but it's awkward at + best. +* You want to "mock out" your dependencies, except that they don't have mock + implementations yet; and, frankly, you aren't thrilled by some of those + hand-written mocks. + +We encourage you to use gMock as + +* a *design* tool, for it lets you experiment with your interface design early + and often. More iterations lead to better designs! +* a *testing* tool to cut your tests' outbound dependencies and probe the + interaction between your module and its collaborators. + +## Getting Started + +gMock is bundled with googletest. + +## A Case for Mock Turtles + +Let's look at an example. Suppose you are developing a graphics program that +relies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like +API for drawing. How would you test that it does the right thing? Well, you can +run it and compare the screen with a golden screen snapshot, but let's admit it: +tests like this are expensive to run and fragile (What if you just upgraded to a +shiny new graphics card that has better anti-aliasing? Suddenly you have to +update all your golden images.). It would be too painful if all your tests are +like this. Fortunately, you learned about +[Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing +to do: instead of having your application talk to the system API directly, wrap +the API in an interface (say, `Turtle`) and code to that interface: + +```cpp +class Turtle { + ... + virtual ~Turtle() {} + virtual void PenUp() = 0; + virtual void PenDown() = 0; + virtual void Forward(int distance) = 0; + virtual void Turn(int degrees) = 0; + virtual void GoTo(int x, int y) = 0; + virtual int GetX() const = 0; + virtual int GetY() const = 0; +}; +``` + +(Note that the destructor of `Turtle` **must** be virtual, as is the case for +**all** classes you intend to inherit from - otherwise the destructor of the +derived class will not be called when you delete an object through a base +pointer, and you'll get corrupted program states like memory leaks.) + +You can control whether the turtle's movement will leave a trace using `PenUp()` +and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and +`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the +turtle. + +Your program will normally use a real implementation of this interface. In +tests, you can use a mock implementation instead. This allows you to easily +check what drawing primitives your program is calling, with what arguments, and +in which order. Tests written this way are much more robust (they won't break +because your new machine does anti-aliasing differently), easier to read and +maintain (the intent of a test is expressed in the code, not in some binary +images), and run *much, much faster*. + +## Writing the Mock Class + +If you are lucky, the mocks you need to use have already been implemented by +some nice people. If, however, you find yourself in the position to write a mock +class, relax - gMock turns this task into a fun game! (Well, almost.) + +### How to Define It + +Using the `Turtle` interface as example, here are the simple steps you need to +follow: + +* Derive a class `MockTurtle` from `Turtle`. +* Take a *virtual* function of `Turtle` (while it's possible to + [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods), + it's much more involved). +* In the `public:` section of the child class, write `MOCK_METHOD();` +* Now comes the fun part: you take the function signature, cut-and-paste it + into the macro, and add two commas - one between the return type and the + name, another between the name and the argument list. +* If you're mocking a const method, add a 4th parameter containing `(const)` + (the parentheses are required). +* Since you're overriding a virtual method, we suggest adding the `override` + keyword. For const methods the 4th parameter becomes `(const, override)`, + for non-const methods just `(override)`. This isn't mandatory. +* Repeat until all virtual functions you want to mock are done. (It goes + without saying that *all* pure virtual methods in your abstract class must + be either mocked or overridden.) + +After the process, you should have something like: + +```cpp +#include // Brings in gMock. + +class MockTurtle : public Turtle { + public: + ... + MOCK_METHOD(void, PenUp, (), (override)); + MOCK_METHOD(void, PenDown, (), (override)); + MOCK_METHOD(void, Forward, (int distance), (override)); + MOCK_METHOD(void, Turn, (int degrees), (override)); + MOCK_METHOD(void, GoTo, (int x, int y), (override)); + MOCK_METHOD(int, GetX, (), (const, override)); + MOCK_METHOD(int, GetY, (), (const, override)); +}; +``` + +You don't need to define these mock methods somewhere else - the `MOCK_METHOD` +macro will generate the definitions for you. It's that simple! + +### Where to Put It + +When you define a mock class, you need to decide where to put its definition. +Some people put it in a `_test.cc`. This is fine when the interface being mocked +(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of +`Foo` changes it, your test could break. (You can't really expect `Foo`'s +maintainer to fix every test that uses `Foo`, can you?) + +Generally, you should not mock classes you don't own. If you must mock such a +class owned by others, define the mock class in `Foo`'s Bazel package (usually +the same directory or a `testing` sub-directory), and put it in a `.h` and a +`cc_library` with `testonly=True`. Then everyone can reference them from their +tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and +only tests that depend on the changed methods need to be fixed. + +Another way to do it: you can introduce a thin layer `FooAdaptor` on top of +`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb +changes in `Foo` much more easily. While this is more work initially, carefully +choosing the adaptor interface can make your code easier to write and more +readable (a net win in the long run), as you can choose `FooAdaptor` to fit your +specific domain much better than `Foo` does. + +## Using Mocks in Tests + +Once you have a mock class, using it is easy. The typical work flow is: + +1. Import the gMock names from the `testing` namespace such that you can use + them unqualified (You only have to do it once per file). Remember that + namespaces are a good idea. +2. Create some mock objects. +3. Specify your expectations on them (How many times will a method be called? + With what arguments? What should it do? etc.). +4. Exercise some code that uses the mocks; optionally, check the result using + googletest assertions. If a mock method is called more than expected or with + wrong arguments, you'll get an error immediately. +5. When a mock is destructed, gMock will automatically check whether all + expectations on it have been satisfied. + +Here's an example: + +```cpp +#include "path/to/mock-turtle.h" +#include +#include + +using ::testing::AtLeast; // #1 + +TEST(PainterTest, CanDrawSomething) { + MockTurtle turtle; // #2 + EXPECT_CALL(turtle, PenDown()) // #3 + .Times(AtLeast(1)); + + Painter painter(&turtle); // #4 + + EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5 +} +``` + +As you might have guessed, this test checks that `PenDown()` is called at least +once. If the `painter` object didn't call this method, your test will fail with +a message like this: + +```text +path/to/my_test.cc:119: Failure +Actual function call count doesn't match this expectation: +Actually: never called; +Expected: called at least once. +Stack trace: +... +``` + +**Tip 1:** If you run the test from an Emacs buffer, you can hit `` on +the line number to jump right to the failed expectation. + +**Tip 2:** If your mock objects are never deleted, the final verification won't +happen. Therefore it's a good idea to turn on the heap checker in your tests +when you allocate mocks on the heap. You get that automatically if you use the +`gtest_main` library already. + +###### Expectation Ordering + +**Important note:** gMock requires expectations to be set **before** the mock +functions are called, otherwise the behavior is **undefined**. Do not alternate +between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set +any expectations on a mock after passing the mock to an API. + +This means `EXPECT_CALL()` should be read as expecting that a call will occur +*in the future*, not that a call has occurred. Why does gMock work like that? +Well, specifying the expectation beforehand allows gMock to report a violation +as soon as it rises, when the context (stack trace, etc) is still available. +This makes debugging much easier. + +Admittedly, this test is contrived and doesn't do much. You can easily achieve +the same effect without using gMock. However, as we shall reveal soon, gMock +allows you to do *so much more* with the mocks. + +## Setting Expectations + +The key to using a mock object successfully is to set the *right expectations* +on it. If you set the expectations too strict, your test will fail as the result +of unrelated changes. If you set them too loose, bugs can slip through. You want +to do it just right such that your test can catch exactly the kind of bugs you +intend it to catch. gMock provides the necessary means for you to do it "just +right." + +### General Syntax + +In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock +method. The general syntax is: + +```cpp +EXPECT_CALL(mock_object, method(matchers)) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +The macro has two arguments: first the mock object, and then the method and its +arguments. Note that the two are separated by a comma (`,`), not a period (`.`). +(Why using a comma? The answer is that it was necessary for technical reasons.) +If the method is not overloaded, the macro can also be called without matchers: + +```cpp +EXPECT_CALL(mock_object, non-overloaded-method) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +This syntax allows the test writer to specify "called with any arguments" +without explicitly specifying the number or types of arguments. To avoid +unintended ambiguity, this syntax may only be used for methods that are not +overloaded. + +Either form of the macro can be followed by some optional *clauses* that provide +more information about the expectation. We'll discuss how each clause works in +the coming sections. + +This syntax is designed to make an expectation read like English. For example, +you can probably guess that + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .Times(5) + .WillOnce(Return(100)) + .WillOnce(Return(150)) + .WillRepeatedly(Return(200)); +``` + +says that the `turtle` object's `GetX()` method will be called five times, it +will return 100 the first time, 150 the second time, and then 200 every time. +Some people like to call this style of syntax a Domain-Specific Language (DSL). + +{: .callout .note} +**Note:** Why do we use a macro to do this? Well it serves two purposes: first +it makes expectations easily identifiable (either by `grep` or by a human +reader), and second it allows gMock to include the source file location of a +failed expectation in messages, making debugging easier. + +### Matchers: What Arguments Do We Expect? + +When a mock function takes arguments, we may specify what arguments we are +expecting, for example: + +```cpp +// Expects the turtle to move forward by 100 units. +EXPECT_CALL(turtle, Forward(100)); +``` + +Oftentimes you do not want to be too specific. Remember that talk about tests +being too rigid? Over specification leads to brittle tests and obscures the +intent of tests. Therefore we encourage you to specify only what's necessary—no +more, no less. If you aren't interested in the value of an argument, write `_` +as the argument, which means "anything goes": + +```cpp +using ::testing::_; +... +// Expects that the turtle jumps to somewhere on the x=50 line. +EXPECT_CALL(turtle, GoTo(50, _)); +``` + +`_` is an instance of what we call **matchers**. A matcher is like a predicate +and can test whether an argument is what we'd expect. You can use a matcher +inside `EXPECT_CALL()` wherever a function argument is expected. `_` is a +convenient way of saying "any value". + +In the above examples, `100` and `50` are also matchers; implicitly, they are +the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be +equal (using `operator==`) to the matcher argument. There are many +[built-in matchers](reference/matchers.md) for common types (as well as +[custom matchers](gmock_cook_book.md#NewMatchers)); for example: + +```cpp +using ::testing::Ge; +... +// Expects the turtle moves forward by at least 100. +EXPECT_CALL(turtle, Forward(Ge(100))); +``` + +If you don't care about *any* arguments, rather than specify `_` for each of +them you may instead omit the parameter list: + +```cpp +// Expects the turtle to move forward. +EXPECT_CALL(turtle, Forward); +// Expects the turtle to jump somewhere. +EXPECT_CALL(turtle, GoTo); +``` + +This works for all non-overloaded methods; if a method is overloaded, you need +to help gMock resolve which overload is expected by specifying the number of +arguments and possibly also the +[types of the arguments](gmock_cook_book.md#SelectOverload). + +### Cardinalities: How Many Times Will It Be Called? + +The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We +call its argument a **cardinality** as it tells *how many times* the call should +occur. It allows us to repeat an expectation many times without actually writing +it as many times. More importantly, a cardinality can be "fuzzy", just like a +matcher can be. This allows a user to express the intent of a test exactly. + +An interesting special case is when we say `Times(0)`. You may have guessed - it +means that the function shouldn't be called with the given arguments at all, and +gMock will report a googletest failure whenever the function is (wrongfully) +called. + +We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the +list of built-in cardinalities you can use, see +[here](gmock_cheat_sheet.md#CardinalityList). + +The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer +the cardinality for you.** The rules are easy to remember: + +* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the + `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. +* If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >= + 1, the cardinality is `Times(n)`. +* If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >= + 0, the cardinality is `Times(AtLeast(n))`. + +**Quick quiz:** what do you think will happen if a function is expected to be +called twice but actually called four times? + +### Actions: What Should It Do? + +Remember that a mock object doesn't really have a working implementation? We as +users have to tell it what to do when a method is invoked. This is easy in +gMock. + +First, if the return type of a mock function is a built-in type or a pointer, +the function has a **default action** (a `void` function will just return, a +`bool` function will return `false`, and other functions will return 0). In +addition, in C++ 11 and above, a mock function whose return type is +default-constructible (i.e. has a default constructor) has a default action of +returning a default-constructed value. If you don't say anything, this behavior +will be used. + +Second, if a mock function doesn't have a default action, or the default action +doesn't suit you, you can specify the action to be taken each time the +expectation matches using a series of `WillOnce()` clauses followed by an +optional `WillRepeatedly()`. For example, + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillOnce(Return(300)); +``` + +says that `turtle.GetX()` will be called *exactly three times* (gMock inferred +this from how many `WillOnce()` clauses we've written, since we didn't +explicitly write `Times()`), and will return 100, 200, and 300 respectively. + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillRepeatedly(Return(300)); +``` + +says that `turtle.GetY()` will be called *at least twice* (gMock knows this as +we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no +explicit `Times()`), will return 100 and 200 respectively the first two times, +and 300 from the third time on. + +Of course, if you explicitly write a `Times()`, gMock will not try to infer the +cardinality itself. What if the number you specified is larger than there are +`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do +the *default* action for the function every time (unless, of course, you have a +`WillRepeatedly()`.). + +What can we do inside `WillOnce()` besides `Return()`? You can return a +reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function, +among [others](gmock_cook_book.md#using-actions). + +**Important note:** The `EXPECT_CALL()` statement evaluates the action clause +only once, even though the action may be performed many times. Therefore you +must be careful about side effects. The following may not do what you want: + +```cpp +using ::testing::Return; +... +int n = 100; +EXPECT_CALL(turtle, GetX()) + .Times(4) + .WillRepeatedly(Return(n++)); +``` + +Instead of returning 100, 101, 102, ..., consecutively, this mock function will +always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` +will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will +return the same pointer every time. If you want the side effect to happen every +time, you need to define a custom action, which we'll teach in the +[cook book](gmock_cook_book.md). + +Time for another quiz! What do you think the following means? + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .Times(4) + .WillOnce(Return(100)); +``` + +Obviously `turtle.GetY()` is expected to be called four times. But if you think +it will return 100 every time, think twice! Remember that one `WillOnce()` +clause will be consumed each time the function is invoked and the default action +will be taken afterwards. So the right answer is that `turtle.GetY()` will +return 100 the first time, but **return 0 from the second time on**, as +returning 0 is the default action for `int` functions. + +### Using Multiple Expectations {#MultiExpectations} + +So far we've only shown examples where you have a single expectation. More +realistically, you'll specify expectations on multiple mock methods which may be +from multiple mock objects. + +By default, when a mock method is invoked, gMock will search the expectations in +the **reverse order** they are defined, and stop when an active expectation that +matches the arguments is found (you can think of it as "newer rules override +older ones."). If the matching expectation cannot take any more calls, you will +get an upper-bound-violated failure. Here's an example: + +```cpp +using ::testing::_; +... +EXPECT_CALL(turtle, Forward(_)); // #1 +EXPECT_CALL(turtle, Forward(10)) // #2 + .Times(2); +``` + +If `Forward(10)` is called three times in a row, the third time it will be an +error, as the last matching expectation (#2) has been saturated. If, however, +the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, +as now #1 will be the matching expectation. + +{: .callout .note} +**Note:** Why does gMock search for a match in the *reverse* order of the +expectations? The reason is that this allows a user to set up the default +expectations in a mock object's constructor or the test fixture's set-up phase +and then customize the mock by writing more specific expectations in the test +body. So, if you have two expectations on the same method, you want to put the +one with more specific matchers **after** the other, or the more specific rule +would be shadowed by the more general one that comes after it. + +{: .callout .tip} +**Tip:** It is very common to start with a catch-all expectation for a method +and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if +overloaded). This makes any calls to the method expected. This is not necessary +for methods that are not mentioned at all (these are "uninteresting"), but is +useful for methods that have some expectations, but for which other calls are +ok. See +[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected). + +### Ordered vs Unordered Calls {#OrderedCalls} + +By default, an expectation can match a call even though an earlier expectation +hasn't been satisfied. In other words, the calls don't have to occur in the +order the expectations are specified. + +Sometimes, you may want all the expected calls to occur in a strict order. To +say this in gMock is easy: + +```cpp +using ::testing::InSequence; +... +TEST(FooTest, DrawsLineSegment) { + ... + { + InSequence seq; + + EXPECT_CALL(turtle, PenDown()); + EXPECT_CALL(turtle, Forward(100)); + EXPECT_CALL(turtle, PenUp()); + } + Foo(); +} +``` + +By creating an object of type `InSequence`, all expectations in its scope are +put into a *sequence* and have to occur *sequentially*. Since we are just +relying on the constructor and destructor of this object to do the actual work, +its name is really irrelevant. + +In this example, we test that `Foo()` calls the three expected functions in the +order as written. If a call is made out-of-order, it will be an error. + +(What if you care about the relative order of some of the calls, but not all of +them? Can you specify an arbitrary partial order? The answer is ... yes! The +details can be found [here](gmock_cook_book.md#OrderedCalls).) + +### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations} + +Now let's do a quick quiz to see how well you can use this mock stuff already. +How would you test that the turtle is asked to go to the origin *exactly twice* +(you want to ignore any other instructions it receives)? + +After you've come up with your answer, take a look at ours and compare notes +(solve it yourself first - don't cheat!): + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(turtle, GoTo(_, _)) // #1 + .Times(AnyNumber()); +EXPECT_CALL(turtle, GoTo(0, 0)) // #2 + .Times(2); +``` + +Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will +see that the arguments match expectation #2 (remember that we always pick the +last matching expectation). Now, since we said that there should be only two +such calls, gMock will report an error immediately. This is basically what we've +told you in the [Using Multiple Expectations](#MultiExpectations) section above. + +This example shows that **expectations in gMock are "sticky" by default**, in +the sense that they remain active even after we have reached their invocation +upper bounds. This is an important rule to remember, as it affects the meaning +of the spec, and is **different** to how it's done in many other mocking +frameworks (Why'd we do that? Because we think our rule makes the common cases +easier to express and understand.). + +Simple? Let's see if you've really understood it: what does the following code +say? + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)); +} +``` + +If you think it says that `turtle.GetX()` will be called `n` times and will +return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we +said, expectations are sticky. So, the second time `turtle.GetX()` is called, +the last (latest) `EXPECT_CALL()` statement will match, and will immediately +lead to an "upper bound violated" error - this piece of code is not very useful! + +One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is +to explicitly say that the expectations are *not* sticky. In other words, they +should *retire* as soon as they are saturated: + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); +} +``` + +And, there's a better way to do it: in this case, we expect the calls to occur +in a specific order, and we line up the actions to match the order. Since the +order is important here, we should make it explicit using a sequence: + +```cpp +using ::testing::InSequence; +using ::testing::Return; +... +{ + InSequence s; + + for (int i = 1; i <= n; i++) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); + } +} +``` + +By the way, the other situation where an expectation may *not* be sticky is when +it's in a sequence - as soon as another expectation that comes after it in the +sequence has been used, it automatically retires (and will never be used to +match any call). + +### Uninteresting Calls + +A mock object may have many methods, and not all of them are that interesting. +For example, in some tests we may not care about how many times `GetX()` and +`GetY()` get called. + +In gMock, if you are not interested in a method, just don't say anything about +it. If a call to this method occurs, you'll see a warning in the test output, +but it won't be a failure. This is called "naggy" behavior; to change, see +[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy). diff --git a/sw/restatdesk_tests/googletest/docs/index.md b/sw/restatdesk_tests/googletest/docs/index.md new file mode 100644 index 0000000..b162c74 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/index.md @@ -0,0 +1,22 @@ +# GoogleTest User's Guide + +## Welcome to GoogleTest! + +GoogleTest is Google's C++ testing and mocking framework. This user's guide has +the following contents: + +* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using + GoogleTest. Read this first if you are new to GoogleTest. +* [GoogleTest Advanced](advanced.md) - Read this when you've finished the + Primer and want to utilize GoogleTest to its full potential. +* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples. +* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here + first. +* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock + objects and use them in tests. +* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to + common mocking use cases. +* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for + matchers, actions, invariants, and more. +* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific + questions. diff --git a/sw/restatdesk_tests/googletest/docs/pkgconfig.md b/sw/restatdesk_tests/googletest/docs/pkgconfig.md new file mode 100644 index 0000000..bf05d59 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/pkgconfig.md @@ -0,0 +1,144 @@ +## Using GoogleTest from various build systems + +GoogleTest comes with pkg-config files that can be used to determine all +necessary flags for compiling and linking to GoogleTest (and GoogleMock). +Pkg-config is a standardised plain-text format containing + +* the includedir (-I) path +* necessary macro (-D) definitions +* further required flags (-pthread) +* the library (-L) path +* the library (-l) to link to + +All current build systems support pkg-config in one way or another. For all +examples here we assume you want to compile the sample +`samples/sample3_unittest.cc`. + +### CMake + +Using `pkg-config` in CMake is fairly easy: + +```cmake +find_package(PkgConfig) +pkg_search_module(GTEST REQUIRED gtest_main) + +add_executable(testapp) +target_sources(testapp PRIVATE samples/sample3_unittest.cc) +target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS}) +target_compile_options(testapp PRIVATE ${GTEST_CFLAGS}) + +enable_testing() +add_test(first_and_only_test testapp) +``` + +It is generally recommended that you use `target_compile_options` + `_CFLAGS` +over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not +just -I flags (GoogleTest might require a macro indicating to internal headers +that all libraries have been compiled with threading enabled. In addition, +GoogleTest might also require `-pthread` in the compiling step, and as such +splitting the pkg-config `Cflags` variable into include dirs and macros for +`target_compile_definitions()` might still miss this). The same recommendation +goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens +to discard `-L` flags and `-pthread`. + +### Help! pkg-config can't find GoogleTest! + +Let's say you have a `CMakeLists.txt` along the lines of the one in this +tutorial and you try to run `cmake`. It is very possible that you get a failure +along the lines of: + +``` +-- Checking for one of the modules 'gtest_main' +CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message): + None of the required 'gtest_main' found +``` + +These failures are common if you installed GoogleTest yourself and have not +sourced it from a distro or other package manager. If so, you need to tell +pkg-config where it can find the `.pc` files containing the information. Say you +installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are +installed under `/usr/local/lib64/pkgconfig`. If you set + +``` +export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig +``` + +pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. + +### Using pkg-config in a cross-compilation setting + +Pkg-config can be used in a cross-compilation setting too. To do this, let's +assume the final prefix of the cross-compiled installation will be `/usr`, and +your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using + +``` +mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. +``` + +Install into the sysroot using `DESTDIR`: + +``` +make -j install DESTDIR=/home/MYUSER/sysroot +``` + +Before we continue, it is recommended to **always** define the following two +variables for pkg-config in a cross-compilation setting: + +``` +export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes +export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes +``` + +otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes +such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for +reasons why this stripping needs to occur usually). + +If you look at the generated pkg-config file, it will look something like + +``` +libdir=/usr/lib64 +includedir=/usr/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.11.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest -lpthread +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread +``` + +Notice that the sysroot is not included in `libdir` and `includedir`! If you try +to run `pkg-config` with the correct +`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc` +file, you will get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include +$ pkg-config --libs gtest +-L/usr/lib64 -lgtest -lpthread +``` + +which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In +order to use this in a cross-compilation setting, we need to tell pkg-config to +inject the actual sysroot into `-I` and `-L` variables. Let us now tell +pkg-config about the actual sysroot + +``` +export PKG_CONFIG_DIR= +export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot +export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig +``` + +and running `pkg-config` again we get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include +$ pkg-config --libs gtest +-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread +``` + +which contains the correct sysroot now. For a more comprehensive guide to also +including `${CHOST}` in build system calls, see the excellent tutorial by Diego +Elio Pettenò: diff --git a/sw/restatdesk_tests/googletest/docs/platforms.md b/sw/restatdesk_tests/googletest/docs/platforms.md new file mode 100644 index 0000000..d35a7be --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/platforms.md @@ -0,0 +1,8 @@ +# Supported Platforms + +GoogleTest follows Google's +[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). +See +[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) +for a list of currently supported versions compilers, platforms, and build +tools. diff --git a/sw/restatdesk_tests/googletest/docs/primer.md b/sw/restatdesk_tests/googletest/docs/primer.md new file mode 100644 index 0000000..69d6c6d --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/primer.md @@ -0,0 +1,482 @@ +# GoogleTest Primer + +## Introduction: Why GoogleTest? + +*GoogleTest* helps you write better C++ tests. + +GoogleTest is a testing framework developed by the Testing Technology team with +Google's specific requirements and constraints in mind. Whether you work on +Linux, Windows, or a Mac, if you write C++ code, GoogleTest can help you. And it +supports *any* kind of tests, not just unit tests. + +So what makes a good test, and how does GoogleTest fit in? We believe: + +1. Tests should be *independent* and *repeatable*. It's a pain to debug a test + that succeeds or fails as a result of other tests. GoogleTest isolates the + tests by running each of them on a different object. When a test fails, + GoogleTest allows you to run it in isolation for quick debugging. +2. Tests should be well *organized* and reflect the structure of the tested + code. GoogleTest groups related tests into test suites that can share data + and subroutines. This common pattern is easy to recognize and makes tests + easy to maintain. Such consistency is especially helpful when people switch + projects and start to work on a new code base. +3. Tests should be *portable* and *reusable*. Google has a lot of code that is + platform-neutral; its tests should also be platform-neutral. GoogleTest + works on different OSes, with different compilers, with or without + exceptions, so GoogleTest tests can work with a variety of configurations. +4. When tests fail, they should provide as much *information* about the problem + as possible. GoogleTest doesn't stop at the first test failure. Instead, it + only stops the current test and continues with the next. You can also set up + tests that report non-fatal failures after which the current test continues. + Thus, you can detect and fix multiple bugs in a single run-edit-compile + cycle. +5. The testing framework should liberate test writers from housekeeping chores + and let them focus on the test *content*. GoogleTest automatically keeps + track of all tests defined, and doesn't require the user to enumerate them + in order to run them. +6. Tests should be *fast*. With GoogleTest, you can reuse shared resources + across tests and pay for the set-up/tear-down only once, without making + tests depend on each other. + +Since GoogleTest is based on the popular xUnit architecture, you'll feel right +at home if you've used JUnit or PyUnit before. If not, it will take you about 10 +minutes to learn the basics and get started. So let's go! + +## Beware of the Nomenclature + +{: .callout .note} +*Note:* There might be some confusion arising from different definitions of the +terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these. + +Historically, GoogleTest started to use the term *Test Case* for grouping +related tests, whereas current publications, including International Software +Testing Qualifications Board ([ISTQB](https://www.istqb.org/)) materials and +various textbooks on software quality, use the term +*[Test Suite][istqb test suite]* for this. + +The related term *Test*, as it is used in GoogleTest, corresponds to the term +*[Test Case][istqb test case]* of ISTQB and others. + +The term *Test* is commonly of broad enough sense, including ISTQB's definition +of *Test Case*, so it's not much of a problem here. But the term *Test Case* as +was used in Google Test is of contradictory sense and thus confusing. + +GoogleTest recently started replacing the term *Test Case* with *Test Suite*. +The preferred API is *TestSuite*. The older TestCase API is being slowly +deprecated and refactored away. + +So please be aware of the different definitions of the terms: + + +Meaning | GoogleTest Term | [ISTQB](https://www.istqb.org/) Term +:----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------- +Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case] + + +[istqb test case]: https://glossary.istqb.org/en_US/term/test-case +[istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite + +## Basic Concepts + +When using GoogleTest, you start by writing *assertions*, which are statements +that check whether a condition is true. An assertion's result can be *success*, +*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the +current function; otherwise the program continues normally. + +*Tests* use assertions to verify the tested code's behavior. If a test crashes +or has a failed assertion, then it *fails*; otherwise it *succeeds*. + +A *test suite* contains one or many tests. You should group your tests into test +suites that reflect the structure of the tested code. When multiple tests in a +test suite need to share common objects and subroutines, you can put them into a +*test fixture* class. + +A *test program* can contain multiple test suites. + +We'll now explain how to write a test program, starting at the individual +assertion level and building up to tests and test suites. + +## Assertions + +GoogleTest assertions are macros that resemble function calls. You test a class +or function by making assertions about its behavior. When an assertion fails, +GoogleTest prints the assertion's source file and line number location, along +with a failure message. You may also supply a custom failure message which will +be appended to GoogleTest's message. + +The assertions come in pairs that test the same thing but have different effects +on the current function. `ASSERT_*` versions generate fatal failures when they +fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal +failures, which don't abort the current function. Usually `EXPECT_*` are +preferred, as they allow more than one failure to be reported in a test. +However, you should use `ASSERT_*` if it doesn't make sense to continue when the +assertion in question fails. + +Since a failed `ASSERT_*` returns from the current function immediately, +possibly skipping clean-up code that comes after it, it may cause a space leak. +Depending on the nature of the leak, it may or may not be worth fixing - so keep +this in mind if you get a heap checker error in addition to assertion errors. + +To provide a custom failure message, simply stream it into the macro using the +`<<` operator or a sequence of such operators. See the following example, using +the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to +verify value equality: + +```c++ +ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; + +for (int i = 0; i < x.size(); ++i) { + EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; +} +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro--in particular, C strings and `string` objects. If a wide string +(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is +streamed to an assertion, it will be translated to UTF-8 when printed. + +GoogleTest provides a collection of assertions for verifying the behavior of +your code in various ways. You can check Boolean conditions, compare values +based on relational operators, verify string values, floating-point values, and +much more. There are even assertions that enable you to verify more complex +states by providing custom predicates. For the complete list of assertions +provided by GoogleTest, see the [Assertions Reference](reference/assertions.md). + +## Simple Tests + +To create a test: + +1. Use the `TEST()` macro to define and name a test function. These are + ordinary C++ functions that don't return a value. +2. In this function, along with any valid C++ statements you want to include, + use the various GoogleTest assertions to check values. +3. The test's result is determined by the assertions; if any assertion in the + test fails (either fatally or non-fatally), or if the test crashes, the + entire test fails. Otherwise, it succeeds. + +```c++ +TEST(TestSuiteName, TestName) { + ... test body ... +} +``` + +`TEST()` arguments go from general to specific. The *first* argument is the name +of the test suite, and the *second* argument is the test's name within the test +suite. Both names must be valid C++ identifiers, and they should not contain any +underscores (`_`). A test's *full name* consists of its containing test suite +and its individual name. Tests from different test suites can have the same +individual name. + +For example, let's take a simple integer function: + +```c++ +int Factorial(int n); // Returns the factorial of n +``` + +A test suite for this function might look like: + +```c++ +// Tests factorial of 0. +TEST(FactorialTest, HandlesZeroInput) { + EXPECT_EQ(Factorial(0), 1); +} + +// Tests factorial of positive numbers. +TEST(FactorialTest, HandlesPositiveInput) { + EXPECT_EQ(Factorial(1), 1); + EXPECT_EQ(Factorial(2), 2); + EXPECT_EQ(Factorial(3), 6); + EXPECT_EQ(Factorial(8), 40320); +} +``` + +GoogleTest groups the test results by test suites, so logically related tests +should be in the same test suite; in other words, the first argument to their +`TEST()` should be the same. In the above example, we have two tests, +`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test +suite `FactorialTest`. + +When naming your test suites and tests, you should follow the same convention as +for +[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names). + +**Availability**: Linux, Windows, Mac. + +## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests} + +If you find yourself writing two or more tests that operate on similar data, you +can use a *test fixture*. This allows you to reuse the same configuration of +objects for several different tests. + +To create a fixture: + +1. Derive a class from `testing::Test` . Start its body with `protected:`, as + we'll want to access fixture members from sub-classes. +2. Inside the class, declare any objects you plan to use. +3. If necessary, write a default constructor or `SetUp()` function to prepare + the objects for each test. A common mistake is to spell `SetUp()` as + **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you + spelled it correctly. +4. If necessary, write a destructor or `TearDown()` function to release any + resources you allocated in `SetUp()` . To learn when you should use the + constructor/destructor and when you should use `SetUp()/TearDown()`, read + the [FAQ](faq.md#CtorVsSetUp). +5. If needed, define subroutines for your tests to share. + +When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to +access objects and subroutines in the test fixture: + +```c++ +TEST_F(TestFixtureClassName, TestName) { + ... test body ... +} +``` + +Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test +fixture class. (`_F` stands for "Fixture"). No test suite name is specified for +this macro. + +Unfortunately, the C++ macro system does not allow us to create a single macro +that can handle both types of tests. Using the wrong macro causes a compiler +error. + +Also, you must first define a test fixture class before using it in a +`TEST_F()`, or you'll get the compiler error "`virtual outside class +declaration`". + +For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test +fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean +up by calling `TearDown()`, and then delete the test fixture. Note that +different tests in the same test suite have different test fixture objects, and +GoogleTest always deletes a test fixture before it creates the next one. +GoogleTest does **not** reuse the same test fixture for multiple tests. Any +changes one test makes to the fixture do not affect other tests. + +As an example, let's write tests for a FIFO queue class named `Queue`, which has +the following interface: + +```c++ +template // E is the element type. +class Queue { + public: + Queue(); + void Enqueue(const E& element); + E* Dequeue(); // Returns NULL if the queue is empty. + size_t size() const; + ... +}; +``` + +First, define a fixture class. By convention, you should give it the name +`FooTest` where `Foo` is the class being tested. + +```c++ +class QueueTest : public testing::Test { + protected: + QueueTest() { + // q0_ remains empty + q1_.Enqueue(1); + q2_.Enqueue(2); + q2_.Enqueue(3); + } + + // ~QueueTest() override = default; + + Queue q0_; + Queue q1_; + Queue q2_; +}; +``` + +In this case, we don't need to define a destructor or a `TearDown()` method, +because the implicit destructor generated by the compiler will perform all of +the necessary cleanup. + +Now we'll write tests using `TEST_F()` and this fixture. + +```c++ +TEST_F(QueueTest, IsEmptyInitially) { + EXPECT_EQ(q0_.size(), 0); +} + +TEST_F(QueueTest, DequeueWorks) { + int* n = q0_.Dequeue(); + EXPECT_EQ(n, nullptr); + + n = q1_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 1); + EXPECT_EQ(q1_.size(), 0); + delete n; + + n = q2_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 2); + EXPECT_EQ(q2_.size(), 1); + delete n; +} +``` + +The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is +to use `EXPECT_*` when you want the test to continue to reveal more errors after +the assertion failure, and use `ASSERT_*` when continuing after failure doesn't +make sense. For example, the second assertion in the `Dequeue` test is +`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which +would lead to a segfault when `n` is `NULL`. + +When these tests run, the following happens: + +1. GoogleTest constructs a `QueueTest` object (let's call it `t1`). +2. The first test (`IsEmptyInitially`) runs on `t1`. +3. `t1` is destructed. +4. The above steps are repeated on another `QueueTest` object, this time + running the `DequeueWorks` test. + +**Availability**: Linux, Windows, Mac. + +## Invoking the Tests + +`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So, +unlike with many other C++ testing frameworks, you don't have to re-list all +your defined tests in order to run them. + +After defining your tests, you can run them with `RUN_ALL_TESTS()`, which +returns `0` if all the tests are successful, or `1` otherwise. Note that +`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different +test suites, or even different source files. + +When invoked, the `RUN_ALL_TESTS()` macro: + +* Saves the state of all GoogleTest flags. + +* Creates a test fixture object for the first test. + +* Initializes it via `SetUp()`. + +* Runs the test on the fixture object. + +* Cleans up the fixture via `TearDown()`. + +* Deletes the fixture. + +* Restores the state of all GoogleTest flags. + +* Repeats the above steps for the next test, until all tests have run. + +If a fatal failure happens the subsequent steps will be skipped. + +{: .callout .important} +> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or +> you will get a compiler error. The rationale for this design is that the +> automated testing service determines whether a test has passed based on its +> exit code, not on its stdout/stderr output; thus your `main()` function must +> return the value of `RUN_ALL_TESTS()`. +> +> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than +> once conflicts with some advanced GoogleTest features (e.g., thread-safe +> [death tests](advanced.md#death-tests)) and thus is not supported. + +**Availability**: Linux, Windows, Mac. + +## Writing the main() Function + +Most users should *not* need to write their own `main` function and instead link +with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry +point. See the end of this section for details. The remainder of this section +should only apply when you need to do something custom before the tests run that +cannot be expressed within the framework of fixtures and test suites. + +If you write your own `main` function, it should return the value of +`RUN_ALL_TESTS()`. + +You can start from this boilerplate: + +```c++ +#include "this/package/foo.h" + +#include + +namespace my { +namespace project { +namespace { + +// The fixture for testing class Foo. +class FooTest : public testing::Test { + protected: + // You can remove any or all of the following functions if their bodies would + // be empty. + + FooTest() { + // You can do set-up work for each test here. + } + + ~FooTest() override { + // You can do clean-up work that doesn't throw exceptions here. + } + + // If the constructor and destructor are not enough for setting up + // and cleaning up each test, you can define the following methods: + + void SetUp() override { + // Code here will be called immediately after the constructor (right + // before each test). + } + + void TearDown() override { + // Code here will be called immediately after each test (right + // before the destructor). + } + + // Class members declared here can be used by all tests in the test suite + // for Foo. +}; + +// Tests that the Foo::Bar() method does Abc. +TEST_F(FooTest, MethodBarDoesAbc) { + const std::string input_filepath = "this/package/testdata/myinputfile.dat"; + const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; + Foo f; + EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); +} + +// Tests that Foo does Xyz. +TEST_F(FooTest, DoesXyz) { + // Exercises the Xyz feature of Foo. +} + +} // namespace +} // namespace project +} // namespace my + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +``` + +The `testing::InitGoogleTest()` function parses the command line for GoogleTest +flags, and removes all recognized flags. This allows the user to control a test +program's behavior via various flags, which we'll cover in the +[AdvancedGuide](advanced.md). You **must** call this function before calling +`RUN_ALL_TESTS()`, or the flags won't be properly initialized. + +On Windows, `InitGoogleTest()` also works with wide strings, so it can be used +in programs compiled in `UNICODE` mode as well. + +But maybe you think that writing all those `main` functions is too much work? We +agree with you completely, and that's why Google Test provides a basic +implementation of main(). If it fits your needs, then just link your test with +the `gtest_main` library and you are good to go. + +{: .callout .note} +NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. + +## Known Limitations + +* Google Test is designed to be thread-safe. The implementation is thread-safe + on systems where the `pthreads` library is available. It is currently + *unsafe* to use Google Test assertions from two threads concurrently on + other systems (e.g. Windows). In most tests this is not an issue as usually + the assertions are done in the main thread. If you want to help, you can + volunteer to implement the necessary synchronization primitives in + `gtest-port.h` for your platform. diff --git a/sw/restatdesk_tests/googletest/docs/quickstart-bazel.md b/sw/restatdesk_tests/googletest/docs/quickstart-bazel.md new file mode 100644 index 0000000..5750f02 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/quickstart-bazel.md @@ -0,0 +1,146 @@ +# Quickstart: Building with Bazel + +This tutorial aims to get you up and running with GoogleTest using the Bazel +build system. If you're using GoogleTest for the first time or need a refresher, +we recommend this tutorial as a starting point. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [Bazel](https://bazel.build/) 7.0 or higher, the preferred build system used + by the GoogleTest team. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have Bazel installed, see the +[Bazel installation guide](https://bazel.build/install). + +{: .callout .note} Note: The terminal commands in this tutorial show a Unix +shell prompt, but the commands work on the Windows command line as well. + +## Set up a Bazel workspace + +A +[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace) +is a directory on your filesystem that you use to manage source files for the +software you want to build. Each workspace directory has a text file named +`MODULE.bazel` which may be empty, or may contain references to external +dependencies required to build the outputs. + +First, create a directory for your workspace: + +``` +$ mkdir my_workspace && cd my_workspace +``` + +Next, you’ll create the `MODULE.bazel` file to specify dependencies. As of Bazel +7.0, the recommended way to consume GoogleTest is through the +[Bazel Central Registry](https://registry.bazel.build/modules/googletest). To do +this, create a `MODULE.bazel` file in the root directory of your Bazel workspace +with the following content: + +``` +# MODULE.bazel + +# Choose the most recent version available at +# https://registry.bazel.build/modules/googletest +bazel_dep(name = "googletest", version = "1.15.2") +``` + +Now you're ready to build C++ code that uses GoogleTest. + +## Create and run a binary + +With your Bazel workspace set up, you can now use GoogleTest code within your +own project. + +As an example, create a file named `hello_test.cc` in your `my_workspace` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, create a file named `BUILD` in the same directory with the +following contents: + +``` +cc_test( + name = "hello_test", + size = "small", + srcs = ["hello_test.cc"], + deps = [ + "@googletest//:gtest", + "@googletest//:gtest_main", + ], +) +``` + +This `cc_test` rule declares the C++ test binary you want to build, and links to +the GoogleTest library (`@googletest//:gtest"`) and the GoogleTest `main()` +function (`@googletest//:gtest_main`). For more information about Bazel `BUILD` +files, see the +[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html). + +{: .callout .note} +NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++14` +to ensure that GoogleTest is compiled as C++14 instead of the compiler's default +setting (which could be C++11). For MSVC, the equivalent would be +`--cxxopt=/std:c++14`. See [Supported Platforms](platforms.md) for more details +on supported language versions. + +Now you can build and run your test: + +
+$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test
+INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
+INFO: Found 1 test target...
+INFO: From Testing //:hello_test:
+==================== Test output for //:hello_test:
+Running main() from gmock_main.cc
+[==========] Running 1 test from 1 test suite.
+[----------] Global test environment set-up.
+[----------] 1 test from HelloTest
+[ RUN      ] HelloTest.BasicAssertions
+[       OK ] HelloTest.BasicAssertions (0 ms)
+[----------] 1 test from HelloTest (0 ms total)
+
+[----------] Global test environment tear-down
+[==========] 1 test from 1 test suite ran. (0 ms total)
+[  PASSED  ] 1 test.
+================================================================================
+Target //:hello_test up-to-date:
+  bazel-bin/hello_test
+INFO: Elapsed time: 4.190s, Critical Path: 3.05s
+INFO: 27 processes: 8 internal, 19 linux-sandbox.
+INFO: Build completed successfully, 27 total actions
+//:hello_test                                                     PASSED in 0.1s
+
+INFO: Build completed successfully, 27 total actions
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/sw/restatdesk_tests/googletest/docs/quickstart-cmake.md b/sw/restatdesk_tests/googletest/docs/quickstart-cmake.md new file mode 100644 index 0000000..4e422b7 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/quickstart-cmake.md @@ -0,0 +1,157 @@ +# Quickstart: Building with CMake + +This tutorial aims to get you up and running with GoogleTest using CMake. If +you're using GoogleTest for the first time or need a refresher, we recommend +this tutorial as a starting point. If your project uses Bazel, see the +[Quickstart for Bazel](quickstart-bazel.md) instead. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [CMake](https://cmake.org/) and a compatible build tool for building the + project. + * Compatible build tools include + [Make](https://www.gnu.org/software/make/), + [Ninja](https://ninja-build.org/), and others - see + [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html) + for more information. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have CMake installed, see the +[CMake installation guide](https://cmake.org/install). + +{: .callout .note} +Note: The terminal commands in this tutorial show a Unix shell prompt, but the +commands work on the Windows command line as well. + +## Set up a project + +CMake uses a file named `CMakeLists.txt` to configure the build system for a +project. You'll use this file to set up your project and declare a dependency on +GoogleTest. + +First, create a directory for your project: + +``` +$ mkdir my_project && cd my_project +``` + +Next, you'll create the `CMakeLists.txt` file and declare a dependency on +GoogleTest. There are many ways to express dependencies in the CMake ecosystem; +in this quickstart, you'll use the +[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html). +To do this, in your project directory (`my_project`), create a file named +`CMakeLists.txt` with the following contents: + +```cmake +cmake_minimum_required(VERSION 3.14) +project(my_project) + +# GoogleTest requires at least C++14 +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is +the Git commit hash of the GoogleTest version to use; we recommend updating the +hash often to point to the latest version. + +For more information about how to create `CMakeLists.txt` files, see the +[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html). + +## Create and run a binary + +With GoogleTest declared as a dependency, you can use GoogleTest code within +your own project. + +As an example, create a file named `hello_test.cc` in your `my_project` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, add the following to the end of your `CMakeLists.txt` file: + +```cmake +enable_testing() + +add_executable( + hello_test + hello_test.cc +) +target_link_libraries( + hello_test + GTest::gtest_main +) + +include(GoogleTest) +gtest_discover_tests(hello_test) +``` + +The above configuration enables testing in CMake, declares the C++ test binary +you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The +last two lines enable CMake's test runner to discover the tests included in the +binary, using the +[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html). + +Now you can build and run your test: + +
+my_project$ cmake -S . -B build
+-- The C compiler identification is GNU 10.2.1
+-- The CXX compiler identification is GNU 10.2.1
+...
+-- Build files have been written to: .../my_project/build
+
+my_project$ cmake --build build
+Scanning dependencies of target gtest
+...
+[100%] Built target gmock_main
+
+my_project$ cd build && ctest
+Test project .../my_project/build
+    Start 1: HelloTest.BasicAssertions
+1/1 Test #1: HelloTest.BasicAssertions ........   Passed    0.00 sec
+
+100% tests passed, 0 tests failed out of 1
+
+Total Test time (real) =   0.01 sec
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/sw/restatdesk_tests/googletest/docs/reference/actions.md b/sw/restatdesk_tests/googletest/docs/reference/actions.md new file mode 100644 index 0000000..0ebdc1e --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/reference/actions.md @@ -0,0 +1,116 @@ +# Actions Reference + +[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a +mock function should do when invoked. This page lists the built-in actions +provided by GoogleTest. All actions are defined in the `::testing` namespace. + +## Returning a Value + +| Action | Description | +| :-------------------------------- | :-------------------------------------------- | +| `Return()` | Return from a `void` mock function. | +| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | +| `ReturnArg()` | Return the `N`-th (0-based) argument. | +| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | +| `ReturnNull()` | Return a null pointer. | +| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | +| `ReturnRef(variable)` | Return a reference to `variable`. | +| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | +| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | + +## Side Effects + +| Action | Description | +| :--------------------------------- | :-------------------------------------- | +| `Assign(&variable, value)` | Assign `value` to variable. | +| `DeleteArg()` | Delete the `N`-th (0-based) argument, which must be a pointer. | +| `SaveArg(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by copy-assignment. | +| `SaveArgByMove(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by move-assignment. | +| `SaveArgPointee(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | +| `SetArgReferee(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. | +| `SetArgPointee(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | +| `SetArgumentPointee(value)` | Same as `SetArgPointee(value)`. Deprecated. Will be removed in v1.7.0. | +| `SetArrayArgument(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. | +| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | +| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | + +## Using a Function, Functor, or Lambda as an Action + +In the following, by "callable" we mean a free function, `std::function`, +functor, or lambda. + +| Action | Description | +| :---------------------------------- | :------------------------------------- | +| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. | +| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | +| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | +| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | +| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | +| `InvokeArgument(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. | + +The return value of the invoked function is used as the return value of the +action. + +When defining a callable to be used with `Invoke*()`, you can declare any unused +parameters as `Unused`: + +```cpp +using ::testing::Invoke; +double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } +... +EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); +``` + +`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of +`callback`, which must be permanent. The type of `callback` must be a base +callback type instead of a derived one, e.g. + +```cpp + BlockingClosure* done = new BlockingClosure; + ... Invoke(done) ...; // This won't compile! + + Closure* done2 = new BlockingClosure; + ... Invoke(done2) ...; // This works. +``` + +In `InvokeArgument(...)`, if an argument needs to be passed by reference, +wrap it inside `std::ref()`. For example, + +```cpp +using ::testing::InvokeArgument; +... +InvokeArgument<2>(5, string("Hi"), std::ref(foo)) +``` + +calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by +value, and `foo` by reference. + +## Default Action + +| Action | Description | +| :------------ | :----------------------------------------------------- | +| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | + +{: .callout .note} +**Note:** due to technical reasons, `DoDefault()` cannot be used inside a +composite action - trying to do so will result in a run-time error. + +## Composite Actions + +| Action | Description | +| :----------------------------- | :------------------------------------------ | +| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. | +| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | +| `WithArg(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | +| `WithArgs(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | +| `WithoutArgs(a)` | Perform action `a` without any arguments. | + +## Defining Actions + +| Macro | Description | +| :--------------------------------- | :-------------------------------------- | +| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | +| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | +| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | + +The `ACTION*` macros cannot be used inside a function or class. diff --git a/sw/restatdesk_tests/googletest/docs/reference/assertions.md b/sw/restatdesk_tests/googletest/docs/reference/assertions.md new file mode 100644 index 0000000..eeec4a0 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/reference/assertions.md @@ -0,0 +1,640 @@ +# Assertions Reference + +This page lists the assertion macros provided by GoogleTest for verifying code +behavior. To use them, add `#include `. + +The majority of the macros listed below come as a pair with an `EXPECT_` variant +and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal +failures and allow the current function to continue running, while `ASSERT_` +macros generate fatal failures and abort the current function. + +All assertion macros support streaming a custom failure message into them with +the `<<` operator, for example: + +```cpp +EXPECT_TRUE(my_condition) << "My condition is not true"; +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro—in particular, C strings and string objects. If a wide string (`wchar_t*`, +`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an +assertion, it will be translated to UTF-8 when printed. + +## Explicit Success and Failure {#success-failure} + +The assertions in this section generate a success or failure directly instead of +testing a value or expression. These are useful when control flow, rather than a +Boolean expression, determines the test's success or failure, as shown by the +following example: + +```c++ +switch(expression) { + case 1: + ... some checks ... + case 2: + ... some other checks ... + default: + FAIL() << "We shouldn't get here."; +} +``` + +### SUCCEED {#SUCCEED} + +`SUCCEED()` + +Generates a success. This *does not* make the overall test succeed. A test is +considered successful only if none of its assertions fail during its execution. + +The `SUCCEED` assertion is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED` messages to GoogleTest output +in the future. + +### FAIL {#FAIL} + +`FAIL()` + +Generates a fatal failure, which returns from the current function. + +Can only be used in functions that return `void`. See +[Assertion Placement](../advanced.md#assertion-placement) for more information. + +### ADD_FAILURE {#ADD_FAILURE} + +`ADD_FAILURE()` + +Generates a nonfatal failure, which allows the current function to continue +running. + +### ADD_FAILURE_AT {#ADD_FAILURE_AT} + +`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)` + +Generates a nonfatal failure at the file and line number specified. + +## Generalized Assertion {#generalized} + +The following assertion allows [matchers](matchers.md) to be used to verify +values. + +### EXPECT_THAT {#EXPECT_THAT} + +`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \ +`ASSERT_THAT(`*`value`*`,`*`matcher`*`)` + +Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*. + +For example, the following code verifies that the string `value1` starts with +`"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and +10: + +```cpp +#include + +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Lt; +using ::testing::MatchesRegex; +using ::testing::StartsWith; + +... +EXPECT_THAT(value1, StartsWith("Hello")); +EXPECT_THAT(value2, MatchesRegex("Line \\d+")); +ASSERT_THAT(value3, AllOf(Gt(5), Lt(10))); +``` + +Matchers enable assertions of this form to read like English and generate +informative failure messages. For example, if the above assertion on `value1` +fails, the resulting message will be similar to the following: + +``` +Value of: value1 + Actual: "Hi, world!" +Expected: starts with "Hello" +``` + +GoogleTest provides a built-in library of matchers—see the +[Matchers Reference](matchers.md). It is also possible to write your own +matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers). +The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion. + +*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project, +which adds `assertThat()` to JUnit.* + +## Boolean Conditions {#boolean} + +The following assertions test Boolean conditions. + +### EXPECT_TRUE {#EXPECT_TRUE} + +`EXPECT_TRUE(`*`condition`*`)` \ +`ASSERT_TRUE(`*`condition`*`)` + +Verifies that *`condition`* is true. + +### EXPECT_FALSE {#EXPECT_FALSE} + +`EXPECT_FALSE(`*`condition`*`)` \ +`ASSERT_FALSE(`*`condition`*`)` + +Verifies that *`condition`* is false. + +## Binary Comparison {#binary-comparison} + +The following assertions compare two values. The value arguments must be +comparable by the assertion's comparison operator, otherwise a compiler error +will result. + +If an argument supports the `<<` operator, it will be called to print the +argument when the assertion fails. Otherwise, GoogleTest will attempt to print +them in the best way it can—see +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values). + +Arguments are always evaluated exactly once, so it's OK for the arguments to +have side effects. However, the argument evaluation order is undefined and +programs should not depend on any particular argument evaluation order. + +These assertions work with both narrow and wide string objects (`string` and +`wstring`). + +See also the [Floating-Point Comparison](#floating-point) assertions to compare +floating-point numbers and avoid problems caused by rounding. + +### EXPECT_EQ {#EXPECT_EQ} + +`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`==`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in the same memory location, not if they have the same value. Use +[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead +of `EXPECT_EQ(`*`ptr`*`, NULL)`. + +### EXPECT_NE {#EXPECT_NE} + +`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_NE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`!=`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in different memory locations, not if they have different values. Use +[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead +of `EXPECT_NE(`*`ptr`*`, NULL)`. + +### EXPECT_LT {#EXPECT_LT} + +`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<`*`val2`*. + +### EXPECT_LE {#EXPECT_LE} + +`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<=`*`val2`*. + +### EXPECT_GT {#EXPECT_GT} + +`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>`*`val2`*. + +### EXPECT_GE {#EXPECT_GE} + +`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>=`*`val2`*. + +## String Comparison {#c-strings} + +The following assertions compare two **C strings**. To compare two `string` +objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead. + +These assertions also accept wide C strings (`wchar_t*`). If a comparison of two +wide strings fails, their values will be printed as UTF-8 narrow strings. + +To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or +`EXPECT_NE(`*`c_string`*`, nullptr)`. + +### EXPECT_STREQ {#EXPECT_STREQ} + +`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents. + +### EXPECT_STRNE {#EXPECT_STRNE} + +`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents. + +### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ} + +`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents, +ignoring case. + +### EXPECT_STRCASENE {#EXPECT_STRCASENE} + +`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents, +ignoring case. + +## Floating-Point Comparison {#floating-point} + +The following assertions compare two floating-point values. + +Due to rounding errors, it is very unlikely that two floating-point values will +match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point +comparison to make sense, the user needs to carefully choose the error bound. + +GoogleTest also provides assertions that use a default error bound based on +Units in the Last Place (ULPs). To learn more about ULPs, see the article +[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ} + +`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `float` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. Infinity and the largest finite float +value are considered to be one ULP apart. + +### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ} + +`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `double` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. Infinity and the largest finite double +value are considered to be one ULP apart. + +### EXPECT_NEAR {#EXPECT_NEAR} + +`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \ +`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` + +Verifies that the difference between *`val1`* and *`val2`* does not exceed the +absolute error bound *`abs_error`*. + +If *`val`* and *`val2`* are both infinity of the same sign, the difference is +considered to be 0. Otherwise, if either value is infinity, the difference is +considered to be infinity. All non-NaN values (including infinity) are +considered to not exceed an *`abs_error`* of infinity. + +## Exception Assertions {#exceptions} + +The following assertions verify that a piece of code throws, or does not throw, +an exception. Usage requires exceptions to be enabled in the build environment. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_NO_THROW({ + int n = 5; + DoSomething(&n); +}); +``` + +### EXPECT_THROW {#EXPECT_THROW} + +`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \ +`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)` + +Verifies that *`statement`* throws an exception of type *`exception_type`*. + +### EXPECT_ANY_THROW {#EXPECT_ANY_THROW} + +`EXPECT_ANY_THROW(`*`statement`*`)` \ +`ASSERT_ANY_THROW(`*`statement`*`)` + +Verifies that *`statement`* throws an exception of any type. + +### EXPECT_NO_THROW {#EXPECT_NO_THROW} + +`EXPECT_NO_THROW(`*`statement`*`)` \ +`ASSERT_NO_THROW(`*`statement`*`)` + +Verifies that *`statement`* does not throw any exception. + +## Predicate Assertions {#predicates} + +The following assertions enable more complex predicates to be verified while +printing a more clear failure message than if `EXPECT_TRUE` were used alone. + +### EXPECT_PRED* {#EXPECT_PRED} + +`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred`* returns `true` when passed the given values +as arguments. + +The parameter *`pred`* is a function or functor that accepts as many arguments +as the corresponding macro accepts values. If *`pred`* returns `true` for the +given arguments, the assertion succeeds, otherwise the assertion fails. + +When the assertion fails, it prints the value of each argument. Arguments are +always evaluated exactly once. + +As an example, see the following code: + +```cpp +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds +EXPECT_PRED2(MutuallyPrime, b, c); // Fails +``` + +In the above example, the first assertion succeeds, and the second fails with +the following message: + +``` +MutuallyPrime(b, c) is false, where +b is 4 +c is 10 +``` + +Note that if the given predicate is an overloaded function or a function +template, the assertion macro might not be able to determine which version to +use, and it might be necessary to explicitly specify the type of the function. +For example, for a Boolean function `IsPositive()` overloaded to take either a +single `int` or `double` argument, it would be necessary to write one of the +following: + +```cpp +EXPECT_PRED1(static_cast(IsPositive), 5); +EXPECT_PRED1(static_cast(IsPositive), 3.14); +``` + +Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error. +Similarly, to use a template function, specify the template arguments: + +```cpp +template +bool IsNegative(T x) { + return x < 0; +} +... +EXPECT_PRED1(IsNegative, -5); // Must specify type for IsNegative +``` + +If a template has multiple parameters, wrap the predicate in parentheses so the +macro arguments are parsed correctly: + +```cpp +ASSERT_PRED2((MyPredicate), 5, 0); +``` + +### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT} + +`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred_formatter`* succeeds when passed the given +values as arguments. + +The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function +or functor with the signature: + +```cpp +testing::AssertionResult PredicateFormatter(const char* expr1, + const char* expr2, + ... + const char* exprn, + T1 val1, + T2 val2, + ... + Tn valn); +``` + +where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate +arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding +expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn` +can be either value types or reference types; if an argument has type `T`, it +can be declared as either `T` or `const T&`, whichever is appropriate. For more +about the return type `testing::AssertionResult`, see +[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult). + +As an example, see the following code: + +```cpp +// Returns the smallest prime common divisor of m and n, +// or 1 when m and n are mutually prime. +int SmallestPrimeCommonDivisor(int m, int n) { ... } + +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } + +// A predicate-formatter for asserting that two integers are mutually prime. +testing::AssertionResult AssertMutuallyPrime(const char* m_expr, + const char* n_expr, + int m, + int n) { + if (MutuallyPrime(m, n)) return testing::AssertionSuccess(); + + return testing::AssertionFailure() << m_expr << " and " << n_expr + << " (" << m << " and " << n << ") are not mutually prime, " + << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); +} + +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails +``` + +In the above example, the final assertion fails and the predicate-formatter +produces the following failure message: + +``` +b and c (4 and 10) are not mutually prime, as they have a common divisor 2 +``` + +## Windows HRESULT Assertions {#HRESULT} + +The following assertions test for `HRESULT` success or failure. For example: + +```cpp +CComPtr shell; +ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); +CComVariant empty; +ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); +``` + +The generated output contains the human-readable error message associated with +the returned `HRESULT` code. + +### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED} + +`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \ +`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)` + +Verifies that *`expression`* is a success `HRESULT`. + +### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED} + +`EXPECT_HRESULT_FAILED(`*`expression`*`)` \ +`ASSERT_HRESULT_FAILED(`*`expression`*`)` + +Verifies that *`expression`* is a failure `HRESULT`. + +## Death Assertions {#death} + +The following assertions verify that a piece of code causes the process to +terminate. For context, see [Death Tests](../advanced.md#death-tests). + +These assertions spawn a new process and execute the code under test in that +process. How that happens depends on the platform and the variable +`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the +command-line flag `--gtest_death_test_style`. + +* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the + child, after which: + * If the variable's value is `"fast"`, the death test statement is + immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes + the unit test binary just as it was originally invoked, but with some + extra flags to cause just the single death test under consideration to + be run. +* On Windows, the child is spawned using the `CreateProcess()` API, and + re-executes the binary to cause just the single death test under + consideration to be run - much like the `"threadsafe"` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to fail. +Currently, the flag's default value is +**`"fast"`**. + +If the death test statement runs to completion without dying, the child process +will nonetheless terminate, and the assertion fails. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_DEATH({ + int n = 5; + DoSomething(&n); +}, "Error on line .* of DoSomething()"); +``` + +### EXPECT_DEATH {#EXPECT_DEATH} + +`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with a nonzero exit +status and produces `stderr` output that matches *`matcher`*. + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `DoSomething(42)` causes +the process to die with an error message that contains the text `My error`: + +```cpp +EXPECT_DEATH(DoSomething(42), "My error"); +``` + +### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED} + +`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` + +If death tests are supported, behaves the same as +[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing. + +### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH} + +`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` + +In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in +debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*. + +### EXPECT_EXIT {#EXPECT_EXIT} + +`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \ +`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with an exit status +that satisfies *`predicate`*, and produces `stderr` output that matches +*`matcher`*. + +The parameter *`predicate`* is a function or functor that accepts an `int` exit +status and returns a `bool`. GoogleTest provides two predicates to handle common +cases: + +```cpp +// Returns true if the program exited normally with the given exit status code. +::testing::ExitedWithCode(exit_code); + +// Returns true if the program was killed by the given signal. +// Not available on Windows. +::testing::KilledBySignal(signal_number); +``` + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `NormalExit()` causes the +process to print a message containing the text `Success` to `stderr` and exit +with exit status code 0: + +```cpp +EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +``` diff --git a/sw/restatdesk_tests/googletest/docs/reference/matchers.md b/sw/restatdesk_tests/googletest/docs/reference/matchers.md new file mode 100644 index 0000000..8ff9e0b --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/reference/matchers.md @@ -0,0 +1,305 @@ +# Matchers Reference + +A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or +`EXPECT_CALL()`, or use it to validate a value directly using two macros: + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | +| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | + +{: .callout .warning} +**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)` +is supported, however note that implicit conversions can cause surprising +results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and +may pass unintentionally. + +**BEST PRACTICE:** Prefer to make the comparison explicit via +`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, +expected_value)`. + +Built-in matchers (where `argument` is the function argument, e.g. +`actual_value` in the example above, or when used in the context of +`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are +divided into several categories. All matchers are defined in the `::testing` +namespace unless otherwise noted. + +## Wildcard + +Matcher | Description +:-------------------------- | :----------------------------------------------- +`_` | `argument` can be any value of the correct type. +`A()` or `An()` | `argument` can be any value of type `type`. + +## Generic Comparison + +| Matcher | Description | +| :--------------------- | :-------------------------------------------------- | +| `Eq(value)` or `value` | `argument == value` | +| `Ge(value)` | `argument >= value` | +| `Gt(value)` | `argument > value` | +| `Le(value)` | `argument <= value` | +| `Lt(value)` | `argument < value` | +| `Ne(value)` | `argument != value` | +| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | +| `DistanceFrom(target, m)` | The distance between `argument` and `target` (computed by `abs(argument - target)`) matches `m`. | +| `DistanceFrom(target, get_distance, m)` | The distance between `argument` and `target` (computed by `get_distance(argument, target)`) matches `m`. | +| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | +| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | +| `NotNull()` | `argument` is a non-null pointer (raw or smart). | +| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| +| `VariantWith(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | +| `Ref(variable)` | `argument` is a reference to `variable`. | +| `TypedEq(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | + +Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or +destructed later. If the compiler complains that `value` doesn't have a public +copy constructor, try wrap it in `std::ref()`, e.g. +`Eq(std::ref(non_copyable_value))`. If you do that, make sure +`non_copyable_value` is not changed afterwards, or the meaning of your matcher +will be changed. + +`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types +that can be explicitly converted to Boolean, but are not implicitly converted to +Boolean. In other cases, you can use the basic +[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions. + +## Floating-Point Matchers {#FpMatchers} + +| Matcher | Description | +| :------------------------------- | :--------------------------------- | +| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | +| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | +| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | +| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| `IsNan()` | `argument` is any floating-point type with a NaN value. | + +The above matchers use ULP-based comparison (the same as used in googletest). +They automatically pick a reasonable error bound based on the absolute value of +the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard, +which requires comparing two NaNs for equality to return false. The +`NanSensitive*` version instead treats two NaNs as equal, which is often what a +user wants. + +| Matcher | Description | +| :------------------------------------------------ | :----------------------- | +| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | +| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | + +## String Matchers + +The `argument` can be either a C string or a C++ string object: + +| Matcher | Description | +| :---------------------- | :------------------------------------------------- | +| `ContainsRegex(string)` | `argument` matches the given regular expression. | +| `EndsWith(suffix)` | `argument` ends with string `suffix`. | +| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | +| `IsEmpty()` | `argument` is an empty string. | +| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. | +| `StartsWith(prefix)` | `argument` starts with string `prefix`. | +| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | +| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | +| `StrEq(string)` | `argument` is equal to `string`. | +| `StrNe(string)` | `argument` is not equal to `string`. | +| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. | + +`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They +use the regular expression syntax defined +[here](../advanced.md#regular-expression-syntax). All of these matchers, except +`ContainsRegex()` and `MatchesRegex()` work for wide strings as well. + +## Container Matchers + +Most STL-style containers support `==`, so you can use `Eq(expected_container)` +or simply `expected_container` to match a container exactly. If you want to +write the elements in-line, match them more flexibly, or get more informative +messages, you can use: + +| Matcher | Description | +| :---------------------------------------- | :------------------------------- | +| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | +| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | +| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | +| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. | +| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | +| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | +| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | +| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | +| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | +| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | +| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | +| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | +| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. | +| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. | +| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | + +**Notes:** + +* These matchers can also match: + 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), + and + 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, + int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). +* The array being matched may be multi-dimensional (i.e. its elements can be + arrays). +* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a + matcher for `::std::tuple` where `T` and `U` are the element type of + the actual container and the expected container, respectively. For example, + to compare two `Foo` containers where `Foo` doesn't support `operator==`, + one might write: + + ```cpp + MATCHER(FooEq, "") { + return std::get<0>(arg).Equals(std::get<1>(arg)); + } + ... + EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); + ``` + +## Member Matchers + +| Matcher | Description | +| :------------------------------ | :----------------------------------------- | +| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | +| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. | +| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. | +| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | +| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size`+`get(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. | +| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. | +| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message. + +{: .callout .warning} +Warning: Don't use `Property()` against member functions that you do not own, +because taking addresses of functions is fragile and generally not part of the +contract of the function. + +**Notes:** + +* You can use `FieldsAre()` to match any type that supports structured + bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate + types. For example: + + ```cpp + std::tuple my_tuple{7, "hello world"}; + EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello"))); + + struct MyStruct { + int value = 42; + std::string greeting = "aloha"; + }; + MyStruct s; + EXPECT_THAT(s, FieldsAre(42, "aloha")); + ``` + +## Matching the Result of a Function, Functor, or Callback + +| Matcher | Description | +| :--------------- | :------------------------------------------------ | +| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | +| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message. + +## Pointer Matchers + +| Matcher | Description | +| :------------------------ | :---------------------------------------------- | +| `Address(m)` | the result of `std::addressof(argument)` matches `m`. | +| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. | +| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. | +| `WhenDynamicCastTo(m)` | when `argument` is passed through `dynamic_cast()`, it matches matcher `m`. | + +## Multi-argument Matchers {#MultiArgMatchers} + +Technically, all matchers match a *single* value. A "multi-argument" matcher is +just one that matches a *tuple*. The following matchers can be used to match a +tuple `(x, y)`: + +Matcher | Description +:------ | :---------- +`Eq()` | `x == y` +`Ge()` | `x >= y` +`Gt()` | `x > y` +`Le()` | `x <= y` +`Lt()` | `x < y` +`Ne()` | `x != y` + +You can use the following selectors to pick a subset of the arguments (or +reorder them) to participate in the matching: + +| Matcher | Description | +| :------------------------- | :---------------------------------------------- | +| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. | +| `Args(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. | + +## Composite Matchers + +You can make a matcher from one or more other matchers: + +| Matcher | Description | +| :------------------------------- | :-------------------------------------- | +| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. | +| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | +| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `Not(m)` | `argument` doesn't match matcher `m`. | +| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.| + +## Adapters for Matchers + +| Matcher | Description | +| :---------------------- | :------------------------------------ | +| `MatcherCast(m)` | casts matcher `m` to type `Matcher`. | +| `SafeMatcherCast(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher`. | +| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. | + +`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, +which must be a permanent callback. + +## Using Matchers as Predicates {#MatchersAsPredicatesCheat} + +| Matcher | Description | +| :---------------------------- | :------------------------------------------ | +| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | +| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | +| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | + +## Defining Matchers + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | +| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. | +| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | + +**Notes:** + +1. The `MATCHER*` macros cannot be used inside a function or class. +2. The matcher body must be *purely functional* (i.e. it cannot have any side + effect, and the result must not depend on anything other than the value + being matched and the matcher parameters). +3. You can use `PrintToString(x)` to convert a value `x` of any type to a + string. +4. You can use `ExplainMatchResult()` in a custom matcher to wrap another + matcher, for example: + + ```cpp + MATCHER_P(NestedPropertyMatches, matcher, "") { + return ExplainMatchResult(matcher, arg.nested().property(), result_listener); + } + ``` + +5. You can use `DescribeMatcher<>` to describe another matcher. For example: + + ```cpp + MATCHER_P(XAndYThat, matcher, + "X that " + DescribeMatcher(matcher, negation) + + (negation ? " or" : " and") + " Y that " + + DescribeMatcher(matcher, negation)) { + return ExplainMatchResult(matcher, arg.x(), result_listener) && + ExplainMatchResult(matcher, arg.y(), result_listener); + } + ``` diff --git a/sw/restatdesk_tests/googletest/docs/reference/mocking.md b/sw/restatdesk_tests/googletest/docs/reference/mocking.md new file mode 100644 index 0000000..ab37ebf --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/reference/mocking.md @@ -0,0 +1,588 @@ +# Mocking Reference + +This page lists the facilities provided by GoogleTest for creating and working +with mock objects. To use them, add `#include `. + +## Macros {#macros} + +GoogleTest defines the following macros for working with mocks. + +### MOCK_METHOD {#MOCK_METHOD} + +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \ +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`), +(`*`specs...`*`));` + +Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and +return type *`return_type`* within a mock class. + +The parameters of `MOCK_METHOD` mirror the method declaration. The optional +fourth parameter *`specs...`* is a comma-separated list of qualifiers. The +following qualifiers are accepted: + +| Qualifier | Meaning | +| -------------------------- | -------------------------------------------- | +| `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. | +| `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. | +| `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. | +| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. | +| `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. | + +Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments +correctly if they are not appropriately surrounded by parentheses. See the +following example: + +```cpp +class MyMock { + public: + // The following 2 lines will not compile due to commas in the arguments: + MOCK_METHOD(std::pair, GetPair, ()); // Error! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Error! + + // One solution - wrap arguments that contain commas in parentheses: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); + + // Another solution - use type aliases: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +`MOCK_METHOD` must be used in the `public:` section of a mock class definition, +regardless of whether the method being mocked is `public`, `protected`, or +`private` in the base class. + +### EXPECT_CALL {#EXPECT_CALL} + +`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the +method *`method_name`* of the object *`mock_object`* is called with arguments +that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any +code that exercises the mock object. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The expectation will +apply only to calls of *`method_name`* whose arguments match all of the +matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to modify the expectation, and they +must be used in the following order: + +```cpp +EXPECT_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .Times(cardinality) // Can be used at most once + .InSequence(sequences...) // Can be used any number of times + .After(expectations...) // Can be used any number of times + .WillOnce(action) // Can be used any number of times + .WillRepeatedly(action) // Can be used at most once + .RetiresOnSaturation(); // Can be used at most once +``` + +See details for each modifier clause below. + +#### With {#EXPECT_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the expectation to apply only to mock function calls whose arguments +as a whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the expectation that +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +... +EXPECT_CALL(my_mock, SetPosition(_, _)) + .With(Lt()); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once on an expectation and must be the +first clause. + +#### Times {#EXPECT_CALL.Times} + +`.Times(`*`cardinality`*`)` + +Specifies how many times the mock function call is expected. + +The parameter *`cardinality`* represents the number of expected calls and can be +one of the following, all defined in the `::testing` namespace: + +| Cardinality | Meaning | +| ------------------- | --------------------------------------------------- | +| `AnyNumber()` | The function can be called any number of times. | +| `AtLeast(n)` | The function call is expected at least *n* times. | +| `AtMost(n)` | The function call is expected at most *n* times. | +| `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. | +| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. | + +If the `Times` clause is omitted, GoogleTest infers the cardinality as follows: + +* If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor + [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred + cardinality is `Times(1)`. +* If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where + *n* >= 1, the inferred cardinality is `Times(n)`. +* If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where + *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`. + +The `Times` clause can be used at most once on an expectation. + +#### InSequence {#EXPECT_CALL.InSequence} + +`.InSequence(`*`sequences...`*`)` + +Specifies that the mock function call is expected in a certain sequence. + +The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects. +Expected calls assigned to the same sequence are expected to occur in the order +the expectations are declared. + +For example, the following code sets the expectation that the `Reset()` method +of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()` +and `Describe()` can occur in any order relative to each other: + +```cpp +using ::testing::Sequence; +Sequence s1, s2; +... +EXPECT_CALL(my_mock, Reset()) + .InSequence(s1, s2); +EXPECT_CALL(my_mock, GetSize()) + .InSequence(s1); +EXPECT_CALL(my_mock, Describe()) + .InSequence(s2); +``` + +The `InSequence` clause can be used any number of times on an expectation. + +See also the [`InSequence` class](#InSequence). + +#### After {#EXPECT_CALL.After} + +`.After(`*`expectations...`*`)` + +Specifies that the mock function call is expected to occur after one or more +other calls. + +The parameter *`expectations...`* can be up to five +[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects. +The mock function call is expected to occur after all of the given expectations. + +For example, the following code sets the expectation that the `Describe()` +method of `my_mock` is called only after both `InitX()` and `InitY()` have been +called. + +```cpp +using ::testing::Expectation; +... +Expectation init_x = EXPECT_CALL(my_mock, InitX()); +Expectation init_y = EXPECT_CALL(my_mock, InitY()); +EXPECT_CALL(my_mock, Describe()) + .After(init_x, init_y); +``` + +The `ExpectationSet` object is helpful when the number of prerequisites for an +expectation is large or variable, for example: + +```cpp +using ::testing::ExpectationSet; +... +ExpectationSet all_inits; +// Collect all expectations of InitElement() calls +for (int i = 0; i < element_count; i++) { + all_inits += EXPECT_CALL(my_mock, InitElement(i)); +} +EXPECT_CALL(my_mock, Describe()) + .After(all_inits); // Expect Describe() call after all InitElement() calls +``` + +The `After` clause can be used any number of times on an expectation. + +#### WillOnce {#EXPECT_CALL.WillOnce} + +`.WillOnce(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for a single +matching function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillOnce` implicitly sets a cardinality on the expectation when +`Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +Each matching function call will perform the next action in the order declared. +For example, the following code specifies that `my_mock.GetNumber()` is expected +to be called exactly 3 times and will return `1`, `2`, and `3` respectively on +the first, second, and third calls: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillOnce(Return(3)); +``` + +The `WillOnce` clause can be used any number of times on an expectation. Unlike +`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most +once, so may be a move-only type and/or have an `&&`-qualified call operator. + +#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly} + +`.WillRepeatedly(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for all subsequent +matching function calls. Takes effect after the actions specified in the +[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillRepeatedly` implicitly sets a cardinality on the expectation +when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +If any `WillOnce` clauses have been specified, matching function calls will +perform those actions before the action specified by `WillRepeatedly`. See the +following example: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetName()) + .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls + +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(42)) // Return 42 on the first call + .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls +``` + +The `WillRepeatedly` clause can be used at most once on an expectation. + +#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation} + +`.RetiresOnSaturation()` + +Indicates that the expectation will no longer be active after the expected +number of matching function calls has been reached. + +The `RetiresOnSaturation` clause is only meaningful for expectations with an +upper-bounded cardinality. The expectation will *retire* (no longer match any +function calls) after it has been *saturated* (the upper bound has been +reached). See the following example: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1 + .Times(AnyNumber()); +EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2 + .Times(2) + .RetiresOnSaturation(); +``` + +In the above example, the first two calls to `my_mock.SetNumber(7)` match +expectation 2, which then becomes inactive and no longer matches any calls. A +third call to `my_mock.SetNumber(7)` would then match expectation 1. Without +`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)` +would match expectation 2 again, producing a failure since the limit of 2 calls +was exceeded. + +The `RetiresOnSaturation` clause can be used at most once on an expectation and +must be the last clause. + +### ON_CALL {#ON_CALL} + +`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Defines what happens when the method *`method_name`* of the object +*`mock_object`* is called with arguments that match the given matchers +*`matchers...`*. Requires a modifier clause to specify the method's behavior. +*Does not* set any expectations that the method will be called. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The `ON_CALL` +specification will apply only to calls of *`method_name`* whose arguments match +all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to set the method's behavior, and +they must be used in the following order: + +```cpp +ON_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .WillByDefault(action); // Required +``` + +See details for each modifier clause below. + +#### With {#ON_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the specification to only mock function calls whose arguments as a +whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the default behavior when +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... +ON_CALL(my_mock, SetPosition(_, _)) + .With(Lt()) + .WillByDefault(Return(true)); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once with each `ON_CALL` statement. + +#### WillByDefault {#ON_CALL.WillByDefault} + +`.WillByDefault(`*`action`*`)` + +Specifies the default behavior of a matching mock function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +For example, the following code specifies that by default, a call to +`my_mock.Greet()` will return `"hello"`: + +```cpp +using ::testing::Return; +... +ON_CALL(my_mock, Greet()) + .WillByDefault(Return("hello")); +``` + +The action specified by `WillByDefault` is superseded by the actions specified +on a matching `EXPECT_CALL` statement, if any. See the +[`WillOnce`](#EXPECT_CALL.WillOnce) and +[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`. + +The `WillByDefault` clause must be used exactly once with each `ON_CALL` +statement. + +## Classes {#classes} + +GoogleTest defines the following classes for working with mocks. + +### DefaultValue {#DefaultValue} + +`::testing::DefaultValue` + +Allows a user to specify the default value for a type `T` that is both copyable +and publicly destructible (i.e. anything that can be used as a function return +type). For mock functions with a return type of `T`, this default value is +returned from function calls that do not specify an action. + +Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the +default value: + +```cpp +// Sets the default value to be returned. T must be copy constructible. +DefaultValue::Set(value); + +// Sets a factory. Will be invoked on demand. T must be move constructible. +T MakeT(); +DefaultValue::SetFactory(&MakeT); + +// Unsets the default value. +DefaultValue::Clear(); +``` + +### NiceMock {#NiceMock} + +`::testing::NiceMock` + +Represents a mock object that suppresses warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NiceMock` is analogous to usage of `T`. `NiceMock` is a subclass +of `T`, so it can be used wherever an object of type `T` is accepted. In +addition, `NiceMock` can be constructed with any arguments that a constructor +of `T` accepts. + +For example, the following code suppresses warnings on the mock `my_mock` of +type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NiceMock; +... +NiceMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`NiceMock` only works for mock methods defined using the `MOCK_METHOD` macro +directly in the definition of class `T`. If a mock method is defined in a base +class of `T`, a warning might still be generated. + +`NiceMock` might not work correctly if the destructor of `T` is not virtual. + +### NaggyMock {#NaggyMock} + +`::testing::NaggyMock` + +Represents a mock object that generates warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NaggyMock` is analogous to usage of `T`. `NaggyMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `NaggyMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates warnings on the mock `my_mock` of type +`MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NaggyMock; +... +NaggyMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +Mock objects of type `T` by default behave the same way as `NaggyMock`. + +### StrictMock {#StrictMock} + +`::testing::StrictMock` + +Represents a mock object that generates test failures on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `StrictMock` is analogous to usage of `T`. `StrictMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `StrictMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates a test failure on the mock `my_mock` +of type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::StrictMock; +... +StrictMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`StrictMock` only works for mock methods defined using the `MOCK_METHOD` +macro directly in the definition of class `T`. If a mock method is defined in a +base class of `T`, a failure might not be generated. + +`StrictMock` might not work correctly if the destructor of `T` is not +virtual. + +### Sequence {#Sequence} + +`::testing::Sequence` + +Represents a chronological sequence of expectations. See the +[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage. + +### InSequence {#InSequence} + +`::testing::InSequence` + +An object of this type causes all expectations encountered in its scope to be +put in an anonymous sequence. + +This allows more convenient expression of multiple expectations in a single +sequence: + +```cpp +using ::testing::InSequence; +{ + InSequence seq; + + // The following are expected to occur in the order declared. + EXPECT_CALL(...); + EXPECT_CALL(...); + ... + EXPECT_CALL(...); +} +``` + +The name of the `InSequence` object does not matter. + +### Expectation {#Expectation} + +`::testing::Expectation` + +Represents a mock function call expectation as created by +[`EXPECT_CALL`](#EXPECT_CALL): + +```cpp +using ::testing::Expectation; +Expectation my_expectation = EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. + +### ExpectationSet {#ExpectationSet} + +`::testing::ExpectationSet` + +Represents a set of mock function call expectations. + +Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set: + +```cpp +using ::testing::ExpectationSet; +ExpectationSet my_expectations; +my_expectations += EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. diff --git a/sw/restatdesk_tests/googletest/docs/reference/testing.md b/sw/restatdesk_tests/googletest/docs/reference/testing.md new file mode 100644 index 0000000..d7dc5cf --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/reference/testing.md @@ -0,0 +1,1550 @@ +# Testing Reference + + + +This page lists the facilities provided by GoogleTest for writing test programs. +To use them, add `#include `. + +## Macros + +GoogleTest defines the following macros for writing tests. + +### TEST {#TEST} + +
+TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* in the test suite +*`TestSuiteName`*, consisting of the given statements. + +Both arguments *`TestSuiteName`* and *`TestName`* must be valid C++ identifiers +and must not contain underscores (`_`). Tests in different test suites can have +the same individual name. + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_F {#TEST_F} + +
+TEST_F(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* that uses the test fixture class +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a test fixture class—see +[Test Fixtures](../primer.md#same-data-multiple-tests). + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_P {#TEST_P} + +
+TEST_P(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual value-parameterized test named *`TestName`* that uses the +test fixture class *`TestFixtureName`*. The test suite name is +*`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a value-parameterized test fixture class—see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +The statements within the test body can be any code under test. Within the test +body, the test parameter can be accessed with the `GetParam()` function (see +[`WithParamInterface`](#WithParamInterface)). For example: + +```cpp +TEST_P(MyTestSuite, DoesSomething) { + ... + EXPECT_TRUE(DoSomething(GetParam())); + ... +} +``` + +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +See also [`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). + +### INSTANTIATE_TEST_SUITE_P {#INSTANTIATE_TEST_SUITE_P} + +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`)` +\ +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`,`*`name_generator`*`)` + +Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with +[`TEST_P`](#TEST_P)). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. If *`InstantiationName`* is empty +(`INSTANTIATE_TEST_SUITE_P(, ...)`), no prefix is added. + +The argument *`param_generator`* is one of the following GoogleTest-provided +functions that generate the test parameters, all defined in the `::testing` +namespace: + + + +| Parameter Generator | Behavior | +| ------------------- | ---------------------------------------------------- | +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. | +| `ConvertGenerator(g)` or `ConvertGenerator(g, func)` | Yields values generated by generator `g`, `static_cast` from `T`. (Note: `T` might not be what you expect. See [*Using ConvertGenerator*](#using-convertgenerator) below.) The second overload uses `func` to perform the conversion. | + +The optional last argument *`name_generator`* is a function or functor that +generates custom test name suffixes based on the test parameters. The function +must accept an argument of type +[`TestParamInfo`](#TestParamInfo) and return a `std::string`. +The test name suffix can only contain alphanumeric characters and underscores. +GoogleTest provides [`PrintToStringParamName`](#PrintToStringParamName), or a +custom function can be used for more control: + +```cpp +INSTANTIATE_TEST_SUITE_P( + MyInstantiation, MyTestSuite, + testing::Values(...), + [](const testing::TestParamInfo& info) { + // Can use info.param here to generate the test suffix + std::string name = ... + return name; + }); +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +See also +[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST). + +###### Using `ConvertGenerator` + +The functions listed in the table above appear to return generators that create +values of the desired types, but this is not generally the case. Rather, they +typically return factory objects that convert to the the desired generators. +This affords some flexibility in allowing you to specify values of types that +are different from, yet implicitly convertible to, the actual parameter type +required by your fixture class. + +For example, you can do the following with a fixture that requires an `int` +parameter: + +```cpp +INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite, + testing::Values(1, 1.2)); // Yes, Values() supports heterogeneous argument types. +``` + +It might seem obvious that `1.2` — a `double` — will be converted to +an `int` but in actuality it requires some template gymnastics involving the +indirection described in the previous paragraph. + +What if your parameter type is not implicitly convertible from the generated +type but is *explicitly* convertible? There will be no automatic conversion, but +you can force it by applying `ConvertGenerator`. The compiler can +automatically deduce the target type (your fixture's parameter type), but +because of the aforementioned indirection it cannot decide what the generated +type should be. You need to tell it, by providing the type `T` explicitly. Thus +`T` should not be your fixture's parameter type, but rather an intermediate type +that is supported by the factory object, and which can be `static_cast` to the +fixture's parameter type: + +```cpp +// The fixture's parameter type. +class MyParam { + public: + // Explicit converting ctor. + explicit MyParam(const std::tuple& t); + ... +}; + +INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite, + ConvertGenerator>(Combine(Values(0.1, 1.2), Bool()))); +``` + +In this example `Combine` supports the generation of `std::tuple>` +objects (even though the provided values for the first tuple element are +`double`s) and those `tuple`s get converted into `MyParam` objects by virtue of +the call to `ConvertGenerator`. + +For parameter types that are not convertible from the generated types you can +provide a callable that does the conversion. The callable accepts an object of +the generated type and returns an object of the fixture's parameter type. The +generated type can often be deduced by the compiler from the callable's call +signature so you do not usually need specify it explicitly (but see a caveat +below). + +```cpp +// The fixture's parameter type. +class MyParam { + public: + MyParam(int, bool); + ... +}; + +INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite, + ConvertGenerator(Combine(Values(1, 1.2), Bool()), + [](const std::tuple& t){ + const auto [i, b] = t; + return MyParam(i, b); + })); +``` + +The callable may be anything that can be used to initialize a `std::function` +with the appropriate call signature. Note the callable's return object gets +`static_cast` to the fixture's parameter type, so it does not have to be of that +exact type, only convertible to it. + +**Caveat:** Consider the following example. + +```cpp +INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite, + ConvertGenerator(Values(std::string("s")), [](std::string_view s) { ... })); +``` + +The `string` argument gets copied into the factory object returned by `Values`. +Then, because the generated type deduced from the lambda is `string_view`, the +factory object spawns a generator that holds a `string_view` referencing that +`string`. Unfortunately, by the time this generator gets invoked, the factory +object is gone and the `string_view` is dangling. + +To overcome this problem you can specify the generated type explicitly: +`ConvertGenerator(Values(std::string("s")), [](std::string_view s) +{ ... })`. Alternatively, you can change the lambda's signature to take a +`std::string` or a `const std::string&` (the latter will not leave you with a +dangling reference because the type deduction strips off the reference and the +`const`). + +### TYPED_TEST_SUITE {#TYPED_TEST_SUITE} + +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)` +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`,`*`NameGenerator`*`)` + +Defines a typed test suite based on the test fixture *`TestFixtureName`*. The +test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type, for example: + +```cpp +template +class MyFixture : public testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. + +The optional third argument *`NameGenerator`* allows specifying a class that +exposes a templated static function `GetName(int)`. For example: + +```cpp +class NameGenerator { + public: + template + static std::string GetName(int) { + if constexpr (std::is_same_v) return "char"; + if constexpr (std::is_same_v) return "int"; + if constexpr (std::is_same_v) return "unsignedInt"; + } +}; +TYPED_TEST_SUITE(MyFixture, MyTypes, NameGenerator); +``` + +See also [`TYPED_TEST`](#TYPED_TEST) and +[Typed Tests](../advanced.md#typed-tests) for more information. + +### TYPED_TEST {#TYPED_TEST} + +
+TYPED_TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual typed test named *`TestName`* in the typed test suite +*`TestSuiteName`*. The test suite must be defined with +[`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See the following example: + +```cpp +TYPED_TEST(MyFixture, Example) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of MyFixture via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} +``` + +For more information, see [Typed Tests](../advanced.md#typed-tests). + +### TYPED_TEST_SUITE_P {#TYPED_TEST_SUITE_P} + +`TYPED_TEST_SUITE_P(`*`TestFixtureName`*`)` + +Defines a type-parameterized test suite based on the test fixture +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type. See [`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE) for an example. + +See also [`TYPED_TEST_P`](#TYPED_TEST_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### TYPED_TEST_P {#TYPED_TEST_P} + +
+TYPED_TEST_P(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual type-parameterized test named *`TestName`* in the +type-parameterized test suite *`TestSuiteName`*. The test suite must be defined +with [`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See [`TYPED_TEST`](#TYPED_TEST) +for an example. + +See also [`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### REGISTER_TYPED_TEST_SUITE_P {#REGISTER_TYPED_TEST_SUITE_P} + +`REGISTER_TYPED_TEST_SUITE_P(`*`TestSuiteName`*`,`*`TestNames...`*`)` + +Registers the type-parameterized tests *`TestNames...`* of the test suite +*`TestSuiteName`*. The test suite and tests must be defined with +[`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P) and [`TYPED_TEST_P`](#TYPED_TEST_P). + +For example: + +```cpp +// Define the test suite and tests. +TYPED_TEST_SUITE_P(MyFixture); +TYPED_TEST_P(MyFixture, HasPropertyA) { ... } +TYPED_TEST_P(MyFixture, HasPropertyB) { ... } + +// Register the tests in the test suite. +REGISTER_TYPED_TEST_SUITE_P(MyFixture, HasPropertyA, HasPropertyB); +``` + +See also [`INSTANTIATE_TYPED_TEST_SUITE_P`](#INSTANTIATE_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### INSTANTIATE_TYPED_TEST_SUITE_P {#INSTANTIATE_TYPED_TEST_SUITE_P} + +`INSTANTIATE_TYPED_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`Types`*`)` + +Instantiates the type-parameterized test suite *`TestSuiteName`*. The test suite +must be registered with +[`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. If *`InstantiationName`* is empty +(`INSTANTIATE_TYPED_TEST_SUITE_P(, ...)`), no prefix is added. + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(MyInstantiation, MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro to parse correctly. + +For more information, see +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +### FRIEND_TEST {#FRIEND_TEST} + +`FRIEND_TEST(`*`TestSuiteName`*`,`*`TestName`*`)` + +Within a class body, declares an individual test as a friend of the class, +enabling the test to access private class members. + +If the class is defined in a namespace, then in order to be friends of the +class, test fixtures and tests must be defined in the exact same namespace, +without inline or anonymous namespaces. + +For example, if the class definition looks like the following: + +```cpp +namespace my_namespace { + +class MyClass { + friend class MyClassTest; + FRIEND_TEST(MyClassTest, HasPropertyA); + FRIEND_TEST(MyClassTest, HasPropertyB); + ... definition of class MyClass ... +}; + +} // namespace my_namespace +``` + +Then the test code should look like: + +```cpp +namespace my_namespace { + +class MyClassTest : public testing::Test { + ... +}; + +TEST_F(MyClassTest, HasPropertyA) { ... } +TEST_F(MyClassTest, HasPropertyB) { ... } + +} // namespace my_namespace +``` + +See [Testing Private Code](../advanced.md#testing-private-code) for more +information. + +### SCOPED_TRACE {#SCOPED_TRACE} + +`SCOPED_TRACE(`*`message`*`)` + +Causes the current file name, line number, and the given message *`message`* to +be added to the failure message for each assertion failure that occurs in the +scope. + +For more information, see +[Adding Traces to Assertions](../advanced.md#adding-traces-to-assertions). + +See also the [`ScopedTrace` class](#ScopedTrace). + +### GTEST_SKIP {#GTEST_SKIP} + +`GTEST_SKIP()` + +Prevents further test execution at runtime. + +Can be used in individual test cases or in the `SetUp()` methods of test +environments or test fixtures (classes derived from the +[`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global +test environment `SetUp()` method, it skips all tests in the test program. If +used in a test fixture `SetUp()` method, it skips all tests in the corresponding +test suite. + +Similar to assertions, `GTEST_SKIP` allows streaming a custom message into it. + +See [Skipping Test Execution](../advanced.md#skipping-test-execution) for more +information. + +### GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST {#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST} + +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(`*`TestSuiteName`*`)` + +Allows the value-parameterized test suite *`TestSuiteName`* to be +uninstantiated. + +By default, every [`TEST_P`](#TEST_P) call without a corresponding +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P) call causes a failing +test in the test suite `GoogleTestVerification`. +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST` suppresses this failure for the +given test suite. + +## Classes and types + +GoogleTest defines the following classes and types to help with writing tests. + +### AssertionResult {#AssertionResult} + +`testing::AssertionResult` + +A class for indicating whether an assertion was successful. + +When the assertion wasn't successful, the `AssertionResult` object stores a +non-empty failure message that can be retrieved with the object's `message()` +method. + +To create an instance of this class, use one of the factory functions +[`AssertionSuccess()`](#AssertionSuccess) or +[`AssertionFailure()`](#AssertionFailure). + +### AssertionException {#AssertionException} + +`testing::AssertionException` + +Exception which can be thrown from +[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). + +### EmptyTestEventListener {#EmptyTestEventListener} + +`testing::EmptyTestEventListener` + +Provides an empty implementation of all methods in the +[`TestEventListener`](#TestEventListener) interface, such that a subclass only +needs to override the methods it cares about. + +### Environment {#Environment} + +`testing::Environment` + +Represents a global test environment. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). + +#### Protected Methods {#Environment-protected} + +##### SetUp {#Environment::SetUp} + +`virtual void Environment::SetUp()` + +Override this to define how to set up the environment. + +##### TearDown {#Environment::TearDown} + +`virtual void Environment::TearDown()` + +Override this to define how to tear down the environment. + +### ScopedTrace {#ScopedTrace} + +`testing::ScopedTrace` + +An instance of this class causes a trace to be included in every test failure +message generated by code in the scope of the lifetime of the `ScopedTrace` +instance. The effect is undone with the destruction of the instance. + +The `ScopedTrace` constructor has the following form: + +```cpp +template +ScopedTrace(const char* file, int line, const T& message) +``` + +Example usage: + +```cpp +testing::ScopedTrace trace("file.cc", 123, "message"); +``` + +The resulting trace includes the given source file path and line number, and the +given message. The `message` argument can be anything streamable to +`std::ostream`. + +See also [`SCOPED_TRACE`](#SCOPED_TRACE). + +### Test {#Test} + +`testing::Test` + +The abstract class that all tests inherit from. `Test` is not copyable. + +#### Public Methods {#Test-public} + +##### SetUpTestSuite {#Test::SetUpTestSuite} + +`static void Test::SetUpTestSuite()` + +Performs shared setup for all tests in the test suite. GoogleTest calls +`SetUpTestSuite()` before running the first test in the test suite. + +##### TearDownTestSuite {#Test::TearDownTestSuite} + +`static void Test::TearDownTestSuite()` + +Performs shared teardown for all tests in the test suite. GoogleTest calls +`TearDownTestSuite()` after running the last test in the test suite. + +##### HasFatalFailure {#Test::HasFatalFailure} + +`static bool Test::HasFatalFailure()` + +Returns true if and only if the current test has a fatal failure. + +##### HasNonfatalFailure {#Test::HasNonfatalFailure} + +`static bool Test::HasNonfatalFailure()` + +Returns true if and only if the current test has a nonfatal failure. + +##### HasFailure {#Test::HasFailure} + +`static bool Test::HasFailure()` + +Returns true if and only if the current test has any failure, either fatal or +nonfatal. + +##### IsSkipped {#Test::IsSkipped} + +`static bool Test::IsSkipped()` + +Returns true if and only if the current test was skipped. + +##### RecordProperty {#Test::RecordProperty} + +`static void Test::RecordProperty(const std::string& key, const std::string& +value)` \ +`static void Test::RecordProperty(const std::string& key, int value)` + +Logs a property for the current test, test suite, or entire invocation of the +test program. Only the last value for a given key is logged. + +The key must be a valid XML attribute name, and cannot conflict with the ones +already used by GoogleTest (`name`, `file`, `line`, `status`, `time`, +`classname`, `type_param`, and `value_param`). + +`RecordProperty` is `public static` so it can be called from utility functions +that are not members of the test fixture. + +Calls to `RecordProperty` made during the lifespan of the test (from the moment +its constructor starts to the moment its destructor finishes) are output in XML +as attributes of the `` element. Properties recorded from a fixture's +`SetUpTestSuite` or `TearDownTestSuite` methods are logged as attributes of the +corresponding `` element. Calls to `RecordProperty` made in the +global context (before or after invocation of `RUN_ALL_TESTS` or from the +`SetUp`/`TearDown` methods of registered `Environment` objects) are output as +attributes of the `` element. + +#### Protected Methods {#Test-protected} + +##### SetUp {#Test::SetUp} + +`virtual void Test::SetUp()` + +Override this to perform test fixture setup. GoogleTest calls `SetUp()` before +running each individual test. + +##### TearDown {#Test::TearDown} + +`virtual void Test::TearDown()` + +Override this to perform test fixture teardown. GoogleTest calls `TearDown()` +after running each individual test. + +### TestWithParam {#TestWithParam} + +`testing::TestWithParam` + +A convenience class which inherits from both [`Test`](#Test) and +[`WithParamInterface`](#WithParamInterface). + +### TestSuite {#TestSuite} + +Represents a test suite. `TestSuite` is not copyable. + +#### Public Methods {#TestSuite-public} + +##### name {#TestSuite::name} + +`const char* TestSuite::name() const` + +Gets the name of the test suite. + +##### type_param {#TestSuite::type_param} + +`const char* TestSuite::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test suite. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### should_run {#TestSuite::should_run} + +`bool TestSuite::should_run() const` + +Returns true if any test in this test suite should run. + +##### successful_test_count {#TestSuite::successful_test_count} + +`int TestSuite::successful_test_count() const` + +Gets the number of successful tests in this test suite. + +##### skipped_test_count {#TestSuite::skipped_test_count} + +`int TestSuite::skipped_test_count() const` + +Gets the number of skipped tests in this test suite. + +##### failed_test_count {#TestSuite::failed_test_count} + +`int TestSuite::failed_test_count() const` + +Gets the number of failed tests in this test suite. + +##### reportable_disabled_test_count {#TestSuite::reportable_disabled_test_count} + +`int TestSuite::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#TestSuite::disabled_test_count} + +`int TestSuite::disabled_test_count() const` + +Gets the number of disabled tests in this test suite. + +##### reportable_test_count {#TestSuite::reportable_test_count} + +`int TestSuite::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### test_to_run_count {#TestSuite::test_to_run_count} + +`int TestSuite::test_to_run_count() const` + +Get the number of tests in this test suite that should run. + +##### total_test_count {#TestSuite::total_test_count} + +`int TestSuite::total_test_count() const` + +Gets the number of all tests in this test suite. + +##### Passed {#TestSuite::Passed} + +`bool TestSuite::Passed() const` + +Returns true if and only if the test suite passed. + +##### Failed {#TestSuite::Failed} + +`bool TestSuite::Failed() const` + +Returns true if and only if the test suite failed. + +##### elapsed_time {#TestSuite::elapsed_time} + +`TimeInMillis TestSuite::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestSuite::start_timestamp} + +`TimeInMillis TestSuite::start_timestamp() const` + +Gets the time of the test suite start, in ms from the start of the UNIX epoch. + +##### GetTestInfo {#TestSuite::GetTestInfo} + +`const TestInfo* TestSuite::GetTestInfo(int i) const` + +Returns the [`TestInfo`](#TestInfo) for the `i`-th test among all the tests. `i` +can range from 0 to `total_test_count() - 1`. If `i` is not in that range, +returns `NULL`. + +##### ad_hoc_test_result {#TestSuite::ad_hoc_test_result} + +`const TestResult& TestSuite::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) that holds test properties recorded +during execution of `SetUpTestSuite` and `TearDownTestSuite`. + +### TestInfo {#TestInfo} + +`testing::TestInfo` + +Stores information about a test. + +#### Public Methods {#TestInfo-public} + +##### test_suite_name {#TestInfo::test_suite_name} + +`const char* TestInfo::test_suite_name() const` + +Returns the test suite name. + +##### name {#TestInfo::name} + +`const char* TestInfo::name() const` + +Returns the test name. + +##### type_param {#TestInfo::type_param} + +`const char* TestInfo::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### value_param {#TestInfo::value_param} + +`const char* TestInfo::value_param() const` + +Returns the text representation of the value parameter, or `NULL` if this is not +a value-parameterized test. See +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +##### file {#TestInfo::file} + +`const char* TestInfo::file() const` + +Returns the file name where this test is defined. + +##### line {#TestInfo::line} + +`int TestInfo::line() const` + +Returns the line where this test is defined. + +##### is_in_another_shard {#TestInfo::is_in_another_shard} + +`bool TestInfo::is_in_another_shard() const` + +Returns true if this test should not be run because it's in another shard. + +##### should_run {#TestInfo::should_run} + +`bool TestInfo::should_run() const` + +Returns true if this test should run, that is if the test is not disabled (or it +is disabled but the `also_run_disabled_tests` flag has been specified) and its +full name matches the user-specified filter. + +GoogleTest allows the user to filter the tests by their full names. Only the +tests that match the filter will run. See +[Running a Subset of the Tests](../advanced.md#running-a-subset-of-the-tests) +for more information. + +##### is_reportable {#TestInfo::is_reportable} + +`bool TestInfo::is_reportable() const` + +Returns true if and only if this test will appear in the XML report. + +##### result {#TestInfo::result} + +`const TestResult* TestInfo::result() const` + +Returns the result of the test. See [`TestResult`](#TestResult). + +### TestParamInfo {#TestParamInfo} + +`testing::TestParamInfo` + +Describes a parameter to a value-parameterized test. The type `T` is the type of +the parameter. + +Contains the fields `param` and `index` which hold the value of the parameter +and its integer index respectively. + +### UnitTest {#UnitTest} + +`testing::UnitTest` + +This class contains information about the test program. + +`UnitTest` is a singleton class. The only instance is created when +`UnitTest::GetInstance()` is first called. This instance is never deleted. + +`UnitTest` is not copyable. + +#### Public Methods {#UnitTest-public} + +##### GetInstance {#UnitTest::GetInstance} + +`static UnitTest* UnitTest::GetInstance()` + +Gets the singleton `UnitTest` object. The first time this method is called, a +`UnitTest` object is constructed and returned. Consecutive calls will return the +same object. + +##### original_working_dir {#UnitTest::original_working_dir} + +`const char* UnitTest::original_working_dir() const` + +Returns the working directory when the first [`TEST()`](#TEST) or +[`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string. + +##### current_test_suite {#UnitTest::current_test_suite} + +`const TestSuite* UnitTest::current_test_suite() const` + +Returns the [`TestSuite`](#TestSuite) object for the test that's currently +running, or `NULL` if no test is running. + +##### current_test_info {#UnitTest::current_test_info} + +`const TestInfo* UnitTest::current_test_info() const` + +Returns the [`TestInfo`](#TestInfo) object for the test that's currently +running, or `NULL` if no test is running. + +##### random_seed {#UnitTest::random_seed} + +`int UnitTest::random_seed() const` + +Returns the random seed used at the start of the current test run. + +##### successful_test_suite_count {#UnitTest::successful_test_suite_count} + +`int UnitTest::successful_test_suite_count() const` + +Gets the number of successful test suites. + +##### failed_test_suite_count {#UnitTest::failed_test_suite_count} + +`int UnitTest::failed_test_suite_count() const` + +Gets the number of failed test suites. + +##### total_test_suite_count {#UnitTest::total_test_suite_count} + +`int UnitTest::total_test_suite_count() const` + +Gets the number of all test suites. + +##### test_suite_to_run_count {#UnitTest::test_suite_to_run_count} + +`int UnitTest::test_suite_to_run_count() const` + +Gets the number of all test suites that contain at least one test that should +run. + +##### successful_test_count {#UnitTest::successful_test_count} + +`int UnitTest::successful_test_count() const` + +Gets the number of successful tests. + +##### skipped_test_count {#UnitTest::skipped_test_count} + +`int UnitTest::skipped_test_count() const` + +Gets the number of skipped tests. + +##### failed_test_count {#UnitTest::failed_test_count} + +`int UnitTest::failed_test_count() const` + +Gets the number of failed tests. + +##### reportable_disabled_test_count {#UnitTest::reportable_disabled_test_count} + +`int UnitTest::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#UnitTest::disabled_test_count} + +`int UnitTest::disabled_test_count() const` + +Gets the number of disabled tests. + +##### reportable_test_count {#UnitTest::reportable_test_count} + +`int UnitTest::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### total_test_count {#UnitTest::total_test_count} + +`int UnitTest::total_test_count() const` + +Gets the number of all tests. + +##### test_to_run_count {#UnitTest::test_to_run_count} + +`int UnitTest::test_to_run_count() const` + +Gets the number of tests that should run. + +##### start_timestamp {#UnitTest::start_timestamp} + +`TimeInMillis UnitTest::start_timestamp() const` + +Gets the time of the test program start, in ms from the start of the UNIX epoch. + +##### elapsed_time {#UnitTest::elapsed_time} + +`TimeInMillis UnitTest::elapsed_time() const` + +Gets the elapsed time, in milliseconds. + +##### Passed {#UnitTest::Passed} + +`bool UnitTest::Passed() const` + +Returns true if and only if the unit test passed (i.e. all test suites passed). + +##### Failed {#UnitTest::Failed} + +`bool UnitTest::Failed() const` + +Returns true if and only if the unit test failed (i.e. some test suite failed or +something outside of all tests failed). + +##### GetTestSuite {#UnitTest::GetTestSuite} + +`const TestSuite* UnitTest::GetTestSuite(int i) const` + +Gets the [`TestSuite`](#TestSuite) object for the `i`-th test suite among all +the test suites. `i` can range from 0 to `total_test_suite_count() - 1`. If `i` +is not in that range, returns `NULL`. + +##### ad_hoc_test_result {#UnitTest::ad_hoc_test_result} + +`const TestResult& UnitTest::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) containing information on test failures +and properties logged outside of individual test suites. + +##### listeners {#UnitTest::listeners} + +`TestEventListeners& UnitTest::listeners()` + +Returns the list of event listeners that can be used to track events inside +GoogleTest. See [`TestEventListeners`](#TestEventListeners). + +### TestEventListener {#TestEventListener} + +`testing::TestEventListener` + +The interface for tracing execution of tests. The methods below are listed in +the order the corresponding events are fired. + +#### Public Methods {#TestEventListener-public} + +##### OnTestProgramStart {#TestEventListener::OnTestProgramStart} + +`virtual void TestEventListener::OnTestProgramStart(const UnitTest& unit_test)` + +Fired before any test activity starts. + +##### OnTestIterationStart {#TestEventListener::OnTestIterationStart} + +`virtual void TestEventListener::OnTestIterationStart(const UnitTest& unit_test, +int iteration)` + +Fired before each iteration of tests starts. There may be more than one +iteration if `GTEST_FLAG(repeat)` is set. `iteration` is the iteration index, +starting from 0. + +##### OnEnvironmentsSetUpStart {#TestEventListener::OnEnvironmentsSetUpStart} + +`virtual void TestEventListener::OnEnvironmentsSetUpStart(const UnitTest& +unit_test)` + +Fired before environment set-up for each iteration of tests starts. + +##### OnEnvironmentsSetUpEnd {#TestEventListener::OnEnvironmentsSetUpEnd} + +`virtual void TestEventListener::OnEnvironmentsSetUpEnd(const UnitTest& +unit_test)` + +Fired after environment set-up for each iteration of tests ends. + +##### OnTestSuiteStart {#TestEventListener::OnTestSuiteStart} + +`virtual void TestEventListener::OnTestSuiteStart(const TestSuite& test_suite)` + +Fired before the test suite starts. + +##### OnTestStart {#TestEventListener::OnTestStart} + +`virtual void TestEventListener::OnTestStart(const TestInfo& test_info)` + +Fired before the test starts. + +##### OnTestPartResult {#TestEventListener::OnTestPartResult} + +`virtual void TestEventListener::OnTestPartResult(const TestPartResult& +test_part_result)` + +Fired after a failed assertion or a `SUCCEED()` invocation. If you want to throw +an exception from this function to skip to the next test, it must be an +[`AssertionException`](#AssertionException) or inherited from it. + +##### OnTestEnd {#TestEventListener::OnTestEnd} + +`virtual void TestEventListener::OnTestEnd(const TestInfo& test_info)` + +Fired after the test ends. + +##### OnTestSuiteEnd {#TestEventListener::OnTestSuiteEnd} + +`virtual void TestEventListener::OnTestSuiteEnd(const TestSuite& test_suite)` + +Fired after the test suite ends. + +##### OnEnvironmentsTearDownStart {#TestEventListener::OnEnvironmentsTearDownStart} + +`virtual void TestEventListener::OnEnvironmentsTearDownStart(const UnitTest& +unit_test)` + +Fired before environment tear-down for each iteration of tests starts. + +##### OnEnvironmentsTearDownEnd {#TestEventListener::OnEnvironmentsTearDownEnd} + +`virtual void TestEventListener::OnEnvironmentsTearDownEnd(const UnitTest& +unit_test)` + +Fired after environment tear-down for each iteration of tests ends. + +##### OnTestIterationEnd {#TestEventListener::OnTestIterationEnd} + +`virtual void TestEventListener::OnTestIterationEnd(const UnitTest& unit_test, +int iteration)` + +Fired after each iteration of tests finishes. + +##### OnTestProgramEnd {#TestEventListener::OnTestProgramEnd} + +`virtual void TestEventListener::OnTestProgramEnd(const UnitTest& unit_test)` + +Fired after all test activities have ended. + +### TestEventListeners {#TestEventListeners} + +`testing::TestEventListeners` + +Lets users add listeners to track events in GoogleTest. + +#### Public Methods {#TestEventListeners-public} + +##### Append {#TestEventListeners::Append} + +`void TestEventListeners::Append(TestEventListener* listener)` + +Appends an event listener to the end of the list. GoogleTest assumes ownership +of the listener (i.e. it will delete the listener when the test program +finishes). + +##### Release {#TestEventListeners::Release} + +`TestEventListener* TestEventListeners::Release(TestEventListener* listener)` + +Removes the given event listener from the list and returns it. It then becomes +the caller's responsibility to delete the listener. Returns `NULL` if the +listener is not found in the list. + +##### default_result_printer {#TestEventListeners::default_result_printer} + +`TestEventListener* TestEventListeners::default_result_printer() const` + +Returns the standard listener responsible for the default console output. Can be +removed from the listeners list to shut down default console output. Note that +removing this object from the listener list with +[`Release()`](#TestEventListeners::Release) transfers its ownership to the +caller and makes this function return `NULL` the next time. + +##### default_xml_generator {#TestEventListeners::default_xml_generator} + +`TestEventListener* TestEventListeners::default_xml_generator() const` + +Returns the standard listener responsible for the default XML output controlled +by the `--gtest_output=xml` flag. Can be removed from the listeners list by +users who want to shut down the default XML output controlled by this flag and +substitute it with custom one. Note that removing this object from the listener +list with [`Release()`](#TestEventListeners::Release) transfers its ownership to +the caller and makes this function return `NULL` the next time. + +### TestPartResult {#TestPartResult} + +`testing::TestPartResult` + +A copyable object representing the result of a test part (i.e. an assertion or +an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). + +#### Public Methods {#TestPartResult-public} + +##### type {#TestPartResult::type} + +`Type TestPartResult::type() const` + +Gets the outcome of the test part. + +The return type `Type` is an enum defined as follows: + +```cpp +enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure, // Failed and the test should be terminated. + kSkip // Skipped. +}; +``` + +##### file_name {#TestPartResult::file_name} + +`const char* TestPartResult::file_name() const` + +Gets the name of the source file where the test part took place, or `NULL` if +it's unknown. + +##### line_number {#TestPartResult::line_number} + +`int TestPartResult::line_number() const` + +Gets the line in the source file where the test part took place, or `-1` if it's +unknown. + +##### summary {#TestPartResult::summary} + +`const char* TestPartResult::summary() const` + +Gets the summary of the failure message. + +##### message {#TestPartResult::message} + +`const char* TestPartResult::message() const` + +Gets the message associated with the test part. + +##### skipped {#TestPartResult::skipped} + +`bool TestPartResult::skipped() const` + +Returns true if and only if the test part was skipped. + +##### passed {#TestPartResult::passed} + +`bool TestPartResult::passed() const` + +Returns true if and only if the test part passed. + +##### nonfatally_failed {#TestPartResult::nonfatally_failed} + +`bool TestPartResult::nonfatally_failed() const` + +Returns true if and only if the test part non-fatally failed. + +##### fatally_failed {#TestPartResult::fatally_failed} + +`bool TestPartResult::fatally_failed() const` + +Returns true if and only if the test part fatally failed. + +##### failed {#TestPartResult::failed} + +`bool TestPartResult::failed() const` + +Returns true if and only if the test part failed. + +### TestProperty {#TestProperty} + +`testing::TestProperty` + +A copyable object representing a user-specified test property which can be +output as a key/value string pair. + +#### Public Methods {#TestProperty-public} + +##### key {#key} + +`const char* key() const` + +Gets the user-supplied key. + +##### value {#value} + +`const char* value() const` + +Gets the user-supplied value. + +##### SetValue {#SetValue} + +`void SetValue(const std::string& new_value)` + +Sets a new value, overriding the previous one. + +### TestResult {#TestResult} + +`testing::TestResult` + +Contains information about the result of a single test. + +`TestResult` is not copyable. + +#### Public Methods {#TestResult-public} + +##### total_part_count {#TestResult::total_part_count} + +`int TestResult::total_part_count() const` + +Gets the number of all test parts. This is the sum of the number of successful +test parts and the number of failed test parts. + +##### test_property_count {#TestResult::test_property_count} + +`int TestResult::test_property_count() const` + +Returns the number of test properties. + +##### Passed {#TestResult::Passed} + +`bool TestResult::Passed() const` + +Returns true if and only if the test passed (i.e. no test part failed). + +##### Skipped {#TestResult::Skipped} + +`bool TestResult::Skipped() const` + +Returns true if and only if the test was skipped. + +##### Failed {#TestResult::Failed} + +`bool TestResult::Failed() const` + +Returns true if and only if the test failed. + +##### HasFatalFailure {#TestResult::HasFatalFailure} + +`bool TestResult::HasFatalFailure() const` + +Returns true if and only if the test fatally failed. + +##### HasNonfatalFailure {#TestResult::HasNonfatalFailure} + +`bool TestResult::HasNonfatalFailure() const` + +Returns true if and only if the test has a non-fatal failure. + +##### elapsed_time {#TestResult::elapsed_time} + +`TimeInMillis TestResult::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestResult::start_timestamp} + +`TimeInMillis TestResult::start_timestamp() const` + +Gets the time of the test case start, in ms from the start of the UNIX epoch. + +##### GetTestPartResult {#TestResult::GetTestPartResult} + +`const TestPartResult& TestResult::GetTestPartResult(int i) const` + +Returns the [`TestPartResult`](#TestPartResult) for the `i`-th test part result +among all the results. `i` can range from 0 to `total_part_count() - 1`. If `i` +is not in that range, aborts the program. + +##### GetTestProperty {#TestResult::GetTestProperty} + +`const TestProperty& TestResult::GetTestProperty(int i) const` + +Returns the [`TestProperty`](#TestProperty) object for the `i`-th test property. +`i` can range from 0 to `test_property_count() - 1`. If `i` is not in that +range, aborts the program. + +### TimeInMillis {#TimeInMillis} + +`testing::TimeInMillis` + +An integer type representing time in milliseconds. + +### Types {#Types} + +`testing::Types` + +Represents a list of types for use in typed tests and type-parameterized tests. + +The template argument `T...` can be any number of types, for example: + +``` +testing::Types +``` + +See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### WithParamInterface {#WithParamInterface} + +`testing::WithParamInterface` + +The pure interface class that all value-parameterized tests inherit from. + +A value-parameterized test fixture class must inherit from both [`Test`](#Test) +and `WithParamInterface`. In most cases that just means inheriting from +[`TestWithParam`](#TestWithParam), but more complicated test hierarchies may +need to inherit from `Test` and `WithParamInterface` at different levels. + +This interface defines the type alias `ParamType` for the parameter type `T` and +has support for accessing the test parameter value via the `GetParam()` method: + +``` +static const ParamType& GetParam() +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +## Functions + +GoogleTest defines the following functions to help with writing and running +tests. + +### InitGoogleTest {#InitGoogleTest} + +`void testing::InitGoogleTest(int* argc, char** argv)` \ +`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \ +`void testing::InitGoogleTest()` + +Initializes GoogleTest. This must be called before calling +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line +for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it +is removed from `argv`, and `*argc` is decremented. Keep in mind that `argv` +must terminate with a `NULL` pointer (i.e. `argv[argc]` is `NULL`), which is +already the case with the default `argv` passed to `main`. + +No value is returned. Instead, the GoogleTest flag variables are updated. + +The `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows +programs compiled in `UNICODE` mode. + +The argument-less `InitGoogleTest()` overload can be used on Arduino/embedded +platforms where there is no `argc`/`argv`. + +### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} + +`Environment* testing::AddGlobalTestEnvironment(Environment* env)` + +Adds a test environment to the test program. Must be called before +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down) for +more information. + +See also [`Environment`](#Environment). + +### RegisterTest {#RegisterTest} + +```cpp +template +TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory) +``` + +Dynamically registers a test with the framework. + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the `Test` object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` methods for it. + +Must be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is invoked, otherwise +behavior is undefined. + +See +[Registering tests programmatically](../advanced.md#registering-tests-programmatically) +for more information. + +### RUN_ALL_TESTS {#RUN_ALL_TESTS} + +`int RUN_ALL_TESTS()` + +Use this function in `main()` to run all tests. It returns `0` if all tests are +successful, or `1` otherwise. + +`RUN_ALL_TESTS()` should be invoked after the command line has been parsed by +[`InitGoogleTest()`](#InitGoogleTest). + +This function was formerly a macro; thus, it is in the global namespace and has +an all-caps name. + +### AssertionSuccess {#AssertionSuccess} + +`AssertionResult testing::AssertionSuccess()` + +Creates a successful assertion result. See +[`AssertionResult`](#AssertionResult). + +### AssertionFailure {#AssertionFailure} + +`AssertionResult testing::AssertionFailure()` + +Creates a failed assertion result. Use the `<<` operator to store a failure +message: + +```cpp +testing::AssertionFailure() << "My failure message"; +``` + +See [`AssertionResult`](#AssertionResult). + +### StaticAssertTypeEq {#StaticAssertTypeEq} + +`testing::StaticAssertTypeEq()` + +Compile-time assertion for type equality. Compiles if and only if `T1` and `T2` +are the same type. The value it returns is irrelevant. + +See [Type Assertions](../advanced.md#type-assertions) for more information. + +### PrintToString {#PrintToString} + +`std::string testing::PrintToString(x)` + +Prints any value `x` using GoogleTest's value printer. + +See +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values) +for more information. + +### PrintToStringParamName {#PrintToStringParamName} + +`std::string testing::PrintToStringParamName(TestParamInfo& info)` + +A built-in parameterized test name generator which returns the result of +[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the +test parameter is a `std::string` or C string. See +[Specifying Names for Value-Parameterized Test Parameters](../advanced.md#specifying-names-for-value-parameterized-test-parameters) +for more information. + +See also [`TestParamInfo`](#TestParamInfo) and +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). diff --git a/sw/restatdesk_tests/googletest/docs/samples.md b/sw/restatdesk_tests/googletest/docs/samples.md new file mode 100644 index 0000000..dedc590 --- /dev/null +++ b/sw/restatdesk_tests/googletest/docs/samples.md @@ -0,0 +1,22 @@ +# Googletest Samples + +If you're like us, you'd like to look at +[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples) +The sample directory has a number of well-commented samples showing how to use a +variety of googletest features. + +* Sample #1 shows the basic steps of using googletest to test C++ functions. +* Sample #2 shows a more complex unit test for a class with multiple member + functions. +* Sample #3 uses a test fixture. +* Sample #4 teaches you how to use googletest and `googletest.h` together to + get the best of both libraries. +* Sample #5 puts shared testing logic in a base test fixture, and reuses it in + derived fixtures. +* Sample #6 demonstrates type-parameterized tests. +* Sample #7 teaches the basics of value-parameterized tests. +* Sample #8 shows using `Combine()` in value-parameterized tests. +* Sample #9 shows use of the listener API to modify Google Test's console + output and the use of its reflection API to inspect test results. +* Sample #10 shows use of the listener API to implement a primitive memory + leak checker. diff --git a/sw/restatdesk_tests/googletest/fake_fuchsia_sdk.bzl b/sw/restatdesk_tests/googletest/fake_fuchsia_sdk.bzl new file mode 100644 index 0000000..bc5b927 --- /dev/null +++ b/sw/restatdesk_tests/googletest/fake_fuchsia_sdk.bzl @@ -0,0 +1,61 @@ +"""Provides a fake @fuchsia_sdk implementation that's used when the real one isn't available. + +GoogleTest can be used with the [Fuchsia](https://fuchsia.dev/) SDK. However, +because the Fuchsia SDK does not yet support bzlmod, GoogleTest's `MODULE.bazel` +file by default provides a "fake" Fuchsia SDK. + +To override this and use the real Fuchsia SDK, you can add the following to your +project's `MODULE.bazel` file: + + fake_fuchsia_sdk_extension = + use_extension("@com_google_googletest//:fake_fuchsia_sdk.bzl", "fuchsia_sdk") + override_repo(fake_fuchsia_sdk_extension, "fuchsia_sdk") + +NOTE: The `override_repo` built-in is only available in Bazel 8.0 and higher. + +See https://github.com/google/googletest/issues/4472 for more details of why the +fake Fuchsia SDK is needed. +""" + +def _fake_fuchsia_sdk_impl(repo_ctx): + for stub_target in repo_ctx.attr._stub_build_targets: + stub_package = stub_target + stub_target_name = stub_target.split("/")[-1] + repo_ctx.file("%s/BUILD.bazel" % stub_package, """ +filegroup( + name = "%s", +) +""" % stub_target_name) + +fake_fuchsia_sdk = repository_rule( + doc = "Used to create a fake @fuchsia_sdk repository with stub build targets.", + implementation = _fake_fuchsia_sdk_impl, + attrs = { + "_stub_build_targets": attr.string_list( + doc = "The stub build targets to initialize.", + default = [ + "pkg/fdio", + "pkg/syslog", + "pkg/zx", + ], + ), + }, +) + +_create_fake = tag_class() + +def _fuchsia_sdk_impl(module_ctx): + create_fake_sdk = False + for mod in module_ctx.modules: + for _ in mod.tags.create_fake: + create_fake_sdk = True + + if create_fake_sdk: + fake_fuchsia_sdk(name = "fuchsia_sdk") + + return module_ctx.extension_metadata(reproducible = True) + +fuchsia_sdk = module_extension( + implementation = _fuchsia_sdk_impl, + tag_classes = {"create_fake": _create_fake}, +) diff --git a/sw/restatdesk_tests/googletest/googlemock/CMakeLists.txt b/sw/restatdesk_tests/googletest/googlemock/CMakeLists.txt new file mode 100644 index 0000000..99b2411 --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/CMakeLists.txt @@ -0,0 +1,210 @@ +######################################################################## +# Note: CMake support is community-based. The maintainers do not use CMake +# internally. +# +# CMake build script for Google Mock. +# +# To run the tests for Google Mock itself on Linux, use 'make test' or +# ctest. You can select which tests to run using 'ctest -R regex'. +# For more options, run 'ctest --help'. + +option(gmock_build_tests "Build all of Google Mock's own tests." OFF) + +# A directory to find Google Test sources. +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt") + set(gtest_dir gtest) +else() + set(gtest_dir ../googletest) +endif() + +# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). +include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL) + +if (COMMAND pre_project_set_up_hermetic_build) + # Google Test also calls hermetic setup functions from add_subdirectory, + # although its changes will not affect things at the current scope. + pre_project_set_up_hermetic_build() +endif() + +######################################################################## +# +# Project-wide settings + +# Name of the project. +# +# CMake files in this project can refer to the root source directory +# as ${gmock_SOURCE_DIR} and to the root binary directory as +# ${gmock_BINARY_DIR}. +# Language "C" is required for find_package(Threads). +cmake_minimum_required(VERSION 3.13) +project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) + +if (COMMAND set_up_hermetic_build) + set_up_hermetic_build() +endif() + +# Instructs CMake to process Google Test's CMakeLists.txt and add its +# targets to the current scope. We are placing Google Test's binary +# directory in a subdirectory of our own as VC compilation may break +# if they are the same (the default). +add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}") + + +# These commands only run if this is the main project +if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") + # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to + # make it prominent in the GUI. + option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) +else() + mark_as_advanced(gmock_build_tests) +endif() + +# Although Google Test's CMakeLists.txt calls this function, the +# changes there don't affect the current scope. Therefore we have to +# call it again here. +config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake + +# Adds Google Mock's and Google Test's header directories to the search path. +# Get Google Test's include dirs from the target, gtest_SOURCE_DIR is broken +# when using fetch-content with the name "GTest". +get_target_property(gtest_include_dirs gtest INCLUDE_DIRECTORIES) +set(gmock_build_include_dirs + "${gmock_SOURCE_DIR}/include" + "${gmock_SOURCE_DIR}" + "${gtest_include_dirs}") +include_directories(${gmock_build_include_dirs}) + +######################################################################## +# +# Defines the gmock & gmock_main libraries. User tests should link +# with one of them. + +# Google Mock libraries. We build them using more strict warnings than what +# are used for other targets, to ensure that Google Mock can be compiled by +# a user aggressive about warnings. +if (MSVC) + cxx_library(gmock + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc) + + cxx_library(gmock_main + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc + src/gmock_main.cc) +else() + cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) + target_link_libraries(gmock PUBLIC gtest) + set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION}) + cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) + target_link_libraries(gmock_main PUBLIC gmock) + set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) +endif() + +string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") +target_include_directories(gmock SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +target_include_directories(gmock_main SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") + +######################################################################## +# +# Install rules. +install_project(gmock gmock_main) + +######################################################################## +# +# Google Mock's own tests. +# +# You can skip this section if you aren't interested in testing +# Google Mock itself. +# +# The tests are not built by default. To build them, set the +# gmock_build_tests option to ON. You can do it by running ccmake +# or specifying the -Dgmock_build_tests=ON flag when running cmake. + +if (gmock_build_tests) + # This must be set in the root directory for the tests to be run by + # 'make test' or ctest. + enable_testing() + + if (MINGW OR CYGWIN) + add_compile_options("-Wa,-mbig-obj") + endif() + + ############################################################ + # C++ tests built with standard compiler flags. + + cxx_test(gmock-actions_test gmock_main) + cxx_test(gmock-cardinalities_test gmock_main) + cxx_test(gmock_ex_test gmock_main) + cxx_test(gmock-function-mocker_test gmock_main) + cxx_test(gmock-internal-utils_test gmock_main) + cxx_test(gmock-matchers-arithmetic_test gmock_main) + cxx_test(gmock-matchers-comparisons_test gmock_main) + cxx_test(gmock-matchers-containers_test gmock_main) + cxx_test(gmock-matchers-misc_test gmock_main) + cxx_test(gmock-more-actions_test gmock_main) + cxx_test(gmock-nice-strict_test gmock_main) + cxx_test(gmock-port_test gmock_main) + cxx_test(gmock-spec-builders_test gmock_main) + cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc) + cxx_test(gmock_test gmock_main) + + if (DEFINED GTEST_HAS_PTHREAD) + cxx_test(gmock_stress_test gmock) + endif() + + # gmock_all_test is commented to save time building and running tests. + # Uncomment if necessary. + # cxx_test(gmock_all_test gmock_main) + + ############################################################ + # C++ tests built with non-standard compiler flags. + + if (MSVC) + cxx_library(gmock_main_no_exception "${cxx_no_exception}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + else() + cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_exception PUBLIC gmock) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_rtti PUBLIC gmock) + endif() + cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" + gmock_main_no_exception test/gmock-more-actions_test.cc) + + cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}" + gmock_main_no_rtti test/gmock-spec-builders_test.cc) + + cxx_shared_library(shared_gmock_main "${cxx_default}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + # Tests that a binary can be built with Google Mock as a shared library. On + # some system configurations, it may not possible to run the binary without + # knowing more details about the system configurations. We do not try to run + # this binary. To get a more robust shared library coverage, configure with + # -DBUILD_SHARED_LIBS=ON. + cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}" + shared_gmock_main test/gmock-spec-builders_test.cc) + set_target_properties(shared_gmock_test_ + PROPERTIES + COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") + + ############################################################ + # Python tests. + + cxx_executable(gmock_leak_test_ test gmock_main) + py_test(gmock_leak_test) + + cxx_executable(gmock_output_test_ test gmock) + py_test(gmock_output_test) +endif() diff --git a/sw/restatdesk_tests/googletest/googlemock/README.md b/sw/restatdesk_tests/googletest/googlemock/README.md new file mode 100644 index 0000000..e1103b1 --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/README.md @@ -0,0 +1,40 @@ +# Googletest Mocking (gMock) Framework + +### Overview + +Google's framework for writing and using C++ mock classes. It can help you +derive better designs of your system and write better tests. + +It is inspired by: + +* [jMock](http://www.jmock.org/) +* [EasyMock](https://easymock.org/) +* [Hamcrest](https://code.google.com/p/hamcrest/) + +It is designed with C++'s specifics in mind. + +gMock: + +- Provides a declarative syntax for defining mocks. +- Can define partial (hybrid) mocks, which are a cross of real and mock + objects. +- Handles functions of arbitrary types and overloaded functions. +- Comes with a rich set of matchers for validating function arguments. +- Uses an intuitive syntax for controlling the behavior of a mock. +- Does automatic verification of expectations (no record-and-replay needed). +- Allows arbitrary (partial) ordering constraints on function calls to be + expressed. +- Lets a user extend it by defining new matchers and actions. +- Does not use exceptions. +- Is easy to learn and use. + +Details and examples can be found here: + +* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html) +* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html) +* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html) +* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) + +GoogleMock is a part of +[GoogleTest C++ testing framework](https://github.com/google/googletest/) and a +subject to the same requirements. diff --git a/sw/restatdesk_tests/googletest/googlemock/cmake/gmock.pc.in b/sw/restatdesk_tests/googletest/googlemock/cmake/gmock.pc.in new file mode 100644 index 0000000..23c67b5 --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/cmake/gmock.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock +Description: GoogleMock (without main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gtest = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/sw/restatdesk_tests/googletest/googlemock/cmake/gmock_main.pc.in b/sw/restatdesk_tests/googletest/googlemock/cmake/gmock_main.pc.in new file mode 100644 index 0000000..66ffea7 --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/cmake/gmock_main.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gmock = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/sw/restatdesk_tests/googletest/googlemock/docs/README.md b/sw/restatdesk_tests/googletest/googlemock/docs/README.md new file mode 100644 index 0000000..1bc57b7 --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/docs/README.md @@ -0,0 +1,4 @@ +# Content Moved + +We are working on updates to the GoogleTest documentation, which has moved to +the top-level [docs](../../docs) directory. diff --git a/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-actions.h b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-actions.h new file mode 100644 index 0000000..5fe50e3 --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-actions.h @@ -0,0 +1,2404 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The ACTION* family of macros can be used in a namespace scope to +// define custom actions easily. The syntax: +// +// ACTION(name) { statements; } +// +// will define an action with the given name that executes the +// statements. The value returned by the statements will be used as +// the return value of the action. Inside the statements, you can +// refer to the K-th (0-based) argument of the mock function by +// 'argK', and refer to its type by 'argK_type'. For example: +// +// ACTION(IncrementArg1) { +// arg1_type temp = arg1; +// return ++(*temp); +// } +// +// allows you to write +// +// ...WillOnce(IncrementArg1()); +// +// You can also refer to the entire argument tuple and its type by +// 'args' and 'args_type', and refer to the mock function type and its +// return type by 'function_type' and 'return_type'. +// +// Note that you don't need to specify the types of the mock function +// arguments. However rest assured that your code is still type-safe: +// you'll get a compiler error if *arg1 doesn't support the ++ +// operator, or if the type of ++(*arg1) isn't compatible with the +// mock function's return type, for example. +// +// Sometimes you'll want to parameterize the action. For that you can use +// another macro: +// +// ACTION_P(name, param_name) { statements; } +// +// For example: +// +// ACTION_P(Add, n) { return arg0 + n; } +// +// will allow you to write: +// +// ...WillOnce(Add(5)); +// +// Note that you don't need to provide the type of the parameter +// either. If you need to reference the type of a parameter named +// 'foo', you can write 'foo_type'. For example, in the body of +// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type +// of 'n'. +// +// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support +// multi-parameter actions. +// +// For the purpose of typing, you can view +// +// ACTION_Pk(Foo, p1, ..., pk) { ... } +// +// as shorthand for +// +// template +// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } +// +// In particular, you can provide the template type arguments +// explicitly when invoking Foo(), as in Foo(5, false); +// although usually you can rely on the compiler to infer the types +// for you automatically. You can assign the result of expression +// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. +// +// You can also overload actions with different numbers of parameters: +// +// ACTION_P(Plus, a) { ... } +// ACTION_P2(Plus, a, b) { ... } +// +// While it's tempting to always use the ACTION* macros when defining +// a new action, you should also consider implementing ActionInterface +// or using MakePolymorphicAction() instead, especially if you need to +// use the action a lot. While these approaches require more work, +// they give you more control on the types of the mock function +// arguments and the action parameters, which in general leads to +// better compiler error messages that pay off in the long run. They +// also allow overloading actions based on parameter types (as opposed +// to just based on the number of parameters). +// +// CAVEAT: +// +// ACTION*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// Users can, however, define any local functors (e.g. a lambda) that +// can be used as actions. +// +// MORE INFORMATION: +// +// To learn more about using these macros, please search for 'ACTION' on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ + +#ifndef _WIN32_WCE +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) + +namespace testing { + +// To implement an action Foo, define: +// 1. a class FooAction that implements the ActionInterface interface, and +// 2. a factory function that creates an Action object from a +// const FooAction*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Action objects can now be copied like plain values. + +namespace internal { + +// BuiltInDefaultValueGetter::Get() returns a +// default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. +// +// This primary template is used when kDefaultConstructible is true. +template +struct BuiltInDefaultValueGetter { + static T Get() { return T(); } +}; +template +struct BuiltInDefaultValueGetter { + static T Get() { + Assert(false, __FILE__, __LINE__, + "Default action undefined for the function return type."); +#if defined(__GNUC__) || defined(__clang__) + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(0); +#else + return Invalid(); + // The above statement will never be reached, but is required in + // order for this function to compile. +#endif + } +}; + +// BuiltInDefaultValue::Get() returns the "built-in" default value +// for type T, which is NULL when T is a raw pointer type, 0 when T is +// a numeric type, false when T is bool, or "" when T is string or +// std::string. In addition, in C++11 and above, it turns a +// default-constructed T value if T is default constructible. For any +// other type T, the built-in default T value is undefined, and the +// function will abort the process. +template +class BuiltInDefaultValue { + public: + // This function returns true if and only if type T has a built-in default + // value. + static bool Exists() { return ::std::is_default_constructible::value; } + + static T Get() { + return BuiltInDefaultValueGetter< + T, ::std::is_default_constructible::value>::Get(); + } +}; + +// This partial specialization says that we use the same built-in +// default value for T and const T. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return BuiltInDefaultValue::Exists(); } + static T Get() { return BuiltInDefaultValue::Get(); } +}; + +// This partial specialization defines the default values for pointer +// types. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return true; } + static T* Get() { return nullptr; } +}; + +// The following specializations define the default values for +// specific types we care about. +#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ + template <> \ + class BuiltInDefaultValue { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ + } + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); + +// There's no need for a default action for signed wchar_t, as that +// type is the same as wchar_t for gcc, and invalid for MSVC. +// +// There's also no need for a default action for unsigned wchar_t, as +// that type is the same as unsigned int for gcc, and invalid for +// MSVC. +#if GMOCK_WCHAR_T_IS_NATIVE_ +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT +#endif + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); + +#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ + +// Partial implementations of metaprogramming types from the standard library +// not available in C++11. + +template +struct negation + // NOLINTNEXTLINE + : std::integral_constant {}; + +// Base case: with zero predicates the answer is always true. +template +struct conjunction : std::true_type {}; + +// With a single predicate, the answer is that predicate. +template +struct conjunction : P1 {}; + +// With multiple predicates the answer is the first predicate if that is false, +// and we recurse otherwise. +template +struct conjunction + : std::conditional, P1>::type {}; + +template +struct disjunction : std::false_type {}; + +template +struct disjunction : P1 {}; + +template +struct disjunction + // NOLINTNEXTLINE + : std::conditional, P1>::type {}; + +template +using void_t = void; + +// Detects whether an expression of type `From` can be implicitly converted to +// `To` according to [conv]. In C++17, [conv]/3 defines this as follows: +// +// An expression e can be implicitly converted to a type T if and only if +// the declaration T t=e; is well-formed, for some invented temporary +// variable t ([dcl.init]). +// +// [conv]/2 implies we can use function argument passing to detect whether this +// initialization is valid. +// +// Note that this is distinct from is_convertible, which requires this be valid: +// +// To test() { +// return declval(); +// } +// +// In particular, is_convertible doesn't give the correct answer when `To` and +// `From` are the same non-moveable type since `declval` will be an rvalue +// reference, defeating the guaranteed copy elision that would otherwise make +// this function work. +// +// REQUIRES: `From` is not cv void. +template +struct is_implicitly_convertible { + private: + // A function that accepts a parameter of type T. This can be called with type + // U successfully only if U is implicitly convertible to T. + template + static void Accept(T); + + // A function that creates a value of type T. + template + static T Make(); + + // An overload be selected when implicit conversion from T to To is possible. + template (Make()))> + static std::true_type TestImplicitConversion(int); + + // A fallback overload selected in all other cases. + template + static std::false_type TestImplicitConversion(...); + + public: + using type = decltype(TestImplicitConversion(0)); + static constexpr bool value = type::value; +}; + +// Like std::invoke_result_t from C++17, but works only for objects with call +// operators (not e.g. member function pointers, which we don't need specific +// support for in OnceAction because std::function deals with them). +template +using call_result_t = decltype(std::declval()(std::declval()...)); + +template +struct is_callable_r_impl : std::false_type {}; + +// Specialize the struct for those template arguments where call_result_t is +// well-formed. When it's not, the generic template above is chosen, resulting +// in std::false_type. +template +struct is_callable_r_impl>, R, F, Args...> + : std::conditional< + std::is_void::value, // + std::true_type, // + is_implicitly_convertible, R>>::type {}; + +// Like std::is_invocable_r from C++17, but works only for objects with call +// operators. See the note on call_result_t. +template +using is_callable_r = is_callable_r_impl; + +// Like std::as_const from C++17. +template +typename std::add_const::type& as_const(T& t) { + return t; +} + +} // namespace internal + +// Specialized for function types below. +template +class OnceAction; + +// An action that can only be used once. +// +// This is accepted by WillOnce, which doesn't require the underlying action to +// be copy-constructible (only move-constructible), and promises to invoke it as +// an rvalue reference. This allows the action to work with move-only types like +// std::move_only_function in a type-safe manner. +// +// For example: +// +// // Assume we have some API that needs to accept a unique pointer to some +// // non-copyable object Foo. +// void AcceptUniquePointer(std::unique_ptr foo); +// +// // We can define an action that provides a Foo to that API. Because It +// // has to give away its unique pointer, it must not be called more than +// // once, so its call operator is &&-qualified. +// struct ProvideFoo { +// std::unique_ptr foo; +// +// void operator()() && { +// AcceptUniquePointer(std::move(Foo)); +// } +// }; +// +// // This action can be used with WillOnce. +// EXPECT_CALL(mock, Call) +// .WillOnce(ProvideFoo{std::make_unique(...)}); +// +// // But a call to WillRepeatedly will fail to compile. This is correct, +// // since the action cannot correctly be used repeatedly. +// EXPECT_CALL(mock, Call) +// .WillRepeatedly(ProvideFoo{std::make_unique(...)}); +// +// A less-contrived example would be an action that returns an arbitrary type, +// whose &&-qualified call operator is capable of dealing with move-only types. +template +class OnceAction final { + private: + // True iff we can use the given callable type (or lvalue reference) directly + // via StdFunctionAdaptor. + template + using IsDirectlyCompatible = internal::conjunction< + // It must be possible to capture the callable in StdFunctionAdaptor. + std::is_constructible::type, Callable>, + // The callable must be compatible with our signature. + internal::is_callable_r::type, + Args...>>; + + // True iff we can use the given callable type via StdFunctionAdaptor once we + // ignore incoming arguments. + template + using IsCompatibleAfterIgnoringArguments = internal::conjunction< + // It must be possible to capture the callable in a lambda. + std::is_constructible::type, Callable>, + // The callable must be invocable with zero arguments, returning something + // convertible to Result. + internal::is_callable_r::type>>; + + public: + // Construct from a callable that is directly compatible with our mocked + // signature: it accepts our function type's arguments and returns something + // convertible to our result type. + template ::type>>, + IsDirectlyCompatible> // + ::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + : function_(StdFunctionAdaptor::type>( + {}, std::forward(callable))) {} + + // As above, but for a callable that ignores the mocked function's arguments. + template ::type>>, + // Exclude callables for which the overload above works. + // We'd rather provide the arguments if possible. + internal::negation>, + IsCompatibleAfterIgnoringArguments>::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + // Call the constructor above with a callable + // that ignores the input arguments. + : OnceAction(IgnoreIncomingArguments::type>{ + std::forward(callable)}) {} + + // We are naturally copyable because we store only an std::function, but + // semantically we should not be copyable. + OnceAction(const OnceAction&) = delete; + OnceAction& operator=(const OnceAction&) = delete; + OnceAction(OnceAction&&) = default; + + // Invoke the underlying action callable with which we were constructed, + // handing it the supplied arguments. + Result Call(Args... args) && { + return function_(std::forward(args)...); + } + + private: + // An adaptor that wraps a callable that is compatible with our signature and + // being invoked as an rvalue reference so that it can be used as an + // StdFunctionAdaptor. This throws away type safety, but that's fine because + // this is only used by WillOnce, which we know calls at most once. + // + // Once we have something like std::move_only_function from C++23, we can do + // away with this. + template + class StdFunctionAdaptor final { + public: + // A tag indicating that the (otherwise universal) constructor is accepting + // the callable itself, instead of e.g. stealing calls for the move + // constructor. + struct CallableTag final {}; + + template + explicit StdFunctionAdaptor(CallableTag, F&& callable) + : callable_(std::make_shared(std::forward(callable))) {} + + // Rather than explicitly returning Result, we return whatever the wrapped + // callable returns. This allows for compatibility with existing uses like + // the following, when the mocked function returns void: + // + // EXPECT_CALL(mock_fn_, Call) + // .WillOnce([&] { + // [...] + // return 0; + // }); + // + // Such a callable can be turned into std::function. If we use an + // explicit return type of Result here then it *doesn't* work with + // std::function, because we'll get a "void function should not return a + // value" error. + // + // We need not worry about incompatible result types because the SFINAE on + // OnceAction already checks this for us. std::is_invocable_r_v itself makes + // the same allowance for void result types. + template + internal::call_result_t operator()( + ArgRefs&&... args) const { + return std::move(*callable_)(std::forward(args)...); + } + + private: + // We must put the callable on the heap so that we are copyable, which + // std::function needs. + std::shared_ptr callable_; + }; + + // An adaptor that makes a callable that accepts zero arguments callable with + // our mocked arguments. + template + struct IgnoreIncomingArguments { + internal::call_result_t operator()(Args&&...) { + return std::move(callable)(); + } + + Callable callable; + }; + + std::function function_; +}; + +// When an unexpected function call is encountered, Google Mock will +// let it return a default value if the user has specified one for its +// return type, or if the return type has a built-in default value; +// otherwise Google Mock won't know what value to return and will have +// to abort the process. +// +// The DefaultValue class allows a user to specify the +// default value for a type T that is both copyable and publicly +// destructible (i.e. anything that can be used as a function return +// type). The usage is: +// +// // Sets the default value for type T to be foo. +// DefaultValue::Set(foo); +template +class DefaultValue { + public: + // Sets the default value for type T; requires T to be + // copy-constructable and have a public destructor. + static void Set(T x) { + delete producer_; + producer_ = new FixedValueProducer(x); + } + + // Provides a factory function to be called to generate the default value. + // This method can be used even if T is only move-constructible, but it is not + // limited to that case. + typedef T (*FactoryFunction)(); + static void SetFactory(FactoryFunction factory) { + delete producer_; + producer_ = new FactoryValueProducer(factory); + } + + // Unsets the default value for type T. + static void Clear() { + delete producer_; + producer_ = nullptr; + } + + // Returns true if and only if the user has set the default value for type T. + static bool IsSet() { return producer_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T if the user has set one; + // otherwise returns the built-in default value. Requires that Exists() + // is true, which ensures that the return value is well-defined. + static T Get() { + return producer_ == nullptr ? internal::BuiltInDefaultValue::Get() + : producer_->Produce(); + } + + private: + class ValueProducer { + public: + virtual ~ValueProducer() = default; + virtual T Produce() = 0; + }; + + class FixedValueProducer : public ValueProducer { + public: + explicit FixedValueProducer(T value) : value_(value) {} + T Produce() override { return value_; } + + private: + const T value_; + FixedValueProducer(const FixedValueProducer&) = delete; + FixedValueProducer& operator=(const FixedValueProducer&) = delete; + }; + + class FactoryValueProducer : public ValueProducer { + public: + explicit FactoryValueProducer(FactoryFunction factory) + : factory_(factory) {} + T Produce() override { return factory_(); } + + private: + const FactoryFunction factory_; + FactoryValueProducer(const FactoryValueProducer&) = delete; + FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; + }; + + static ValueProducer* producer_; +}; + +// This partial specialization allows a user to set default values for +// reference types. +template +class DefaultValue { + public: + // Sets the default value for type T&. + static void Set(T& x) { // NOLINT + address_ = &x; + } + + // Unsets the default value for type T&. + static void Clear() { address_ = nullptr; } + + // Returns true if and only if the user has set the default value for type T&. + static bool IsSet() { return address_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T& if the user has set one; + // otherwise returns the built-in default value if there is one; + // otherwise aborts the process. + static T& Get() { + return address_ == nullptr ? internal::BuiltInDefaultValue::Get() + : *address_; + } + + private: + static T* address_; +}; + +// This specialization allows DefaultValue::Get() to +// compile. +template <> +class DefaultValue { + public: + static bool Exists() { return true; } + static void Get() {} +}; + +// Points to the user-set default value for type T. +template +typename DefaultValue::ValueProducer* DefaultValue::producer_ = nullptr; + +// Points to the user-set default value for type T&. +template +T* DefaultValue::address_ = nullptr; + +// Implement this interface to define an action for function type F. +template +class ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + ActionInterface() = default; + virtual ~ActionInterface() = default; + + // Performs the action. This method is not const, as in general an + // action can have side effects and be stateful. For example, a + // get-the-next-element-from-the-collection action will need to + // remember the current element. + virtual Result Perform(const ArgumentTuple& args) = 0; + + private: + ActionInterface(const ActionInterface&) = delete; + ActionInterface& operator=(const ActionInterface&) = delete; +}; + +template +class Action; + +// An Action is a copyable and IMMUTABLE (except by assignment) +// object that represents an action to be taken when a mock function of type +// R(Args...) is called. The implementation of Action is just a +// std::shared_ptr to const ActionInterface. Don't inherit from Action! You +// can view an object implementing ActionInterface as a concrete action +// (including its current state), and an Action object as a handle to it. +template +class Action { + private: + using F = R(Args...); + + // Adapter class to allow constructing Action from a legacy ActionInterface. + // New code should create Actions from functors instead. + struct ActionAdapter { + // Adapter must be copyable to satisfy std::function requirements. + ::std::shared_ptr> impl_; + + template + typename internal::Function::Result operator()(InArgs&&... args) { + return impl_->Perform( + ::std::forward_as_tuple(::std::forward(args)...)); + } + }; + + template + using IsCompatibleFunctor = std::is_constructible, G>; + + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + // Constructs a null Action. Needed for storing Action objects in + // STL containers. + Action() = default; + + // Construct an Action from a specified callable. + // This cannot take std::function directly, because then Action would not be + // directly constructible from lambda (it would require two conversions). + template < + typename G, + typename = typename std::enable_if, std::is_constructible, + G>>::value>::type> + Action(G&& fun) { // NOLINT + Init(::std::forward(fun), IsCompatibleFunctor()); + } + + // Constructs an Action from its implementation. + explicit Action(ActionInterface* impl) + : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} + + // This constructor allows us to turn an Action object into an + // Action, as long as F's arguments can be implicitly converted + // to Func's and Func's return type can be implicitly converted to F's. + template + Action(const Action& action) // NOLINT + : fun_(action.fun_) {} + + // Returns true if and only if this is the DoDefault() action. + bool IsDoDefault() const { return fun_ == nullptr; } + + // Performs the action. Note that this method is const even though + // the corresponding method in ActionInterface is not. The reason + // is that a const Action means that it cannot be re-bound to + // another concrete action, not that the concrete action it binds to + // cannot change state. (Think of the difference between a const + // pointer and a pointer to const.) + Result Perform(ArgumentTuple args) const { + if (IsDoDefault()) { + internal::IllegalDoDefault(__FILE__, __LINE__); + } + return internal::Apply(fun_, ::std::move(args)); + } + + // An action can be used as a OnceAction, since it's obviously safe to call it + // once. + operator OnceAction() const { // NOLINT + // Return a OnceAction-compatible callable that calls Perform with the + // arguments it is provided. We could instead just return fun_, but then + // we'd need to handle the IsDoDefault() case separately. + struct OA { + Action action; + + R operator()(Args... args) && { + return action.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{*this}; + } + + private: + template + friend class Action; + + template + void Init(G&& g, ::std::true_type) { + fun_ = ::std::forward(g); + } + + template + void Init(G&& g, ::std::false_type) { + fun_ = IgnoreArgs::type>{::std::forward(g)}; + } + + template + struct IgnoreArgs { + template + Result operator()(const InArgs&...) const { + return function_impl(); + } + template + Result operator()(const InArgs&...) { + return function_impl(); + } + + FunctionImpl function_impl; + }; + + // fun_ is an empty function if and only if this is the DoDefault() action. + ::std::function fun_; +}; + +// The PolymorphicAction class template makes it easy to implement a +// polymorphic action (i.e. an action that can be used in mock +// functions of than one type, e.g. Return()). +// +// To define a polymorphic action, a user first provides a COPYABLE +// implementation class that has a Perform() method template: +// +// class FooAction { +// public: +// template +// Result Perform(const ArgumentTuple& args) const { +// // Processes the arguments and returns a result, using +// // std::get(args) to get the N-th (0-based) argument in the tuple. +// } +// ... +// }; +// +// Then the user creates the polymorphic action using +// MakePolymorphicAction(object) where object has type FooAction. See +// the definition of Return(void) and SetArgumentPointee(value) for +// complete examples. +template +class PolymorphicAction { + public: + explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} + + template + operator Action() const { + return Action(new MonomorphicImpl(impl_)); + } + + private: + template + class MonomorphicImpl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} + + Result Perform(const ArgumentTuple& args) override { + return impl_.template Perform(args); + } + + private: + Impl impl_; + }; + + Impl impl_; +}; + +// Creates an Action from its implementation and returns it. The +// created Action object owns the implementation. +template +Action MakeAction(ActionInterface* impl) { + return Action(impl); +} + +// Creates a polymorphic action from its implementation. This is +// easier to use than the PolymorphicAction constructor as it +// doesn't require you to explicitly write the template argument, e.g. +// +// MakePolymorphicAction(foo); +// vs +// PolymorphicAction(foo); +template +inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { + return PolymorphicAction(impl); +} + +namespace internal { + +// Helper struct to specialize ReturnAction to execute a move instead of a copy +// on return. Useful for move-only types, but could be used on any type. +template +struct ByMoveWrapper { + explicit ByMoveWrapper(T value) : payload(std::move(value)) {} + T payload; +}; + +// The general implementation of Return(R). Specializations follow below. +template +class ReturnAction final { + public: + explicit ReturnAction(R value) : value_(std::move(value)) {} + + template >, // + negation>, // + std::is_convertible, // + std::is_move_constructible>::value>::type> + operator OnceAction() && { // NOLINT + return Impl(std::move(value_)); + } + + template >, // + negation>, // + std::is_convertible, // + std::is_copy_constructible>::value>::type> + operator Action() const { // NOLINT + return Impl(value_); + } + + private: + // Implements the Return(x) action for a mock function that returns type U. + template + class Impl final { + public: + // The constructor used when the return value is allowed to move from the + // input value (i.e. we are converting to OnceAction). + explicit Impl(R&& input_value) + : state_(new State(std::move(input_value))) {} + + // The constructor used when the return value is not allowed to move from + // the input value (i.e. we are converting to Action). + explicit Impl(const R& input_value) : state_(new State(input_value)) {} + + U operator()() && { return std::move(state_->value); } + U operator()() const& { return state_->value; } + + private: + // We put our state on the heap so that the compiler-generated copy/move + // constructors work correctly even when U is a reference-like type. This is + // necessary only because we eagerly create State::value (see the note on + // that symbol for details). If we instead had only the input value as a + // member then the default constructors would work fine. + // + // For example, when R is std::string and U is std::string_view, value is a + // reference to the string backed by input_value. The copy constructor would + // copy both, so that we wind up with a new input_value object (with the + // same contents) and a reference to the *old* input_value object rather + // than the new one. + struct State { + explicit State(const R& input_value_in) + : input_value(input_value_in), + // Make an implicit conversion to Result before initializing the U + // object we store, avoiding calling any explicit constructor of U + // from R. + // + // This simulates the language rules: a function with return type U + // that does `return R()` requires R to be implicitly convertible to + // U, and uses that path for the conversion, even U Result has an + // explicit constructor from R. + value(ImplicitCast_(internal::as_const(input_value))) {} + + // As above, but for the case where we're moving from the ReturnAction + // object because it's being used as a OnceAction. + explicit State(R&& input_value_in) + : input_value(std::move(input_value_in)), + // For the same reason as above we make an implicit conversion to U + // before initializing the value. + // + // Unlike above we provide the input value as an rvalue to the + // implicit conversion because this is a OnceAction: it's fine if it + // wants to consume the input value. + value(ImplicitCast_(std::move(input_value))) {} + + // A copy of the value originally provided by the user. We retain this in + // addition to the value of the mock function's result type below in case + // the latter is a reference-like type. See the std::string_view example + // in the documentation on Return. + R input_value; + + // The value we actually return, as the type returned by the mock function + // itself. + // + // We eagerly initialize this here, rather than lazily doing the implicit + // conversion automatically each time Perform is called, for historical + // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126) + // made the Action conversion operator eagerly convert the R value to + // U, but without keeping the R alive. This broke the use case discussed + // in the documentation for Return, making reference-like types such as + // std::string_view not safe to use as U where the input type R is a + // value-like type such as std::string. + // + // The example the commit gave was not very clear, nor was the issue + // thread (https://github.com/google/googlemock/issues/86), but it seems + // the worry was about reference-like input types R that flatten to a + // value-like type U when being implicitly converted. An example of this + // is std::vector::reference, which is often a proxy type with an + // reference to the underlying vector: + // + // // Helper method: have the mock function return bools according + // // to the supplied script. + // void SetActions(MockFunction& mock, + // const std::vector& script) { + // for (size_t i = 0; i < script.size(); ++i) { + // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i])); + // } + // } + // + // TEST(Foo, Bar) { + // // Set actions using a temporary vector, whose operator[] + // // returns proxy objects that references that will be + // // dangling once the call to SetActions finishes and the + // // vector is destroyed. + // MockFunction mock; + // SetActions(mock, {false, true}); + // + // EXPECT_FALSE(mock.AsStdFunction()(0)); + // EXPECT_TRUE(mock.AsStdFunction()(1)); + // } + // + // This eager conversion helps with a simple case like this, but doesn't + // fully make these types work in general. For example the following still + // uses a dangling reference: + // + // TEST(Foo, Baz) { + // MockFunction()> mock; + // + // // Return the same vector twice, and then the empty vector + // // thereafter. + // auto action = Return(std::initializer_list{ + // "taco", "burrito", + // }); + // + // EXPECT_CALL(mock, Call) + // .WillOnce(action) + // .WillOnce(action) + // .WillRepeatedly(Return(std::vector{})); + // + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty()); + // } + // + U value; + }; + + const std::shared_ptr state_; + }; + + R value_; +}; + +// A specialization of ReturnAction when R is ByMoveWrapper for some T. +// +// This version applies the type system-defeating hack of moving from T even in +// the const call operator, checking at runtime that it isn't called more than +// once, since the user has declared their intent to do so by using ByMove. +template +class ReturnAction> final { + public: + explicit ReturnAction(ByMoveWrapper wrapper) + : state_(new State(std::move(wrapper.payload))) {} + + T operator()() const { + GTEST_CHECK_(!state_->called) + << "A ByMove() action must be performed at most once."; + + state_->called = true; + return std::move(state_->value); + } + + private: + // We store our state on the heap so that we are copyable as required by + // Action, despite the fact that we are stateful and T may not be copyable. + struct State { + explicit State(T&& value_in) : value(std::move(value_in)) {} + + T value; + bool called = false; + }; + + const std::shared_ptr state_; +}; + +// Implements the ReturnNull() action. +class ReturnNullAction { + public: + // Allows ReturnNull() to be used in any pointer-returning function. In C++11 + // this is enforced by returning nullptr, and in non-C++11 by asserting a + // pointer type on compile time. + template + static Result Perform(const ArgumentTuple&) { + return nullptr; + } +}; + +// Implements the Return() action. +class ReturnVoidAction { + public: + // Allows Return() to be used in any void-returning function. + template + static void Perform(const ArgumentTuple&) { + static_assert(std::is_void::value, "Result should be void."); + } +}; + +// Implements the polymorphic ReturnRef(x) action, which can be used +// in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefAction { + public: + // Constructs a ReturnRefAction object from the reference to be returned. + explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT + + // This template type conversion operator allows ReturnRef(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRef(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRef to return a value"); + return Action(new Impl(ref_)); + } + + private: + // Implements the ReturnRef(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(T& ref) : ref_(ref) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return ref_; } + + private: + T& ref_; + }; + + T& ref_; +}; + +// Implements the polymorphic ReturnRefOfCopy(x) action, which can be +// used in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefOfCopyAction { + public: + // Constructs a ReturnRefOfCopyAction object from the reference to + // be returned. + explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT + + // This template type conversion operator allows ReturnRefOfCopy(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRefOfCopy(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRefOfCopy to return a value"); + return Action(new Impl(value_)); + } + + private: + // Implements the ReturnRefOfCopy(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const T& value) : value_(value) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return value_; } + + private: + T value_; + }; + + const T value_; +}; + +// Implements the polymorphic ReturnRoundRobin(v) action, which can be +// used in any function that returns the element_type of v. +template +class ReturnRoundRobinAction { + public: + explicit ReturnRoundRobinAction(std::vector values) { + GTEST_CHECK_(!values.empty()) + << "ReturnRoundRobin requires at least one element."; + state_->values = std::move(values); + } + + template + T operator()(Args&&...) const { + return state_->Next(); + } + + private: + struct State { + T Next() { + T ret_val = values[i++]; + if (i == values.size()) i = 0; + return ret_val; + } + + std::vector values; + size_t i = 0; + }; + std::shared_ptr state_ = std::make_shared(); +}; + +// Implements the polymorphic DoDefault() action. +class DoDefaultAction { + public: + // This template type conversion operator allows DoDefault() to be + // used in any function. + template + operator Action() const { + return Action(); + } // NOLINT +}; + +// Implements the Assign action to set a given pointer referent to a +// particular value. +template +class AssignAction { + public: + AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} + + template + void Perform(const ArgumentTuple& /* args */) const { + *ptr_ = value_; + } + + private: + T1* const ptr_; + const T2 value_; +}; + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Implements the SetErrnoAndReturn action to simulate return from +// various system calls and libc functions. +template +class SetErrnoAndReturnAction { + public: + SetErrnoAndReturnAction(int errno_value, T result) + : errno_(errno_value), result_(result) {} + template + Result Perform(const ArgumentTuple& /* args */) const { + errno = errno_; + return result_; + } + + private: + const int errno_; + const T result_; +}; + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetArgumentPointee(x) action for any function +// whose N-th argument (0-based) is a pointer to x's type. +template +struct SetArgumentPointeeAction { + A value; + + template + void operator()(const Args&... args) const { + *::std::get(std::tie(args...)) = value; + } +}; + +// Implements the Invoke(object_ptr, &Class::Method) action. +template +struct InvokeMethodAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + template + auto operator()(Args&&... args) const + -> decltype((obj_ptr->*method_ptr)(std::forward(args)...)) { + return (obj_ptr->*method_ptr)(std::forward(args)...); + } +}; + +// Implements the InvokeWithoutArgs(f) action. The template argument +// FunctionImpl is the implementation type of f, which can be either a +// function pointer or a functor. InvokeWithoutArgs(f) can be used as an +// Action as long as f's type is compatible with F. +template +struct InvokeWithoutArgsAction { + FunctionImpl function_impl; + + // Allows InvokeWithoutArgs(f) to be used as any action whose type is + // compatible with f. + template + auto operator()(const Args&...) -> decltype(function_impl()) { + return function_impl(); + } +}; + +// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. +template +struct InvokeMethodWithoutArgsAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + using ReturnType = + decltype((std::declval()->*std::declval())()); + + template + ReturnType operator()(const Args&...) const { + return (obj_ptr->*method_ptr)(); + } +}; + +// Implements the IgnoreResult(action) action. +template +class IgnoreResultAction { + public: + explicit IgnoreResultAction(const A& action) : action_(action) {} + + template + operator Action() const { + // Assert statement belongs here because this is the best place to verify + // conditions on F. It produces the clearest error messages + // in most compilers. + // Impl really belongs in this scope as a local class but can't + // because MSVC produces duplicate symbols in different translation units + // in this case. Until MS fixes that bug we put Impl into the class scope + // and put the typedef both here (for use in assert statement) and + // in the Impl class. But both definitions must be the same. + typedef typename internal::Function::Result Result; + + // Asserts at compile time that F returns void. + static_assert(std::is_void::value, "Result type should be void."); + + return Action(new Impl(action_)); + } + + private: + template + class Impl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const A& action) : action_(action) {} + + void Perform(const ArgumentTuple& args) override { + // Performs the action and ignores its result. + action_.Perform(args); + } + + private: + // Type OriginalFunction is the same as F except that its return + // type is IgnoredValue. + typedef + typename internal::Function::MakeResultIgnoredValue OriginalFunction; + + const Action action_; + }; + + const A action_; +}; + +template +struct WithArgsAction { + InnerAction inner_action; + + // The signature of the function as seen by the inner action, given an out + // action with the given result and argument types. + template + using InnerSignature = + R(typename std::tuple_element>::type...); + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + struct OA { + OnceAction> inner_action; + + R operator()(Args&&... args) && { + return std::move(inner_action) + .Call(std::get( + std::forward_as_tuple(std::forward(args)...))...); + } + }; + + return OA{std::move(inner_action)}; + } + + // As above, but in the case where we want to create a OnceAction from a const + // WithArgsAction. This is fine as long as the inner action doesn't need to + // move any of its state to create a OnceAction. + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator OnceAction() const& { // NOLINT + struct OA { + OnceAction> inner_action; + + R operator()(Args&&... args) && { + return std::move(inner_action) + .Call(std::get( + std::forward_as_tuple(std::forward(args)...))...); + } + }; + + return OA{inner_action}; + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator Action() const { // NOLINT + Action> converted(inner_action); + + return [converted](Args&&... args) -> R { + return converted.Perform(std::forward_as_tuple( + std::get(std::forward_as_tuple(std::forward(args)...))...)); + }; + } +}; + +template +class DoAllAction; + +// Base case: only a single action. +template +class DoAllAction { + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& action) + : final_action_(std::forward(action)) {} + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + // We support conversion to OnceAction whenever the sub-action does. + template >::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return std::move(final_action_); + } + + // We also support conversion to OnceAction whenever the sub-action supports + // conversion to Action (since any Action can also be a OnceAction). + template < + typename R, typename... Args, + typename std::enable_if< + conjunction< + negation< + std::is_convertible>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return Action(std::move(final_action_)); + } + + // We support conversion to Action whenever the sub-action does. + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>::value, + int>::type = 0> + operator Action() const { // NOLINT + return final_action_; + } + + private: + FinalAction final_action_; +}; + +// Recursive case: support N actions by calling the initial action and then +// calling through to the base class containing N-1 actions. +template +class DoAllAction + : private DoAllAction { + private: + using Base = DoAllAction; + + // The type of reference that should be provided to an initial action for a + // mocked function parameter of type T. + // + // There are two quirks here: + // + // * Unlike most forwarding functions, we pass scalars through by value. + // This isn't strictly necessary because an lvalue reference would work + // fine too and be consistent with other non-reference types, but it's + // perhaps less surprising. + // + // For example if the mocked function has signature void(int), then it + // might seem surprising for the user's initial action to need to be + // convertible to Action. This is perhaps less + // surprising for a non-scalar type where there may be a performance + // impact, or it might even be impossible, to pass by value. + // + // * More surprisingly, `const T&` is often not a const reference type. + // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to + // U& or U&& for some non-scalar type U, then InitialActionArgType is + // U&. In other words, we may hand over a non-const reference. + // + // So for example, given some non-scalar type Obj we have the following + // mappings: + // + // T InitialActionArgType + // ------- ----------------------- + // Obj const Obj& + // Obj& Obj& + // Obj&& Obj& + // const Obj const Obj& + // const Obj& const Obj& + // const Obj&& const Obj& + // + // In other words, the initial actions get a mutable view of an non-scalar + // argument if and only if the mock function itself accepts a non-const + // reference type. They are never given an rvalue reference to an + // non-scalar type. + // + // This situation makes sense if you imagine use with a matcher that is + // designed to write through a reference. For example, if the caller wants + // to fill in a reference argument and then return a canned value: + // + // EXPECT_CALL(mock, Call) + // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19))); + // + template + using InitialActionArgType = + typename std::conditional::value, T, const T&>::type; + + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& initial_action, + U&&... other_actions) + : Base({}, std::forward(other_actions)...), + initial_action_(std::forward(initial_action)) {} + + // We support conversion to OnceAction whenever both the initial action and + // the rest support conversion to OnceAction. + template < + typename R, typename... Args, + typename std::enable_if< + conjunction...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + OnceAction...)> initial_action; + OnceAction remaining_actions; + + R operator()(Args... args) && { + std::move(initial_action) + .Call(static_cast>(args)...); + + return std::move(remaining_actions).Call(std::forward(args)...); + } + }; + + return OA{ + std::move(initial_action_), + std::move(static_cast(*this)), + }; + } + + // We also support conversion to OnceAction whenever the initial action + // supports conversion to Action (since any Action can also be a OnceAction). + // + // The remaining sub-actions must also be compatible, but we don't need to + // special case them because the base class deals with them. + template < + typename R, typename... Args, + typename std::enable_if< + conjunction< + negation...)>>>, + std::is_convertible...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return DoAll( + Action...)>(std::move(initial_action_)), + std::move(static_cast(*this))); + } + + // We support conversion to Action whenever both the initial action and the + // rest support conversion to Action. + template < + typename R, typename... Args, + typename std::enable_if< + conjunction< + std::is_convertible...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator Action() const { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + Action...)> initial_action; + Action remaining_actions; + + R operator()(Args... args) const { + initial_action.Perform(std::forward_as_tuple( + static_cast>(args)...)); + + return remaining_actions.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{ + initial_action_, + static_cast(*this), + }; + } + + private: + InitialAction initial_action_; +}; + +template +struct ReturnNewAction { + T* operator()() const { + return internal::Apply( + [](const Params&... unpacked_params) { + return new T(unpacked_params...); + }, + params); + } + std::tuple params; +}; + +template +struct ReturnArgAction { + template ::type> + auto operator()(Args&&... args) const -> decltype(std::get( + std::forward_as_tuple(std::forward(args)...))) { + return std::get(std::forward_as_tuple(std::forward(args)...)); + } +}; + +template +struct SaveArgAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = std::get(std::tie(args...)); + } +}; + +template +struct SaveArgByMoveAction { + Ptr pointer; + + template + void operator()(Args&&... args) const { + *pointer = std::move(std::get(std::tie(args...))); + } +}; + +template +struct SaveArgPointeeAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = *std::get(std::tie(args...)); + } +}; + +template +struct SetArgRefereeAction { + T value; + + template + void operator()(Args&&... args) const { + using argk_type = + typename ::std::tuple_element>::type; + static_assert(std::is_lvalue_reference::value, + "Argument must be a reference type."); + std::get(std::tie(args...)) = value; + } +}; + +template +struct SetArrayArgumentAction { + I1 first; + I2 last; + + template + void operator()(const Args&... args) const { + auto value = std::get(std::tie(args...)); + for (auto it = first; it != last; ++it, (void)++value) { + *value = *it; + } + } +}; + +template +struct DeleteArgAction { + template + void operator()(const Args&... args) const { + delete std::get(std::tie(args...)); + } +}; + +template +struct ReturnPointeeAction { + Ptr pointer; + template + auto operator()(const Args&...) const -> decltype(*pointer) { + return *pointer; + } +}; + +#if GTEST_HAS_EXCEPTIONS +template +struct ThrowAction { + T exception; + // We use a conversion operator to adapt to any return type. + template + operator Action() const { // NOLINT + T copy = exception; + return [copy](Args...) -> R { throw copy; }; + } +}; +struct RethrowAction { + std::exception_ptr exception; + template + operator Action() const { // NOLINT + return [ex = exception](Args...) -> R { std::rethrow_exception(ex); }; + } +}; +#endif // GTEST_HAS_EXCEPTIONS + +} // namespace internal + +// An Unused object can be implicitly constructed from ANY value. +// This is handy when defining actions that ignore some or all of the +// mock function arguments. For example, given +// +// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); +// MOCK_METHOD3(Bar, double(int index, double x, double y)); +// +// instead of +// +// double DistanceToOriginWithLabel(const string& label, double x, double y) { +// return sqrt(x*x + y*y); +// } +// double DistanceToOriginWithIndex(int index, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)) +// .WillOnce(Invoke(DistanceToOriginWithLabel)); +// EXPECT_CALL(mock, Bar(5, _, _)) +// .WillOnce(Invoke(DistanceToOriginWithIndex)); +// +// you could write +// +// // We can declare any uninteresting argument as Unused. +// double DistanceToOrigin(Unused, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +typedef internal::IgnoredValue Unused; + +// Creates an action that does actions a1, a2, ..., sequentially in +// each invocation. All but the last action will have a readonly view of the +// arguments. +template +internal::DoAllAction::type...> DoAll( + Action&&... action) { + return internal::DoAllAction::type...>( + {}, std::forward(action)...); +} + +// WithArg(an_action) creates an action that passes the k-th +// (0-based) argument of the mock function to an_action and performs +// it. It adapts an action accepting one argument to one that accepts +// multiple arguments. For convenience, we also provide +// WithArgs(an_action) (defined below) as a synonym. +template +internal::WithArgsAction::type, k> WithArg( + InnerAction&& action) { + return {std::forward(action)}; +} + +// WithArgs(an_action) creates an action that passes +// the selected arguments of the mock function to an_action and +// performs it. It serves as an adaptor between actions with +// different argument lists. +template +internal::WithArgsAction::type, k, ks...> +WithArgs(InnerAction&& action) { + return {std::forward(action)}; +} + +// WithoutArgs(inner_action) can be used in a mock function with a +// non-empty argument list to perform inner_action, which takes no +// argument. In other words, it adapts an action accepting no +// argument to one that accepts (and ignores) arguments. +template +internal::WithArgsAction::type> WithoutArgs( + InnerAction&& action) { + return {std::forward(action)}; +} + +// Creates an action that returns a value. +// +// The returned type can be used with a mock function returning a non-void, +// non-reference type U as follows: +// +// * If R is convertible to U and U is move-constructible, then the action can +// be used with WillOnce. +// +// * If const R& is convertible to U and U is copy-constructible, then the +// action can be used with both WillOnce and WillRepeatedly. +// +// The mock expectation contains the R value from which the U return value is +// constructed (a move/copy of the argument to Return). This means that the R +// value will survive at least until the mock object's expectations are cleared +// or the mock object is destroyed, meaning that U can safely be a +// reference-like type such as std::string_view: +// +// // The mock function returns a view of a copy of the string fed to +// // Return. The view is valid even after the action is performed. +// MockFunction mock; +// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco"))); +// const std::string_view result = mock.AsStdFunction()(); +// EXPECT_EQ("taco", result); +// +template +internal::ReturnAction Return(R value) { + return internal::ReturnAction(std::move(value)); +} + +// Creates an action that returns NULL. +inline PolymorphicAction ReturnNull() { + return MakePolymorphicAction(internal::ReturnNullAction()); +} + +// Creates an action that returns from a void function. +inline PolymorphicAction Return() { + return MakePolymorphicAction(internal::ReturnVoidAction()); +} + +// Creates an action that returns the reference to a variable. +template +inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT + return internal::ReturnRefAction(x); +} + +// Prevent using ReturnRef on reference to temporary. +template +internal::ReturnRefAction ReturnRef(R&&) = delete; + +// Creates an action that returns the reference to a copy of the +// argument. The copy is created when the action is constructed and +// lives as long as the action. +template +inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { + return internal::ReturnRefOfCopyAction(x); +} + +// DEPRECATED: use Return(x) directly with WillOnce. +// +// Modifies the parent action (a Return() action) to perform a move of the +// argument instead of a copy. +// Return(ByMove()) actions can only be executed once and will assert this +// invariant. +template +internal::ByMoveWrapper ByMove(R x) { + return internal::ByMoveWrapper(std::move(x)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin(std::vector vals) { + return internal::ReturnRoundRobinAction(std::move(vals)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin( + std::initializer_list vals) { + return internal::ReturnRoundRobinAction(std::vector(vals)); +} + +// Creates an action that does the default action for the give mock function. +inline internal::DoDefaultAction DoDefault() { + return internal::DoDefaultAction(); +} + +// Creates an action that sets the variable pointed by the N-th +// (0-based) function argument to 'value'. +template +internal::SetArgumentPointeeAction SetArgPointee(T value) { + return {std::move(value)}; +} + +// The following version is DEPRECATED. +template +internal::SetArgumentPointeeAction SetArgumentPointee(T value) { + return {std::move(value)}; +} + +// Creates an action that sets a pointer referent to a given value. +template +PolymorphicAction> Assign(T1* ptr, T2 val) { + return MakePolymorphicAction(internal::AssignAction(ptr, val)); +} + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Creates an action that sets errno and returns the appropriate error. +template +PolymorphicAction> SetErrnoAndReturn( + int errval, T result) { + return MakePolymorphicAction( + internal::SetErrnoAndReturnAction(errval, result)); +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Various overloads for Invoke(). + +// Legacy function. +// Actions can now be implicitly constructed from callables. No need to create +// wrapper objects. +// This function exists for backwards compatibility. +template +typename std::decay::type Invoke(FunctionImpl&& function_impl) { + return std::forward(function_impl); +} + +// Creates an action that invokes the given method on the given object +// with the mock function's arguments. +template +internal::InvokeMethodAction Invoke(Class* obj_ptr, + MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that invokes 'function_impl' with no argument. +template +internal::InvokeWithoutArgsAction::type> +InvokeWithoutArgs(FunctionImpl function_impl) { + return {std::move(function_impl)}; +} + +// Creates an action that invokes the given method on the given object +// with no argument. +template +internal::InvokeMethodWithoutArgsAction InvokeWithoutArgs( + Class* obj_ptr, MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that performs an_action and throws away its +// result. In other words, it changes the return type of an_action to +// void. an_action MUST NOT return void, or the code won't compile. +template +inline internal::IgnoreResultAction IgnoreResult(const A& an_action) { + return internal::IgnoreResultAction(an_action); +} + +// Creates a reference wrapper for the given L-value. If necessary, +// you can explicitly specify the type of the reference. For example, +// suppose 'derived' is an object of type Derived, ByRef(derived) +// would wrap a Derived&. If you want to wrap a const Base& instead, +// where Base is a base class of Derived, just write: +// +// ByRef(derived) +// +// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. +// However, it may still be used for consistency with ByMove(). +template +inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT + return ::std::reference_wrapper(l_value); +} + +// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new +// instance of type T, constructed on the heap with constructor arguments +// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. +template +internal::ReturnNewAction::type...> ReturnNew( + Params&&... params) { + return {std::forward_as_tuple(std::forward(params)...)}; +} + +// Action ReturnArg() returns the k-th argument of the mock function. +template +internal::ReturnArgAction ReturnArg() { + return {}; +} + +// Action SaveArg(pointer) saves the k-th (0-based) argument of the +// mock function to *pointer. +template +internal::SaveArgAction SaveArg(Ptr pointer) { + return {pointer}; +} + +// Action SaveArgByMove(pointer) moves the k-th (0-based) argument of the +// mock function into *pointer. +template +internal::SaveArgByMoveAction SaveArgByMove(Ptr pointer) { + return {pointer}; +} + +// Action SaveArgPointee(pointer) saves the value pointed to +// by the k-th (0-based) argument of the mock function to *pointer. +template +internal::SaveArgPointeeAction SaveArgPointee(Ptr pointer) { + return {pointer}; +} + +// Action SetArgReferee(value) assigns 'value' to the variable +// referenced by the k-th (0-based) argument of the mock function. +template +internal::SetArgRefereeAction::type> SetArgReferee( + T&& value) { + return {std::forward(value)}; +} + +// Action SetArrayArgument(first, last) copies the elements in +// source range [first, last) to the array pointed to by the k-th +// (0-based) argument, which can be either a pointer or an +// iterator. The action does not take ownership of the elements in the +// source range. +template +internal::SetArrayArgumentAction SetArrayArgument(I1 first, + I2 last) { + return {first, last}; +} + +// Action DeleteArg() deletes the k-th (0-based) argument of the mock +// function. +template +internal::DeleteArgAction DeleteArg() { + return {}; +} + +// This action returns the value pointed to by 'pointer'. +template +internal::ReturnPointeeAction ReturnPointee(Ptr pointer) { + return {pointer}; +} + +#if GTEST_HAS_EXCEPTIONS +// Action Throw(exception) can be used in a mock function of any type +// to throw the given exception. Any copyable value can be thrown, +// except for std::exception_ptr, which is likely a mistake if +// thrown directly. +template +typename std::enable_if< + !std::is_base_of::type>::value, + internal::ThrowAction::type>>::type +Throw(T&& exception) { + return {std::forward(exception)}; +} +// Action Rethrow(exception_ptr) can be used in a mock function of any type +// to rethrow any exception_ptr. Note that the same object is thrown each time. +inline internal::RethrowAction Rethrow(std::exception_ptr exception) { + return {std::move(exception)}; +} +#endif // GTEST_HAS_EXCEPTIONS + +namespace internal { + +// A macro from the ACTION* family (defined later in gmock-generated-actions.h) +// defines an action that can be used in a mock function. Typically, +// these actions only care about a subset of the arguments of the mock +// function. For example, if such an action only uses the second +// argument, it can be used in any mock function that takes >= 2 +// arguments where the type of the second argument is compatible. +// +// Therefore, the action implementation must be prepared to take more +// arguments than it needs. The ExcessiveArg type is used to +// represent those excessive arguments. In order to keep the compiler +// error messages tractable, we define it in the testing namespace +// instead of testing::internal. However, this is an INTERNAL TYPE +// and subject to change without notice, so a user MUST NOT USE THIS +// TYPE DIRECTLY. +struct ExcessiveArg {}; + +// Builds an implementation of an Action<> for some particular signature, using +// a class defined by an ACTION* macro. +template +struct ActionImpl; + +template +struct ImplBase { + struct Holder { + // Allows each copy of the Action<> to get to the Impl. + explicit operator const Impl&() const { return *ptr; } + std::shared_ptr ptr; + }; + using type = typename std::conditional::value, + Impl, Holder>::type; +}; + +template +struct ActionImpl : ImplBase::type { + using Base = typename ImplBase::type; + using function_type = R(Args...); + using args_type = std::tuple; + + ActionImpl() = default; // Only defined if appropriate for Base. + explicit ActionImpl(std::shared_ptr impl) : Base{std::move(impl)} {} + + R operator()(Args&&... arg) const { + static constexpr size_t kMaxArgs = + sizeof...(Args) <= 10 ? sizeof...(Args) : 10; + return Apply(std::make_index_sequence{}, + std::make_index_sequence<10 - kMaxArgs>{}, + args_type{std::forward(arg)...}); + } + + template + R Apply(std::index_sequence, std::index_sequence, + const args_type& args) const { + // Impl need not be specific to the signature of action being implemented; + // only the implementing function body needs to have all of the specific + // types instantiated. Up to 10 of the args that are provided by the + // args_type get passed, followed by a dummy of unspecified type for the + // remainder up to 10 explicit args. + static constexpr ExcessiveArg kExcessArg{}; + return static_cast(*this) + .template gmock_PerformImpl< + /*function_type=*/function_type, /*return_type=*/R, + /*args_type=*/args_type, + /*argN_type=*/ + typename std::tuple_element::type...>( + /*args=*/args, std::get(args)..., + ((void)excess_id, kExcessArg)...); + } +}; + +// Stores a default-constructed Impl as part of the Action<>'s +// std::function<>. The Impl should be trivial to copy. +template +::testing::Action MakeAction() { + return ::testing::Action(ActionImpl()); +} + +// Stores just the one given instance of Impl. +template +::testing::Action MakeAction(std::shared_ptr impl) { + return ::testing::Action(ActionImpl(std::move(impl))); +} + +#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ + , [[maybe_unused]] const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ + [[maybe_unused]] const args_type& args GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_ARG_UNUSED, , 10) + +#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ + const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) + +#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type +#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ + GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) + +#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type +#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type +#define GMOCK_ACTION_TYPE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ + , param##_type gmock_p##i +#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ + , std::forward(gmock_p##i) +#define GMOCK_ACTION_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ + , param(::std::forward(gmock_p##i)) +#define GMOCK_ACTION_INIT_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) + +#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; +#define GMOCK_ACTION_FIELD_PARAMS_(params) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) + +#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ + template \ + class full_name { \ + public: \ + explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : impl_(std::make_shared( \ + GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ + full_name(const full_name&) = default; \ + full_name(full_name&&) noexcept = default; \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(impl_); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : GMOCK_ACTION_INIT_PARAMS_(params) {} \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + GMOCK_ACTION_FIELD_PARAMS_(params) \ + }; \ + std::shared_ptr impl_; \ + }; \ + template \ + [[nodiscard]] inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)); \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ + return full_name( \ + GMOCK_ACTION_GVALUE_PARAMS_(params)); \ + } \ + template \ + template \ + return_type \ + full_name::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +} // namespace internal + +// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored. +#define ACTION(name) \ + class name##Action { \ + public: \ + explicit name##Action() noexcept {} \ + name##Action(const name##Action&) noexcept {} \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + }; \ + }; \ + [[nodiscard]] inline name##Action name(); \ + inline name##Action name() { return name##Action(); } \ + template \ + return_type name##Action::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) + +#define ACTION_P2(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) + +#define ACTION_P3(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) + +#define ACTION_P4(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) + +#define ACTION_P5(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) + +#define ACTION_P6(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) + +#define ACTION_P7(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) + +#define ACTION_P8(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) + +#define ACTION_P9(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) + +#define ACTION_P10(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-cardinalities.h b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-cardinalities.h new file mode 100644 index 0000000..533e604 --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-cardinalities.h @@ -0,0 +1,159 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used cardinalities. More +// cardinalities can be defined by the user implementing the +// CardinalityInterface interface if necessary. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ + +#include + +#include +#include // NOLINT + +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) + +namespace testing { + +// To implement a cardinality Foo, define: +// 1. a class FooCardinality that implements the +// CardinalityInterface interface, and +// 2. a factory function that creates a Cardinality object from a +// const FooCardinality*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Cardinality objects can now be copied like plain values. + +// The implementation of a cardinality. +class CardinalityInterface { + public: + virtual ~CardinalityInterface() = default; + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + virtual int ConservativeLowerBound() const { return 0; } + virtual int ConservativeUpperBound() const { return INT_MAX; } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(::std::ostream* os) const = 0; +}; + +// A Cardinality is a copyable and IMMUTABLE (except by assignment) +// object that specifies how many times a mock function is expected to +// be called. The implementation of Cardinality is just a std::shared_ptr +// to const CardinalityInterface. Don't inherit from Cardinality! +class GTEST_API_ Cardinality { + public: + // Constructs a null cardinality. Needed for storing Cardinality + // objects in STL containers. + Cardinality() = default; + + // Constructs a Cardinality from its implementation. + explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } + int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + bool IsSatisfiedByCallCount(int call_count) const { + return impl_->IsSatisfiedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will saturate this + // cardinality. + bool IsSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will over-saturate this + // cardinality, i.e. exceed the maximum number of allowed calls. + bool IsOverSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count) && + !impl_->IsSatisfiedByCallCount(call_count); + } + + // Describes self to an ostream + void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + // Describes the given actual call count to an ostream. + static void DescribeActualCallCountTo(int actual_call_count, + ::std::ostream* os); + + private: + std::shared_ptr impl_; +}; + +// Creates a cardinality that allows at least n calls. +GTEST_API_ Cardinality AtLeast(int n); + +// Creates a cardinality that allows at most n calls. +GTEST_API_ Cardinality AtMost(int n); + +// Creates a cardinality that allows any number of calls. +GTEST_API_ Cardinality AnyNumber(); + +// Creates a cardinality that allows between min and max calls. +GTEST_API_ Cardinality Between(int min, int max); + +// Creates a cardinality that allows exactly n calls. +GTEST_API_ Cardinality Exactly(int n); + +// Creates a cardinality from its implementation. +inline Cardinality MakeCardinality(const CardinalityInterface* c) { + return Cardinality(c); +} + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-function-mocker.h b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-function-mocker.h new file mode 100644 index 0000000..d2cb13c --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-function-mocker.h @@ -0,0 +1,519 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements MOCK_METHOD. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ + +#include +#include // IWYU pragma: keep +#include // IWYU pragma: keep + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-pp.h" + +namespace testing { +namespace internal { +template +using identity_t = T; + +template +struct ThisRefAdjuster { + template + using AdjustT = typename std::conditional< + std::is_const::type>::value, + typename std::conditional::value, + const T&, const T&&>::type, + typename std::conditional::value, T&, + T&&>::type>::type; + + template + static AdjustT Adjust(const MockType& mock) { + return static_cast>(const_cast(mock)); + } +}; + +constexpr bool PrefixOf(const char* a, const char* b) { + return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); +} + +template +constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(prefix, str); +} + +template +constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(suffix, str + M - N); +} + +template +constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { + return N == M && internal::PrefixOf(a, b); +} + +template +constexpr bool ValidateSpec(const char (&spec)[N]) { + return internal::Equals("const", spec) || + internal::Equals("override", spec) || + internal::Equals("final", spec) || + internal::Equals("noexcept", spec) || + (internal::StartsWith("noexcept(", spec) && + internal::EndsWith(")", spec)) || + internal::Equals("ref(&)", spec) || + internal::Equals("ref(&&)", spec) || + (internal::StartsWith("Calltype(", spec) && + internal::EndsWith(")", spec)); +} + +} // namespace internal + +// The style guide prohibits "using" statements in a namespace scope +// inside a header file. However, the FunctionMocker class template +// is meant to be defined in the ::testing namespace. The following +// line is just a trick for working around a bug in MSVC 8.0, which +// cannot handle it if we define FunctionMocker in ::testing. +using internal::FunctionMocker; +} // namespace testing + +#define MOCK_METHOD(...) \ + GMOCK_INTERNAL_WARNING_PUSH() \ + GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ + GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \ + GMOCK_INTERNAL_WARNING_POP() + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ + GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ + GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ + GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ + GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ + (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_WRONG_ARITY(...) \ + static_assert( \ + false, \ + "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ + "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ + "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ + "it must also be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ + static_assert( \ + GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ + GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ + static_assert( \ + std::is_function<__VA_ARGS__>::value, \ + "Signature must be a function type, maybe return type contains " \ + "unprotected comma."); \ + static_assert( \ + ::testing::tuple_size::ArgumentTuple>::value == _N, \ + "This method does not take " GMOCK_PP_STRINGIZE( \ + _N) " arguments. Parenthesize all types with unprotected commas.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) + +#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ + _Override, _Final, _NoexceptSpec, \ + _CallType, _RefSpec, _Signature) \ + typename ::testing::internal::Function::Result \ + GMOCK_INTERNAL_EXPAND(_CallType) \ + _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) \ + _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \ + GMOCK_PP_IF(_Final, final, ) { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .SetOwnerAndName(this, #_MethodName); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) _RefSpec { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + const ::testing::internal::WithoutMatchers&, \ + GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ + GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \ + return ::testing::internal::ThisRefAdjuster::Adjust(*this) \ + .gmock_##_MethodName(GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ + } \ + mutable ::testing::FunctionMocker \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) + +#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ + +// Valid modifiers. +#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ + GMOCK_PP_HAS_COMMA( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) + +#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + +#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ + _elem, ) + +#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple) + +#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) + +#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \ + GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \ + "Token \'" GMOCK_PP_STRINGIZE( \ + _elem) "\' cannot be recognized as a valid specification " \ + "modifier. Is a ',' missing?"); +#else +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \ + GMOCK_PP_STRINGIZE( \ + _elem) " cannot be recognized as a valid specification modifier."); +#endif // GMOCK_INTERNAL_STRICT_SPEC_ASSERT + +// Modifiers implementation. +#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CONST_I_const , + +#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , + +#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_FINAL_I_final , + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , + +#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_REF_I_ref , + +#define GMOCK_INTERNAL_UNPACK_ref(x) x + +#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype , + +#define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__ + +// Note: The use of `identity_t` here allows _Ret to represent return types that +// would normally need to be specified in a different way. For example, a method +// returning a function pointer must be written as +// +// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...) +// +// But we only support placing the return type at the beginning. To handle this, +// we wrap all calls in identity_t, so that a declaration will be expanded to +// +// identity_t method(method_args_t...) +// +// This allows us to work around the syntactic oddities of function/method +// types. +#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ + ::testing::internal::identity_t( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) + +#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ + GMOCK_PP_IDENTITY) \ + (_elem) + +#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::std::forward(gmock_a##_i) + +#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ + GMOCK_PP_COMMA_IF(_i) \ + gmock_a##_i + +#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::testing::A() + +#define GMOCK_INTERNAL_ARG_O(_i, ...) \ + typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type + +#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \ + const ::testing::Matcher::template Arg<_i>::type>& + +#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__) +#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__) +#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__) +#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__) +#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__) +#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__) +#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__) +#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__) +#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__) +#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__) +#define MOCK_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__) +#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__) +#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__) +#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__) +#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__) +#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__) +#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__) +#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__) +#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__) +#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__) +#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__) + +#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__) +#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__) +#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__) +#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__) +#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__) +#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__) +#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__) +#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__) +#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__) +#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__) +#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + args_num, ::testing::internal::identity_t<__VA_ARGS__>); \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \ + (::testing::internal::identity_t<__VA_ARGS__>)) + +#define GMOCK_MOCKER_(arity, constness, Method) \ + GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ diff --git a/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-matchers.h b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-matchers.h new file mode 100644 index 0000000..aa3a5eb --- /dev/null +++ b/sw/restatdesk_tests/googletest/googlemock/include/gmock/gmock-matchers.h @@ -0,0 +1,5891 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The MATCHER* family of macros can be used in a namespace scope to +// define custom matchers easily. +// +// Basic Usage +// =========== +// +// The syntax +// +// MATCHER(name, description_string) { statements; } +// +// defines a matcher with the given name that executes the statements, +// which must return a bool to indicate if the match succeeds. Inside +// the statements, you can refer to the value being matched by 'arg', +// and refer to its type by 'arg_type'. +// +// The description string documents what the matcher does, and is used +// to generate the failure message when the match fails. Since a +// MATCHER() is usually defined in a header file shared by multiple +// C++ source files, we require the description to be a C-string +// literal to avoid possible side effects. It can be empty, in which +// case we'll use the sequence of words in the matcher name as the +// description. +// +// For example: +// +// MATCHER(IsEven, "") { return (arg % 2) == 0; } +// +// allows you to write +// +// // Expects mock_foo.Bar(n) to be called where n is even. +// EXPECT_CALL(mock_foo, Bar(IsEven())); +// +// or, +// +// // Verifies that the value of some_expression is even. +// EXPECT_THAT(some_expression, IsEven()); +// +// If the above assertion fails, it will print something like: +// +// Value of: some_expression +// Expected: is even +// Actual: 7 +// +// where the description "is even" is automatically calculated from the +// matcher name IsEven. +// +// Argument Type +// ============= +// +// Note that the type of the value being matched (arg_type) is +// determined by the context in which you use the matcher and is +// supplied to you by the compiler, so you don't need to worry about +// declaring it (nor can you). This allows the matcher to be +// polymorphic. For example, IsEven() can be used to match any type +// where the value of "(arg % 2) == 0" can be implicitly converted to +// a bool. In the "Bar(IsEven())" example above, if method Bar() +// takes an int, 'arg_type' will be int; if it takes an unsigned long, +// 'arg_type' will be unsigned long; and so on. +// +// Parameterizing Matchers +// ======================= +// +// Sometimes you'll want to parameterize the matcher. For that you +// can use another macro: +// +// MATCHER_P(name, param_name, description_string) { statements; } +// +// For example: +// +// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +// +// will allow you to write: +// +// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +// +// which may lead to this message (assuming n is 10): +// +// Value of: Blah("a") +// Expected: has absolute value 10 +// Actual: -9 +// +// Note that both the matcher description and its parameter are +// printed, making the message human-friendly. +// +// In the matcher definition body, you can write 'foo_type' to +// reference the type of a parameter named 'foo'. For example, in the +// body of MATCHER_P(HasAbsoluteValue, value) above, you can write +// 'value_type' to refer to the type of 'value'. +// +// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to +// support multi-parameter matchers. +// +// Describing Parameterized Matchers +// ================================= +// +// The last argument to MATCHER*() is a string-typed expression. The +// expression can reference all of the matcher's parameters and a +// special bool-typed variable named 'negation'. When 'negation' is +// false, the expression should evaluate to the matcher's description; +// otherwise it should evaluate to the description of the negation of +// the matcher. For example, +// +// using testing::PrintToString; +// +// MATCHER_P2(InClosedRange, low, hi, +// std::string(negation ? "is not" : "is") + " in range [" + +// PrintToString(low) + ", " + PrintToString(hi) + "]") { +// return low <= arg && arg <= hi; +// } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: is in range [4, 6] +// ... +// Expected: is not in range [2, 4] +// +// If you specify "" as the description, the failure message will +// contain the sequence of words in the matcher name followed by the +// parameter values printed as a tuple. For example, +// +// MATCHER_P2(InClosedRange, low, hi, "") { ... } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: in closed range (4, 6) +// ... +// Expected: not (in closed range (2, 4)) +// +// Types of Matcher Parameters +// =========================== +// +// For the purpose of typing, you can view +// +// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +// +// as shorthand for +// +// template +// FooMatcherPk +// Foo(p1_type p1, ..., pk_type pk) { ... } +// +// When you write Foo(v1, ..., vk), the compiler infers the types of +// the parameters v1, ..., and vk for you. If you are not happy with +// the result of the type inference, you can specify the types by +// explicitly instantiating the template, as in Foo(5, +// false). As said earlier, you don't get to (or need to) specify +// 'arg_type' as that's determined by the context in which the matcher +// is used. You can assign the result of expression Foo(p1, ..., pk) +// to a variable of type FooMatcherPk. This +// can be useful when composing matchers. +// +// While you can instantiate a matcher template with reference types, +// passing the parameters by pointer usually makes your code more +// readable. If, however, you still want to pass a parameter by +// reference, be aware that in the failure message generated by the +// matcher you will see the value of the referenced object but not its +// address. +// +// Explaining Match Results +// ======================== +// +// Sometimes the matcher description alone isn't enough to explain why +// the match has failed or succeeded. For example, when expecting a +// long string, it can be very helpful to also print the diff between +// the expected string and the actual one. To achieve that, you can +// optionally stream additional information to a special variable +// named result_listener, whose type is a pointer to class +// MatchResultListener: +// +// MATCHER_P(EqualsLongString, str, "") { +// if (arg == str) return true; +// +// *result_listener << "the difference: " +/// << DiffStrings(str, arg); +// return false; +// } +// +// Overloading Matchers +// ==================== +// +// You can overload matchers with different numbers of parameters: +// +// MATCHER_P(Blah, a, description_string1) { ... } +// MATCHER_P2(Blah, a, b, description_string2) { ... } +// +// Caveats +// ======= +// +// When defining a new matcher, you should also consider implementing +// MatcherInterface or using MakePolymorphicMatcher(). These +// approaches require more work than the MATCHER* macros, but also +// give you more control on the types of the value being matched and +// the matcher parameters, which may leads to better compiler error +// messages when the matcher is used wrong. They also allow +// overloading matchers based on parameter types (as opposed to just +// based on the number of parameters). +// +// MATCHER*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// +// More Information +// ================ +// +// To learn more about using these macros, please search for 'MATCHER' +// on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md +// +// This file also implements some commonly used argument matchers. More +// matchers can be defined by the user implementing the +// MatcherInterface interface if necessary. +// +// See googletest/include/gtest/gtest-matchers.h for the definition of class +// Matcher, class MatcherInterface, and others. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // NOLINT +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" +#include "gtest/gtest.h" + +// MSVC warning C5046 is new as of VS2017 version 15.8. +#if defined(_MSC_VER) && _MSC_VER >= 1915 +#define GMOCK_MAYBE_5046_ 5046 +#else +#define GMOCK_MAYBE_5046_ +#endif + +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by + clients of class B */ + /* Symbol involving type with internal linkage not defined */) + +namespace testing { + +// To implement a matcher Foo for type T, define: +// 1. a class FooMatcherImpl that implements the +// MatcherInterface interface, and +// 2. a factory function that creates a Matcher object from a +// FooMatcherImpl*. +// +// The two-level delegation design makes it possible to allow a user +// to write "v" instead of "Eq(v)" where a Matcher is expected, which +// is impossible if we pass matchers by pointers. It also eases +// ownership management as Matcher objects can now be copied like +// plain values. + +// A match result listener that stores the explanation in a string. +class StringMatchResultListener : public MatchResultListener { + public: + StringMatchResultListener() : MatchResultListener(&ss_) {} + + // Returns the explanation accumulated so far. + std::string str() const { return ss_.str(); } + + // Clears the explanation accumulated so far. + void Clear() { ss_.str(""); } + + private: + ::std::stringstream ss_; + + StringMatchResultListener(const StringMatchResultListener&) = delete; + StringMatchResultListener& operator=(const StringMatchResultListener&) = + delete; +}; + +// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION +// and MUST NOT BE USED IN USER CODE!!! +namespace internal { + +// The MatcherCastImpl class template is a helper for implementing +// MatcherCast(). We need this helper in order to partially +// specialize the implementation of MatcherCast() (C++ allows +// class/struct templates to be partially specialized, but not +// function templates.). + +// This general version is used when MatcherCast()'s argument is a +// polymorphic matcher (i.e. something that can be converted to a +// Matcher but is not one yet; for example, Eq(value)) or a value (for +// example, "hello"). +template +class MatcherCastImpl { + public: + static Matcher Cast(const M& polymorphic_matcher_or_value) { + // M can be a polymorphic matcher, in which case we want to use + // its conversion operator to create Matcher. Or it can be a value + // that should be passed to the Matcher's constructor. + // + // We can't call Matcher(polymorphic_matcher_or_value) when M is a + // polymorphic matcher because it'll be ambiguous if T has an implicit + // constructor from M (this usually happens when T has an implicit + // constructor from any type). + // + // It won't work to unconditionally implicit_cast + // polymorphic_matcher_or_value to Matcher because it won't trigger + // a user-defined conversion from M to T if one exists (assuming M is + // a value). + return CastImpl(polymorphic_matcher_or_value, + std::is_convertible>{}, + std::is_convertible{}); + } + + private: + template + static Matcher CastImpl(const M& polymorphic_matcher_or_value, + std::true_type /* convertible_to_matcher */, + std::integral_constant) { + // M is implicitly convertible to Matcher, which means that either + // M is a polymorphic matcher or Matcher has an implicit constructor + // from M. In both cases using the implicit conversion will produce a + // matcher. + // + // Even if T has an implicit constructor from M, it won't be called because + // creating Matcher would require a chain of two user-defined conversions + // (first to create T from M and then to create Matcher from T). + return polymorphic_matcher_or_value; + } + + // M can't be implicitly converted to Matcher, so M isn't a polymorphic + // matcher. It's a value of a type implicitly convertible to T. Use direct + // initialization to create a matcher. + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::true_type /* convertible_to_T */) { + return Matcher(ImplicitCast_(value)); + } + + // M can't be implicitly converted to either Matcher or T. Attempt to use + // polymorphic matcher Eq(value) in this case. + // + // Note that we first attempt to perform an implicit cast on the value and + // only fall back to the polymorphic Eq() matcher afterwards because the + // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end + // which might be undefined even when Rhs is implicitly convertible to Lhs + // (e.g. std::pair vs. std::pair). + // + // We don't define this method inline as we need the declaration of Eq(). + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::false_type /* convertible_to_T */); +}; + +// This more specialized version is used when MatcherCast()'s argument +// is already a Matcher. This only compiles when type T can be +// statically converted to type U. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& source_matcher) { + return Matcher(new Impl(source_matcher)); + } + + private: + // If it's possible to implicitly convert a `const T&` to U, then `Impl` can + // take that as input to avoid a copy. Otherwise, such as when `T` is a + // non-const reference type or a type explicitly constructible only from a + // non-const reference, then `Impl` must use `T` as-is (potentially copying). + using ImplArgT = + typename std::conditional::value, + const T&, T>::type; + + class Impl : public MatcherInterface { + public: + explicit Impl(const Matcher& source_matcher) + : source_matcher_(source_matcher) {} + + // We delegate the matching logic to the source matcher. + bool MatchAndExplain(ImplArgT x, + MatchResultListener* listener) const override { + using FromType = typename std::remove_cv::type>::type>::type; + using ToType = typename std::remove_cv::type>::type>::type; + // Do not allow implicitly converting base*/& to derived*/&. + static_assert( + // Do not trigger if only one of them is a pointer. That implies a + // regular conversion and not a down_cast. + (std::is_pointer::type>::value != + std::is_pointer::type>::value) || + std::is_same::value || + !std::is_base_of::value, + "Can't implicitly convert from to "); + + // Do the cast to `U` explicitly if necessary. + // Otherwise, let implicit conversions do the trick. + using CastType = typename std::conditional< + std::is_convertible::value, ImplArgT&, U>::type; + + return source_matcher_.MatchAndExplain(static_cast(x), + listener); + } + + void DescribeTo(::std::ostream* os) const override { + source_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + source_matcher_.DescribeNegationTo(os); + } + + private: + const Matcher source_matcher_; + }; +}; + +// This even more specialized version is used for efficiently casting +// a matcher to its own type. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& matcher) { return matcher; } +}; + +// Template specialization for parameterless Matcher. +template +class MatcherBaseImpl { + public: + MatcherBaseImpl() = default; + + template + operator ::testing::Matcher() const { // NOLINT(runtime/explicit) + return ::testing::Matcher(new + typename Derived::template gmock_Impl()); + } +}; + +// Template specialization for Matcher with parameters. +template