Testing¶
This page shows how to test a node at five levels, from a plain pytest run on your laptop to a memory profile inside the node image. After reading it you can write unit tests that drive the real node class through the same hooks the engine calls, check that the schema file and the code agree, know what the Mock Runner does and does not prove, run custom triggers over a real broker without an engine, verify a deployment on an engine, and check a node for memory leaks.
| Layer | Tool | Proves | Needs |
|---|---|---|---|
| 1 | pytest + FakeDataFlow |
hook logic, port names, message types, schema-vs-code | Python only |
| 2 | Mock Runner | configure, data flow between wired nodes, typed config, log output | Docker |
| 3 | run_local_demo.py + mosquitto |
custom trigger wiring over a real broker | Docker + SDK install |
| 4 | an engine | registration, palette entry, end-to-end graph | platform access |
| 5 | neuraverse-node-profiler |
no memory or thread growth across configure/stop cycles | node image |
Layer 1: unit tests with pytest¶
Test the real node class, not a mock of it. The engine calls your hooks in a fixed way, and a unit test should call them the same way:
- Instantiate the class.
__init__must stay side-effect free, so this is cheap. - Replace the data flow with an in-memory adapter:
node.data_flow = FakeDataFlow(). - Call
on_configure(config, dynamic_config)with two arguments, the wayconfigure()does. The static string map comes from the schema'sconfigurationblock; passNone(or a typed map built fromon_get_configuration()) as the second argument. - Put one message object per data input into
input_ports, then callon_execute(). - Assert on
published[<port>]: the objects there must be ROS 2 message instances with the value you expect.
Do not mock get_data and publish
A test such as node.get_data = MagicMock(return_value=10) passes while the node is broken:
the real adapters return message objects (read msg.data), return None when nothing has
arrived, and silently drop anything passed to publish() that is not a message object. Drive
the node through a fake data flow instead so those contracts are part of the test.
The fake data flow¶
FakeDataFlow implements the SDK's IDataFlow interface in memory. get_data() latches like
the production adapters: it returns the last message stored for a port, the same one on every
call, and None for a port nothing was written to. publish() appends to published[port].
The lifecycle methods are no-ops.
"""An in-memory ``IDataFlow`` for driving example nodes in unit tests.
``FakeDataFlow`` replaces the ROS/MQTT adapters the SDK wires up at runtime. Put a message
per input port into ``input_ports``, assign the instance to ``node.data_flow``, run the hook
under test and read what the node published from ``published``::
node = MathAddNode()
node.data_flow = FakeDataFlow()
node.on_configure({}, None)
node.data_flow.input_ports["a"] = Float32(data=1.0)
node.data_flow.input_ports["b"] = Float32(data=2.0)
node.on_execute()
assert node.data_flow.published["sum"][0].data == 3.0
``get_data()`` latches like the production adapters do: repeated calls return the same last
value, and an unconnected port returns ``None``. Every other adapter method is a no-op.
"""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from neuraverse_sdk.dataflow.i_dataflow import IDataFlow
class FakeDataFlow(IDataFlow):
"""In-memory data flow adapter: ``input_ports`` in, ``published`` out."""
def __init__(self) -> None:
super().__init__()
self.input_ports: dict[str, Any] = {}
self.published: dict[str, list[Any]] = {}
# -- lifecycle (no-ops) ------------------------------------------------------------------
def init(self, config: Any) -> None:
pass
def configure(self, node_data_flow_entry: Any) -> None:
pass
def destroy(self) -> None:
pass
# -- data --------------------------------------------------------------------------------
def get_data(self, placeholder: str, timeout: float | None = 1.0) -> Any:
"""Return the latched message for ``placeholder`` or ``None`` when nothing arrived."""
return self.input_ports.get(placeholder)
def publish(self, target: str, message: Any, meta_data: Any = None) -> None:
"""Record ``message`` under ``published[target]`` in arrival order."""
self.published.setdefault(target, []).append(message)
def receive(self, input_name: str, message: Any) -> None:
"""Simulate an incoming message: latch it and run a registered handler, if any."""
self.input_ports[input_name] = message
handler = self.message_handlers.get(input_name)
if handler is not None:
handler(message)
else:
self.handle_message(input_name, message, {"topic_name": input_name})
def register_handler(self, callback: Callable[[Any], None], input_name: str = "") -> None:
"""Mirror ``CompositeDataFlow.register_handler``: per-port callback or catch-all."""
if input_name:
self.message_handlers[input_name] = callback
else:
self.handle_message = callback # type: ignore[method-assign]
def wait_for_message(self, subscription: str, timeout: float = -1.0) -> tuple[bool, Any]:
return (False, None)
# -- introspection -----------------------------------------------------------------------
def get_connected_ports(self) -> dict[str, bool]:
return {name: True for name in self.input_ports}
def get_input_topics(self) -> dict[str, Any]:
return {}
def get_output_topics(self) -> dict[str, Any]:
return {}
def handle_message(self, input_name: str, msg: Any, topic_info: Any) -> None:
pass
Copy this file into your own tests/ directory. The version shipped with the SDK examples lives
at examples/_testing/fake_dataflow.py.
A complete test module¶
The test for the Math node tutorial exercises the happy path, the
default configuration, a missing input, latching between runs and the schema's configuration
block:
"""Tests for the tutorial MathAddNode.
Runs without a ROS installation: the shared stubs shim ``std_msgs`` and the
transport libraries before the node module is imported. The node is driven
exactly like the engine drives it: ``on_configure`` gets the static string map
parsed from ``math_node_schema.json``, ``on_execute`` reads the latched inputs
through ``get_data`` and publishes a real message object.
"""
from examples._testing.stubs import install_stubs
install_stubs()
import json # noqa: E402
import pathlib # noqa: E402
from google.protobuf.json_format import ParseDict # noqa: E402
from neuraverse.models.v1.gen.business.node_graph_pb2 import Node # noqa: E402
from std_msgs.msg import Float32 # noqa: E402
from examples._testing.fake_dataflow import FakeDataFlow # noqa: E402
from examples.tutorials.math_node.math_node import MathAddNode # noqa: E402
SCHEMA_PATH = pathlib.Path(__file__).with_name("math_node_schema.json")
def load_schema() -> Node:
return ParseDict(json.loads(SCHEMA_PATH.read_text(encoding="utf-8")), Node())
def make_node(config: dict[str, str] | None = None) -> MathAddNode:
node = MathAddNode()
node.data_flow = FakeDataFlow()
node.on_configure(config if config is not None else {}, None)
return node
def test_publishes_sum_of_inputs_and_offset() -> None:
node = make_node({"offset": "1.5"})
node.data_flow.input_ports["a"] = Float32(data=2.0)
node.data_flow.input_ports["b"] = Float32(data=3.0)
node.on_execute()
published = node.data_flow.published["sum"]
assert len(published) == 1
assert isinstance(published[0], Float32)
assert published[0].data == 6.5
def test_offset_defaults_to_zero() -> None:
node = make_node()
node.data_flow.input_ports["a"] = Float32(data=0.25)
node.data_flow.input_ports["b"] = Float32(data=0.5)
node.on_execute()
assert node.offset == 0.0
assert node.data_flow.published["sum"][0].data == 0.75
def test_missing_input_warns_and_publishes_nothing() -> None:
node = make_node()
warnings: list[str] = []
node.log_warning = warnings.append
node.data_flow.input_ports["a"] = Float32(data=1.0)
node.on_execute()
assert not node.data_flow.published.get("sum")
assert len(warnings) == 1
assert "'b'" in warnings[0]
def test_inputs_latch_between_executions() -> None:
node = make_node()
node.data_flow.input_ports["a"] = Float32(data=1.0)
node.data_flow.input_ports["b"] = Float32(data=1.0)
node.on_execute()
node.on_execute()
assert [msg.data for msg in node.data_flow.published["sum"]] == [2.0, 2.0]
def test_schema_configuration_drives_on_configure() -> None:
schema = load_schema()
node = MathAddNode()
node.data_flow = FakeDataFlow()
# The engine passes Node.configuration (a protobuf ScalarMap of strings).
node.on_configure(schema.configuration, None)
assert schema.executionContext.className == MathAddNode.__name__
assert set(schema.inputs) == {"start", "stop", "a", "b"}
assert set(schema.outputs) == {"start", "error", "sum"}
assert node.offset == 0.0
Points worth copying:
make_node()callson_configurewith a plaindictandNone. The engine passes a protobufScalarMap, which behaves like adictfor.get(), so the same code path is tested.test_schema_configuration_drives_on_configureparses the schema JSON into theNodeproto and passesschema.configurationtoon_configure. This catches a typo in a config key that the UI would otherwise expose at runtime.- Log calls are replaced per instance (
node.log_warning = warnings.append) to assert on them. - Every message the node publishes is checked with
isinstance(published[0], Float32).
Running tests without ROS 2¶
Importing neuraverse_sdk.node_base pulls in rclpy, zenoh and livekit through the SDK's
transport adapters, and your node imports ROS 2 message classes such as std_msgs.msg.Float32. On a machine without ROS 2 you have
two options:
The node image is built on ros:humble, so rclpy and every ROS 2 message package the
image installs are importable. Source the ROS 2 environment before pytest:
docker run --rm -it my-node:dev \
bash -c "source /opt/ros/humble/setup.bash && poetry run pytest -q tests/"
Register lightweight stand-ins in sys.modules before the first SDK import. The SDK examples
ship a helper that does this for rclpy, zenoh, livekit and the message classes the
examples use; call it at the very top of each test module:
from examples._testing.stubs import install_stubs
install_stubs()
from std_msgs.msg import Float32 # noqa: E402 (stub or real, whichever imports)
install_stubs() is idempotent and never replaces a package that imports for real, so the
same test module runs unchanged inside the node image. The SDK's own test suite applies the
same pattern from tests/conftest.py. Extend the message table in your copy of stubs.py
when your node uses a type the helper does not know.
The SDK repository runs the example tests exactly like this:
PYTHONPATH="$(pwd):$(pwd)/src" poetry run pytest examples/ -q -p no:cacheprovider
Schema-vs-code test¶
The schema file and the Python module drift apart easily: a class rename that is not mirrored in
executionContext.className, a port renamed in the code but not in the JSON, or a Stop output
left in from a template. None of that is caught by the tests above, and the Mock Runner cannot
catch a className mismatch either. The SDK examples carry a reusable test parametrized over
every *_schema.json that has a sibling .py module. It asserts that:
- the JSON parses into the business
Nodeproto and setsnameandexecutionContext.className; executionContext.classNamenames aNodeBasesubclass defined in the sibling module;- every input and output key is lowercase snake_case;
- no output port has
rosType: "Stop". The SDK fires every declared Stop output after each successfulon_execute, which would stop downstream nodes on every run; - every string literal passed to
self.publish(...)orself.get_data(...)in the module is a declared output or input key (found withast, so no node code runs).
The last two checks look like this:
@pytest.mark.parametrize("schema", SCHEMAS, ids=SCHEMA_IDS)
def test_no_stop_output(schema: pathlib.Path) -> None:
outputs = _load_schema(schema).get("outputs", {})
stop_outputs = [k for k, v in outputs.items() if v.get("rosType") == "Stop"]
assert not stop_outputs, (
f"{schema}: a Stop output fires after every successful on_execute and stops "
f"downstream nodes; remove {stop_outputs}"
)
@pytest.mark.parametrize("schema", SCHEMAS, ids=SCHEMA_IDS)
def test_publish_and_get_data_literals_are_declared_ports(schema: pathlib.Path) -> None:
data = _load_schema(schema)
module_path = _module_path(schema)
outputs = set(data.get("outputs", {}))
inputs = set(data.get("inputs", {}))
unknown_outputs = [p for p in _call_literals(module_path, "publish") if p not in outputs]
unknown_inputs = [p for p in _call_literals(module_path, "get_data") if p not in inputs]
assert not unknown_outputs, f"{module_path}: publish() to undeclared outputs {unknown_outputs}"
assert not unknown_inputs, f"{module_path}: get_data() from undeclared inputs {unknown_inputs}"
Drop examples/tests/test_node_schemas.py into your repository and point EXAMPLES at your
src/ directory. Because the module is imported by file path, the same way the runtime loads it,
an import error in the node module also fails this test.
Layer 2: the Mock Runner¶
The Mock Runner (mock-nodegraph) runs your node source in a browser canvas without an engine,
broker or registry. Point it at your src/ directory, drag nodes on the canvas, wire data ports
and click Init, Configure and Execute on each node.
What it exercises with the real SDK code:
__init__andon_get_configuration()on Init, so a bad@trigger_handlerdeclaration (built-in name, duplicate) fails here.- The real
NodeBase.configure()on Configure, so youron_configure(config, dynamic_config)runs with the values you entered in the UI, andon_health_check()is called once. - The real
NodeBase.execute()on Execute, soon_execute()runs andget_data()andpublish()move messages between wired nodes in memory. Logs and the last value on every port are shown in the UI.
What it cannot prove:
- Triggers are mocked out entirely. Nothing fires and nothing is received, so
Start,Errorand custom trigger ports do not propagate; you execute each node in a chain yourself. - There is no stop, pause or resume, so
on_stop_execution(),on_cleanup(),on_stop(),on_pause(),on_resume()andis_paused()never run. on_execute()runs synchronously withtrigger_context=None.- The static
configurationblock of the schema is not delivered; only typed values from the UI reachon_configure. - The Mock Runner pins its own SDK version, which can be older than the one in your node image.
An API that exists in a newer SDK can raise
AttributeErrorin the mock and still be correct in production.
Rule of thumb: green in the Mock Runner proves data flow, configuration and the code paths inside
on_execute. Cover teardown, triggers, health and visualization with Layer 1 tests or on an
engine. The full matrix is on the Mock Runner site:
Mock Runner limitations.
Layer 3: real transports without an engine¶
Custom trigger ports cannot be tested in the Mock Runner, but they can be tested over a real MQTT
broker with nothing else running. The SDK ships examples/custom_triggers/run_local_demo.py,
which builds by hand the trigger wiring the engine would compute for the two nodes of the
custom triggers tutorial, connects both to a broker and runs
the watchdog once:
docker run -d --name mosquitto -p 1883:1883 \
eclipse-mosquitto:2 mosquitto -c /mosquitto-no-auth.conf
# inside an environment with the SDK installed (node image or SDK dev container)
python examples/custom_triggers/run_local_demo.py
The script asserts that the worker's SpecialStart handler ran twice, sourced from
WatchdogNode; the printed lines show both dispatches arriving while the watchdog's
on_execute was still running. Adapt it for your own nodes
by changing the TriggerNodeEntry maps: keys are port keys (task_interrupt), values and
InputConnection.rosType are trigger type names (TaskInterrupt, SpecialStart).
Layer 4: on an engine¶
Build the image, deploy it as described in Deploying on an engine and check three things:
- Startup log. The node service logs
Node classes set to [...], thenNode <ClassName> registeredonce per class after a successful registration, and finallyServing HTTP. A warningRegistry endpoint not configured, skipping registration.means the node runs but will never appear in the palette. - Palette. Each class appears exactly once in the node-graph editor, in the category given
by the schema's
id, with the ports you declared. - HTTP port.
GET /on the configuredhttp.port(default 8080) returns a page saying the node SDK web service is reachable.
Then build a small graph with the node, run it and inspect the node's logs and the status of
downstream nodes. This is the only layer where trigger propagation, Error handling,
stop/pause and visualization run for real.
Layer 5: memory profiling¶
Nodes that hold hardware connections, threads or large buffers can leak across
configure/stop cycles. The SDK installs a neuraverse-node-profiler console script
(neuraverse_sdk.utilities.mem_profiler) that instantiates your class, calls
on_configure(config) and on_stop() in a loop and samples RSS and thread count from
/proc/self/status after each cycle. Run it inside your node image:
docker run --rm -it my-node:dev \
neuraverse-node-profiler --module my_node.my_node --node-class MyNode \
--config-json config/profile.json --cycles 30
| Option | Default | Meaning |
|---|---|---|
--module, --node-class |
required | import path of the module and the class name; may also be given as _module and _class keys in the config JSON |
--config-json |
none | JSON file with the dict passed to on_configure |
--cycles |
30 | configure/stop cycles to run |
--warmup |
5 | cycle used as the baseline; growth is measured from there to the last cycle |
--settle |
0.3 | seconds to sleep after on_configure before on_stop |
--max-rss-growth-kb |
20000 | fail when RSS grows more than this (about 20 MiB) |
--max-thread-growth |
3 | fail when the thread count grows more than this |
--csv |
profile_cycles.csv |
per-cycle trend written for plotting |
Exit code 0 means flat, 1 means a possible leak, 2 means too few cycles to evaluate. The script
re-executes itself under a sourced ROS 2 shell when it finds /opt/ros/humble/setup.bash and no
ROS environment is active; override the paths with NEURAVERSE_PROFILER_ROS_SETUP,
NEURAVERSE_PROFILER_SRC (default /neuraverse-node/src) and NEURAVERSE_PROFILER_VENV_GLOB.
Note
The profiler calls on_configure with the config dict only, so keep the dynamic_config=None
default on your override, and it calls on_stop() directly without the rest of the stop
chain, so resources released in on_cleanup() are not counted. To profile a release path,
call on_cleanup() from a thin on_stop() override in the profiled build only.