Developing and testing Sonde

This guide is for people changing the library: fixing bugs, adding tools or features. It covers setting up a build, running and writing tests, the quality checks every change must pass, and two worked examples. Read architecture.md first for how the code fits together.

Set up

The quickest way is mise-en-place. The repository’s mise.toml pins CMake, Ninja, Python and the exact clang-format version the code is formatted with:

mise install        # the pinned tools, into mise's own directory
mise run setup      # configure build/ (Debug, Ninja) and install the git hooks
mise tasks          # build, test, format, lint, check, fuzz, chaos, package-test, docker-test

mise doesn’t install Qt or LLVM. Get those as described below.

Without mise, you need:

Tool Version Used for
Qt 6.8 or newer, with Core, Network, Gui, Widgets, Quick, Qml and Test building and testing
CMake 3.24 or newer the build
Ninja any recent version recommended generator (make also works)
A C++17 compiler Clang, GCC or MSVC the build. Coverage needs Clang.
Python 3 3.8 or newer the end-to-end, package and Docker tests, and tools/check.py (using Sonde doesn’t need it)
clang-tidy and run-clang-tidy from LLVM the clang-tidy target
Doxygen 1.9.5 or newer the docs target
clang-format exactly the version in mise.toml (23.1.5) formatting; other versions format some code differently
git   GoogleTest is fetched with git if it is not installed

On macOS with Homebrew:

brew install qt cmake ninja llvm doxygen

Homebrew’s llvm provides clang-tidy. You don’t have to change your compiler: the build still uses Apple’s clang, and the tooling finds /opt/homebrew/opt/llvm/bin/clang-tidy by itself.

If your Qt is somewhere CMake doesn’t look (for example from the Qt online installer), tell CMake where it is:

cmake -S . -B build -G Ninja -DCMAKE_PREFIX_PATH=$HOME/Qt/6.8.3/macos

GoogleTest does not need to be installed. If CMake can’t find an installed copy, it downloads v1.17.0 during configuration, so the first configure needs network access.

Code style and git hooks

The code follows the Qt project’s style: .clang-format holds the settings of Qt’s own _clang-format (4-space indents, 100 columns, the brace and line-break rules Qt’s sources use). Don’t format by hand:

mise run format          # or: python3 tools/check.py format

The git hooks in .githooks/ check every commit and push. mise run setup installs them, or run python3 tools/check.py hooks, which sets git config core.hooksPath .githooks.

Hook Checks Typical time
pre-commit The staged C++ files are formatted (their staged content); a file that isn’t is formatted and staged again, unless it also has unstaged changes, which stops the commit. Staged Python files compile. If Markdown is staged, the documentation links resolve. If code or build files are staged: build, unit tests and smoke test. about 20 s; a few seconds for documentation-only commits
pre-push Every C++ file is formatted, then build, unit tests, smoke test, clang-tidy, Doxygen and the link check. about 1 minute

Both hooks run tools/check.py, which also runs the checks by hand: mise run test, mise run lint, mise run format-check, mise run check (everything the pre-push hook runs).

Things to know:

The slower checks are not in the hooks, so run them yourself when they apply: coverage, the sanitizers, the fuzzers (mise run fuzz) and the Docker test (mise run docker-test).

Continuous integration

.github/workflows/ci.yml runs on every push to any branch and every pull request. It catches what the hooks can’t: other platforms, other Qt versions, and pushes or pull requests made without the hooks.

Job Runs Where
test tools/check.py test, then the smoke test again with SONDE_THREADED=1 Linux with Qt 6.8 and GCC, macOS with Qt 6.12 and Apple Clang, Windows with Qt 6.8 and MSVC
lint format check, link check, clang-tidy and Doxygen, with the versions the hooks use (clang-format 23.1.5, LLVM 23, Doxygen 1.18) Linux with Qt 6.12 and Clang 23
chaos the chaos test, 3 fixed and 3 random seeds in both threading modes, in its container (below) Linux
docker tests/docker_test.py: Debian’s packaged Qt 6.8, and the container workflows Linux

Design: 0024.

Build

cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
cmake --build build

This builds the libraries, sonde-bridge, both demos and both test programs.

Build options (pass as -D<option>=ON|OFF):

Option Default Effect
SONDE_BUILD_GUI ON Build Sonde::Gui
SONDE_BUILD_WIDGETS ON Build Sonde::Widgets if Qt Widgets is found
SONDE_BUILD_QUICK ON Build Sonde::Quick if Qt Quick is found
SONDE_BUILD_BRIDGE ON Build sonde-bridge
SONDE_BUILD_EXAMPLES ON when top-level Build the demos
SONDE_BUILD_TESTS ON when top-level Build the unit tests
SONDE_STRICT_WARNINGS ON when top-level Build Sonde’s own targets with a strict warning set, as errors (see Warnings)
SONDE_INSTALL_SHELL_FILES ON Install the man pages and the bash and zsh completions (written at build time; never on Windows or when cross-compiling)
SONDE_COVERAGE OFF Instrument for coverage and add the coverage target (Clang only)
BUILD_SHARED_LIBS OFF Build shared instead of static libraries

Use a separate build directory for each configuration, for example build for everyday work and build-cov for coverage. All build*/ directories are ignored by git.

Warnings

Sonde builds with a strict set of warnings, as errors, set in cmake/SondeWarnings.cmake: -Wall -Wextra -Wpedantic, -Wshadow, -Woverloaded-virtual, -Wold-style-cast, -Wconversion -Wsign-conversion and more, for GCC and Clang. The reason: an application that adds Sonde with FetchContent compiles Sonde’s sources with its own flags, and many applications turn warnings into errors. A warning Sonde lets through can break someone else’s build.

Run the demos

build/examples/widgets/sonde-widgets-demo           # HTTP on 8765, local socket "sonde-widgets-demo"
build/examples/quick/sonde-quick-demo               # HTTP on 8766, local socket "sonde-quick-demo"
SONDE_HTTP=8799 build/examples/acme-orders/acme-orders   # the walkthrough's app (has a deliberate bug)

To run without opening a window (on a server, or so it doesn’t get in your way):

QT_QPA_PLATFORM=offscreen build/examples/widgets/sonde-widgets-demo

Then connect a client as described in using.md. The demos are the quickest way to try a change by hand.

Tests

There are two kinds:

Kind Where What it covers How to run
Unit tests (GoogleTest) tests/core/, tests/gui/ Everything in the libraries, in-process, including the real transports ctest --test-dir build
The same unit tests in WorkerThread mode the same programs, as tests named *.worker Everything again, with the transports on a worker thread (SONDE_THREADED=1) ctest --test-dir build (runs both)
End-to-end smoke test (Python) tests/smoke_test.py, with its parts in tests/smoke/ (the transports; the sonde command on a project) The demo application, sonde-bridge and the sonde command (build/sonde) as separate processes python3 tests/smoke_test.py build
Package test (Python) tests/package_test.py Installing Sonde, moving the install, and building and running an application against it with find_package python3 tests/package_test.py build
Chaos test (only in its container) tests/chaos/ Random changes to an application while random tool calls, cancellations and disconnections hit it (below) python3 tests/chaos/run.py
Docker test (Python) tests/docker_test.py Building against Qt 6.8 in Debian, and the container workflows in containers.md python3 tests/docker_test.py

The Python tests share tests/mcptest.py: check() and the summary, MCP clients over HTTP and over a command’s stdio, and a line reader with a timeout. They use only the standard library.

The unit tests are built into three programs:

Running tests

ctest --test-dir build                         # everything (add -j8 to run in parallel)
ctest --test-dir build -R 'HttpTest\.'         # tests whose name matches a regex
ctest --test-dir build --output-on-failure     # show the output of failing tests

ctest runs each test case as its own process. To run a test program directly, which is faster when you are iterating and easier to debug:

QT_QPA_PLATFORM=offscreen build/tests/sonde_core_tests --gtest_filter='ToolCallTest.*'
build/tests/sonde_core_tests --gtest_list_tests

The GUI test program sets QT_QPA_PLATFORM=offscreen itself if it isn’t set. To watch the GUI tests on your screen, set QT_QPA_PLATFORM=cocoa (macOS), xcb or wayland (Linux), or windows.

Writing tests

The helpers

tests/support/testsupport.h has everything needed to talk to a server from a test, without starting another process:

Helper Use
waitUntil(predicate, timeoutMs) Run the event loop until the predicate is true. Use it instead of sleep.
spin(ms) Run the event loop for a fixed time. Only use it when you need nothing to happen, e.g. to check that no notification arrives.
uniqueName(prefix) A local socket name no other test uses.
LocalClient An MCP client over the local socket: initialize(), request(), callTool(), callToolText(), notify(), sendRaw(), notifications(), waitForNotification().
HttpClient An MCP client over HTTP: initialize(), request(), post().
http(), rawHttp() Send one HTTP request, or exact raw bytes (for malformed requests and pipelining).
SseStream Open GET /mcp and collect the server-sent events.
resultText(result) The text blocks of a tool result, joined.

tests/support/testobject.h defines TestObject, a QObject with properties of many types, an enum, a flags type, slots and invokable methods, for introspection and conversion tests.

tests/gui/guifixture.h defines GuiTest: a fixture with a server that has all tools and integrations installed, a widget form (edit, button, check, slider, list, hiddenLabel, and a Ctrl+K shortcut) and a QML window (box, input). It provides call(), text() and fails() shortcuts for calling tools.

An example

#include <sonde/server.h>

#include "testsupport.h"

#include <gtest/gtest.h>

using namespace Sonde;
using namespace SondeTest;

TEST(MyFeature, EchoToolReturnsItsArgument)
{
    Server server;
    const QString name = uniqueName(QStringLiteral("myfeature"));
    ASSERT_TRUE(server.listenLocal(name));

    ToolDefinition def;
    def.name = QStringLiteral("echo");
    server.addTool(def, [](const QJsonObject &args) {
        return ToolResult::text(args.value(QStringLiteral("text")).toString());
    });

    LocalClient client(name);
    client.initialize();
    EXPECT_EQ(client.callToolText(QStringLiteral("echo"), {{QStringLiteral("text"), QStringLiteral("hi")}}),
              QStringLiteral("hi"));
}

Add a new test file to the sonde_add_test(...) list in tests/CMakeLists.txt.

Tips and traps

Coverage

cmake -S . -B build-cov -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_COVERAGE=ON -DSONDE_BUILD_EXAMPLES=OFF
cmake --build build-cov
cmake --build build-cov --target coverage

The coverage target runs all unit tests, then prints a per-file table for the library sources (not tests, examples or the bridge). It also writes an HTML report that shows each line’s hit count: open build-cov/coverage/html/index.html.

The project’s bar is at least 80% line coverage of the libraries. It is currently about 97%. A change should not lower coverage noticeably: new code comes with tests for its success and error paths. The remaining gaps are mostly paths behind long timers (the 15-second SSE ping, 30-minute session expiry) and defensive branches that cannot be reached from outside.

Coverage needs Clang. The coverage target uses llvm-cov and llvm-profdata (from Xcode on macOS, or from your LLVM installation).

Static analysis with clang-tidy

cmake --build build --target clang-tidy

This runs clang-tidy over every .cpp file under src, tools, examples and tests, using the configuration in .clang-tidy. That configuration enables the bugprone, cert, clang-analyzer, concurrency, cppcoreguidelines, misc, modernize, performance, portability and readability check groups, and any finding fails the target. The file lists the checks that are switched off, with the reason for each. Most clash with ordinary Qt code (parent-owned new, QStringLiteral, implicit QPointer to bool).

Two limits keep functions readable:

Nested lambdas count towards the function that contains them. So a tool is written as named functions (a handler, plus an install...() that registers it), not as one long installer full of lambdas. See src/core/introspectiontools.cpp for the pattern.

When clang-tidy reports something:

  1. Fix the code. This is almost always the right answer.
  2. If the finding is wrong for this one line, suppress it on that line with the reason:
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): QKeySequence has no at(); i < count()
    

    A NOLINT without a reason will not pass review.

  3. Only change .clang-tidy if a check is wrong for the whole project, and explain why in the comment at the top of that file.

Be careful with -fix. clang-tidy can rewrite code automatically (run-clang-tidy -fix), but review every change it makes before committing. In this project an automatic cppcoreguidelines-prefer-member-initializer fix once changed LogEventSource so that a second, inactive instance believed it was active. Its destructor would then have removed the first instance’s message handler. Commit or stash your work before running -fix, so you can diff the result.

Sanitizers

The compiler’s sanitizers find undefined behaviour and memory errors that tests alone can miss. Run the whole suite under each before a release, and after any change to parsing, number conversion, or object lifetimes:

# Undefined behaviour: overflow, out-of-range conversions, bad casts, ...
cmake -S . -B build-ubsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_BUILD_EXAMPLES=OFF \
      -DCMAKE_CXX_FLAGS="-fsanitize=undefined,float-cast-overflow -fno-sanitize-recover=all" \
      -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=undefined"
cmake --build build-ubsan && ctest --test-dir build-ubsan

# Memory errors: use after free, use after scope, buffer overflows
cmake -S . -B build-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_BUILD_EXAMPLES=OFF \
      -DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer" \
      -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address"
cmake --build build-asan && ASAN_OPTIONS=detect_leaks=0 ctest --test-dir build-asan

# Data races: ThreadSanitizer (works with a normal, uninstrumented Qt; see below)
cmake -S . -B build-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_BUILD_EXAMPLES=OFF \
      -DCMAKE_CXX_FLAGS="-fsanitize=thread" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread"
cmake --build build-tsan && QT_QPA_PLATFORM=offscreen ctest --test-dir build-tsan

ThreadSanitizer usually needs every library built with it, because it can’t see the locking inside uninstrumented code, Qt’s event queue included. Sonde gets around that: whatever it hands from one thread to another goes through HomeLink, which takes a mutex TSan can see on both sides. So TSan runs against a normal Qt. Hand-overs of your own (a QMetaObject::invokeMethod carrying data from another thread) should go through HomeLink too, or TSan will report them.

Any report is a bug, in test code as much as in the library. Undefined behaviour often “works” on one machine: an out-of-range double to quint64 cast happens to saturate on Apple silicon, for example. That is why a passing test is not proof that none is there.

ThreadSanitizer, weekly

Against a normal Qt, TSan only sees the hand-overs that go through HomeLink. The TSan workflow runs every Sunday, and by hand from the Actions tab, against Qt 6.8’s qtbase and qtdeclarative built with ThreadSanitizer too, so it sees Qt’s own locking and event queue as well (design 0032):

Fuzzing

A fuzzer calls the code with millions of generated inputs. It keeps the inputs that reach new code, mutates them, and stops when one makes the program crash or trips a sanitizer. It finds the inputs nobody thinks of writing a test for. Sonde uses libFuzzer for the code that reads what clients send:

Target What it feeds What it checks
fuzz_http_parser Raw bytes to Http::parseRequest (as a stream of pipelined requests), decodeChunked and bearerTokenMatches No crash or UB. Nothing is consumed unless a request completes, every complete request consumes input, bodies stay within the limit, and errors are 4xx
fuzz_jsonrpc Lines of JSON to ServerPrivate::handleMessage, with the introspection tools, an event source and an echo tool installed No crash or UB. Every request gets at most one reply, and every request other than tools/call is answered before handleMessage returns
fuzz_json_variant JSON to ObjectTree::jsonToVariant for 20 property types, then back with variantToJson; the same text as an object spec to ObjectTree::find No crash or UB

Apple’s clang doesn’t include libFuzzer, so the fuzzers are built and run in a Debian container. You need Docker:

python3 tests/fuzz/run.py                 # all targets, 60 s each
python3 tests/fuzz/run.py --seconds 600 fuzz_jsonrpc

The script builds the sonde-fuzz image from tests/fuzz/Dockerfile, then runs each target with AddressSanitizer and UndefinedBehaviorSanitizer. The inputs a run finds interesting are kept in build-fuzz/corpus/<target>/ and reused next time, so later runs start where earlier ones stopped. The hand-written starting inputs (“seeds”) are in tests/fuzz/corpus/<target>/ and are always included.

When a target crashes, the script prints the report and the input is saved in build-fuzz/crashes/. To reproduce it:

docker run --rm -v "$PWD/build-fuzz:/out" sonde-fuzz build/tests/fuzz/fuzz_jsonrpc /out/crashes/<file>

Then fix it like any other bug:

  1. Write a unit test that fails with the crashing input (shortened by hand to what matters).
  2. Fix the bug.
  3. Copy the crashing input into tests/fuzz/corpus/<target>/ with a name that says what it was, so every later run tries it first.

On Linux with clang you can also build the fuzzers directly: CC=clang CXX=clang++ cmake -S . -B build-fuzz-native -DSONDE_BUILD_FUZZERS=ON. The option compiles the whole library with -fsanitize=fuzzer-no-link,address,undefined, so use a separate build directory.

Adding a target: add fuzz_<name>.cpp to tests/fuzz/, with an extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) function. Add sonde_add_fuzzer(fuzz_<name>) to tests/fuzz/CMakeLists.txt, put a few seeds in tests/fuzz/corpus/fuzz_<name>/, and add the name to TARGETS in run.py. Check invariants with std::abort(), not assert, so they also work in a release build. Keep per-input work small: a slow target explores less. Shared state such as a QCoreApplication goes in a static fixture, created once.

Run the fuzzers for a few minutes after any change to httpparser.cpp, JSON-RPC dispatch, argument validation, or the JSON conversion code.

The chaos test

The chaos test (design 0029) changes a running application at random (widgets, Qt Quick items, windows, models, short stalls of the main thread) while clients call tools with arguments drawn from their schemas, cancel calls and disconnect. After every step it checks that each request got exactly one well-formed answer, and that a tool’s failure is a tool error, not a protocol error. At the end it checks that the main thread answers and nothing is left behind.

It runs only in a disposable container, never on your machine: nobody has read what a given seed will do. The program is built only with SONDE_BUILD_CHAOS, which a normal build leaves off, and refuses to start without its image’s marker.

python3 tests/chaos/run.py                         # 3 fixed + 3 random seeds, both modes, 300 steps
python3 tests/chaos/run.py --variant address 42    # one seed, with AddressSanitizer and UBSan
python3 tests/chaos/run.py --steps 1000 --random 10
mise run chaos

run.py builds the image (sonde-chaos-none, -address or -thread) and runs the seeds in one new container, with --rm, no network, no capabilities, no new privileges, a read-only root filesystem, and limits on memory, CPUs and processes. Only build-chaos-out/ is mounted.

Documentation comments

cmake --build build --target docs

This runs Doxygen with the Doxyfile configuration and writes HTML to build/docs/html/index.html. Each published release also puts them on the website, under api/, with the release’s version (docs.yml). Every class, function, member variable and enum value must have a doc comment, including private and internal ones. Any undocumented entity, or a malformed comment, fails the target. Test case bodies (TEST, TEST_F) are exempt; fixtures and helpers in test files are not.

The style used throughout:

/// @brief One sentence saying what it does.
///
/// Optional details: when to use it, what to watch out for.
/// @param name   Only when the meaning isn't obvious from the name.
/// @return       Only when it isn't obvious.
QString describe(const QObject *object);

int count = 0;  ///< Short description, for members.

Each source file starts with a /// @file block saying what the file is for.

The guides in notes/ are not processed by Doxygen, because it cannot resolve their GitHub-style section links. The reference’s front page is notes/api-reference.md, which avoids Markdown links for that reason.

Known problem: Doxygen 1.18.0 occasionally crashes with “Bus error” (exit status 138) on this project, about one run in six. This is a Doxygen bug, not a documentation problem. Run the target again. Real documentation problems are reported as warning: or error: lines that name a file.

Guides like this one live in notes/. If your change affects behaviour a guide describes, update the guide in the same change.

Worked example: adding a tool

Suppose we want a clipboard_text tool that returns the clipboard’s text. It needs QtGui, so it belongs in src/gui/ (see architecture.md, “Where to put new code”).

1. Write the tool. Add it to installWindowTools() in src/gui/windowtools.cpp, following the other tools there:

// --- clipboard_text -------------------------------------------------------
{
    ToolDefinition def;
    def.name = QStringLiteral("clipboard_text");
    def.title = QStringLiteral("Clipboard text");
    def.description = QStringLiteral("The text currently on the clipboard (empty if it holds no text).");
    def.annotations = QJsonObject{{QStringLiteral("readOnlyHint"), true}};
    server.addTool(def, [](const QJsonObject &) {
        return ToolResult::text(QGuiApplication::clipboard()->text());
    });
}

Write the description for the AI that will read it. Say what comes back and what happens in the edge cases.

2. Test it. In tests/gui/test_windows.cpp:

TEST_F(GuiTest, ClipboardText)
{
    QGuiApplication::clipboard()->setText(QStringLiteral("copied"));
    EXPECT_EQ(text(QStringLiteral("clipboard_text")), QStringLiteral("copied"));
}

3. Document it. Add the tool to the table in using.md and in the repository README.

4. Check everything with the list in Before you ask for review.

Worked example: fixing a bug

Suppose input_keys with "é" types É. This really happened. The process:

  1. Reproduce it in a test. In tests/gui/test_input.cpp, the KeyPressAndShortcuts test presses é and expects the line edit to contain é. Run it and see it fail:
    cmake --build build && build/tests/sonde_gui_tests --gtest_filter='GuiTest.KeyPressAndShortcuts'
    
  2. Find the cause. textForKey() in src/gui/inputtools.cpp lower-cased ASCII letters only. Qt key codes for letters are always upper case, so the non-ASCII branch returned É.
  3. Fix it with the smallest change that makes the test pass. Here, apply the Shift rule to non-ASCII characters too.
  4. Run the whole suite, clang-tidy and docs, not just the one test.

Debugging tips

Before you ask for review

Run all of these and make sure they pass:

mise run check                               # formatting, build, tests, smoke test, clang-tidy, Doxygen, links
mise run docker-test                         # Qt 6.8 build + container workflows (needs Docker)
cmake --build build-cov --target coverage    # coverage still at or above the bar

mise run check is what the pre-push hook runs. Without mise, run python3 tools/check.py pre-push. The individual commands are cmake --build build, ctest --test-dir build, python3 tests/smoke_test.py build, cmake --build build --target clang-tidy, cmake --build build --target docs and python3 tests/check_links.py.

If you touched parsing, number conversion or object lifetimes, also run the sanitizers. If you touched the HTTP parser, dispatch or JSON conversion, run the fuzzers for a few minutes too.

Then check your change against reviewing.md. The reviewer will.

Making a release

Releases are made from master, once its CI is green:

  1. Run the sanitizers (UBSan and ASan) over the whole suite.
  2. Review the examples. The README’s “See it in action” list should name the three to five examples that best show what Sonde can do. When an example has been added or has grown, ask whether it belongs there, and what it would replace. Check that every folder in examples/ has a README, and a row in examples/README.md.
  3. Make the release commit, “Release X.Y.Z”, with:
    • the version in the top-level CMakeLists.txt;
    • the changelog’s “Unreleased” heading changed to “X.Y.Z (date)”;
    • the versions in the README’s and using.md’s find_package(Sonde X.Y ...) and GIT_TAG vX.Y.Z lines.
  4. Tag it vX.Y.Z, annotated “Sonde X.Y.Z”, and push master and the tag together.
  5. Publish the GitHub release once CI is green, titled “Sonde X.Y.Z”. Use the changelog section as the notes, with its links made absolute to the tag (https://github.com/asgeir/sonde/blob/vX.Y.Z/...). Publishing puts the documentation of that version on the website.