184а. Renode and Ceedling/CMock: firmware in a board emulator and unit tests with mocked peripherals in the pipeline
Section 184 checked pure logic with its own small harness, section 129а replaced registers and HAL functions at link time, section 110 built the firmware in a container, and 110б ran tests on a real board at the rig. Here are two ready-made tools that fill the gap between "logic on the computer" and "board on the desk": Ceedling with CMock (unit tests where fakes of dependencies are built from headers automatically) and Renode (an emulator that runs the same ELF that goes into the microcontroller and lets a test script read its UART).
The goal is one: a check without a board on every change. The rig board is a single one, it is busy, it has to be reset and flashed; an emulator and a computer are available on every pipeline runner.
Sources and what was verified. A temperature sensor module with read retries and its tests are written in the Unity/CMock style, built with gcc and run three times: without a bug and with two injected bugs. The real Unity, CMock, Ceedling and Renode were not run here: they are not in the images on this machine, and downloading was not allowed for the check. Assertions with the same names and a fake whose function names match what CMock would generate are hand-written; the Renode and Robot Framework scripts are checked for syntax only.
What it is called in the documentation
Original Meaning Ceedling a Ruby test build tool: finds tests, builds fakes, compiles and runs CMock a generator of fake C functions from a header Unity (test framework) an assertion and result printing library for C expectation, _ExpectAndReturnan expected call: with which arguments and what to return _ReturnThruPtrreturn data through a pointer argument _StubWithCallbackput your own function in place of the fake Renode a board and system-on-chip emulator by Antmicro platform description ( .repl)a board description: core, memory, peripherals, addresses Renode script ( .resc)a script: create a machine, load the ELF, open an analyzer Robot Framework keyword a test script keyword, for example Wait For Line On Uart
184а.1 Why, and where each level sits in the pipeline
Section 184 splits checks into unit, integration and system ones. For a long time there was a hole between the first two: a unit test does not see startup, interrupt vectors, the linker script or clock setup, while the rig board is expensive and slow. A board emulator closes half of that hole: it executes real Cortex-M instructions from the real ELF and models peripherals at the register level, but not at the electrical level.
| Unit tests on the computer (Ceedling + CMock) | Renode | QEMU (netduinoplus2 etc.) |
Board at the rig | |
|---|---|---|---|---|
| speed | fractions of a second per suite | seconds per scenario | seconds | tens of seconds: flashing, reset, waiting |
| what runs | logic built by gcc for the computer | the same ELF that goes into the board | the same ELF | the same ELF on the real chip |
| fidelity to hardware | none: peripherals are fakes | registers and interrupts of the main peripherals | the core is exact, few peripherals | full |
| catches | logic, sign, boundary, call order and retry bugs | startup, vectors, linking, init order, UART exchange, interrupt logic | crashes at startup, core and memory errors | timing, analog, noise, power, silicon bugs |
| misses | everything that depends on registers and time | exact timing, analog, DMA subtleties and silicon bugs | almost all STM32 peripherals | rare combinations of conditions unless reproduced |
| where it runs | on any runner, on every change | on any runner, on every change | on any runner | on its own runner with the rig, before release or on a schedule |
The order in the pipeline follows from the cost: cheap and fast first, the expensive only if the cheap passed.
184а.2 A Ceedling project: what lives where
Ceedling is a Ruby build tool that ties three parts together: Unity
(assertions), CMock (fakes) and build rules. It finds test files itself,
understands from #include "mock_….h" lines which fakes to build, and
for each test_*.c builds a separate program: the test, the module under
test, fakes of its dependencies, Unity.
thermo/
├── project.yml настройки: пути, ключи компилятора, плагины
├── src/
│ ├── temp.c модуль под тестом
│ ├── temp.h
│ └── hal_i2c.h тонкая прослойка над шиной — из неё строится подделка
├── test/
│ ├── test_temp.c тесты модуля: функции test_*
│ └── support/ общие помощники тестов
└── build/ всё сгенерированное: подделки, объектники, отчёты
A minimal project.yml (keys from memory of the 0.31 and 1.0 branches; in
version 1.0 some keys were renamed, so check against the documentation of
your version):
:project:
:build_root: build
:test_file_prefix: test_
:paths:
:test:
- test/**
:source:
- src/**
:include:
- src/**
:defines:
:test:
- TEST
:cmock:
:mock_prefix: mock_
:plugins:
- :expect_any_args
- :ignore
- :ignore_arg
- :return_thru_ptr
- :callback
:plugins:
:enabled:
- report_tests_pretty_stdout
- junit_tests_report
- gcov
Running is ceedling test:all, a single file is ceedling test:temp,
coverage is ceedling gcov:all (task name from memory). The
junit_tests_report plugin puts a JUnit-format report into
build/artifacts/test/; GitLab reads it and shows failed tests right in
the merge request.
The build runs on the computer, with ordinary gcc: a test is a program for the computer, not for the board. So there must be no vendor header and no register access in tests; that is the next subsection.
184а.3 A thin layer: what the fake is built from
CMock builds a fake from a header: for each declared function, its own
implementation that checks the call against an expectation. You can feed
it stm32f4xx_hal_i2c.h, but it goes badly: the header pulls in
stm32f4xx.h, CMSIS, hundreds of macros and register structures, and
there will be more fakes than tests. A layer of your own with a few
functions is easier:
/* Тонкая прослойка над I2C: тесты видят только её, а не заголовки производителя. */
#ifndef HAL_I2C_H
#define HAL_I2C_H
#include <stdint.h>
typedef enum { HAL_I2C_OK = 0, HAL_I2C_ERR = 1 } hal_i2c_status_t;
hal_i2c_status_t hal_i2c_read(uint8_t addr, uint8_t reg, uint8_t *buf, uint16_t len);
#endif
In the firmware its implementation is three lines over HAL_I2C_Mem_Read
or over registers; in tests its place is taken by mock_hal_i2c.c. The
module that uses the bus sees only hal_i2c.h and builds the same way for
the board and for the computer. It is the same seam as in 129а, only drawn
along your own header rather than along HAL functions at link time.
The module under test reads an LM75-type sensor: two bytes, high byte first, temperature in the upper 11 bits with sign, step 0.125 °C; on a bus error, up to three tries:
#include "temp.h"
#include "hal_i2c.h"
int temp_read_mdeg(int32_t *out)
{
uint8_t b[2];
for (int i = 0; i < TEMP_TRIES; i++) {
if (hal_i2c_read(TEMP_ADDR, TEMP_REG, b, 2) != HAL_I2C_OK)
continue;
int16_t raw = (int16_t)(b[0] << 8 | b[1]);
*out = (int32_t)(raw >> 5) * 125; /* 11 бит, шаг 0,125 °C */
return 0;
}
return -1;
}
184а.4 Unity and CMock: expectations, return through pointer, ignore
What CMock generates for hal_i2c_read (the names are those given by
the plugins enabled above):
| Fake function | What it does |
|---|---|
hal_i2c_read_ExpectAndReturn(addr, reg, buf, len, ret) |
expects a call with these arguments, returns ret |
hal_i2c_read_IgnoreArg_buf() |
do not check the buf pointer of the last expectation |
hal_i2c_read_ReturnArrayThruPtr_buf(data, n) |
on the call, copy n bytes into buf |
hal_i2c_read_IgnoreAndReturn(ret) |
accept all calls without checks and return ret |
hal_i2c_read_StubWithCallback(fn) |
call your own fn instead of the expectation queue |
hal_i2c_read_ExpectAnyArgsAndReturn(ret) |
expect a call, do not check arguments |
Expectations form a queue. Each call of the function is checked against the next expectation in order; an extra call fails at once, a missing one fails at the end of the test, when Ceedling calls the fake verification. Hence the main property: the test checks not only the result but also the conversation with the hardware: how many times and with which arguments the module went to the bus.
The module tests (in full at the end of the section):
void test_minus_25(void)
{
int32_t t = 0;
expect_read(0xE7, 0x00, HAL_I2C_OK);
TEST_ASSERT_EQUAL_INT(0, temp_read_mdeg(&t));
TEST_ASSERT_EQUAL_INT(-25000, t);
}
void test_gives_up_after_3(void)
{
int32_t t = 7;
for (int i = 0; i < TEMP_TRIES; i++)
expect_read(0, 0, HAL_I2C_ERR);
TEST_ASSERT_EQUAL_INT(-1, temp_read_mdeg(&t));
TEST_ASSERT_EQUAL_INT(7, t);
}
The expect_read helper sets one expectation: address 0x48, register 0,
length 2, pointer not checked, on success return two bytes through the
pointer. The expectations in the test are independent numbers from the
sensor description, not a recomputation by the same code (a pitfall from
184.8): 0x19 0x00 is +25 °C, 0x19 0x80 is +25.5 °C, 0xE7 0x00 is −25 °C,
0x00 0x20 is one step, 0.125 °C.
_StubWithCallback is needed when the expectation queue is awkward: for
example, a fake clock that adds a millisecond on every call, or a bus that
answers based on the request contents. _IgnoreAndReturn is for when the
dependency is beside the point; the next subsection shows the price of
that ease.
184а.5 The run: a clean module and two injected bugs
Six tests are built with gcc -Wall -Wextra -Werror together with the
fake and the assertions. The module is built three times: as is, with a
lost sign (uint16_t instead of int16_t before the shift) and with an
extra try (<= instead of < in the loop).
The clean module:
test_temp.c:69:test_plus_25:PASS
test_temp.c:70:test_fraction:PASS
test_temp.c:71:test_minus_25:PASS
test_temp.c:72:test_retry_then_ok:PASS
test_temp.c:73:test_gives_up_after_3:PASS
test_temp.c:74:test_bus_dead:PASS
-----------------------
6 Tests 0 Failures 0 Ignored
OK
Lost sign: positive temperatures pass, the negative one fails:
test_temp.c:38:test_minus_25:FAIL: Expected -25000 Was 231000
-----------------------
6 Tests 1 Failures 0 Ignored
FAIL
0xE700 unsigned, shifted by 5, is 1848; times 125, that is 231000: the sensor "showed" +231 °C in frost. Tests only at room temperature would never see it.
Extra try: the function result is the same (−1), its assertion would pass. The fake catches it: there is no fourth call in the queue.
mock_hal_i2c.c:49:test_gives_up_after_3:FAIL: Function hal_i2c_read called more times than expected.
-----------------------
6 Tests 1 Failures 0 Ignored
FAIL
And the test_bus_dead test, where the same bus is faked with
_IgnoreAndReturn, passed in all three builds: ignore accepts any number
of calls. An extra try on a dead bus means extra milliseconds in every
poll, and such a test will not notice it.
In both failures the program returned a non-zero code, so the pipeline stops, as in 110.7.
184а.6 Renode: a board from a text description
Renode is an open-source emulator by Antmicro. A machine in it is
assembled from a platform description (.repl): core, memory,
peripherals and their addresses. The Renode catalogue has ready
descriptions for a number of STM32 boards, among them the Discovery on
STM32F407 and several Nucleo boards; exact file names are given from
memory and change between versions, so look in the platforms/boards
directory of your installation.
A .resc script creates the machine, loads the ELF and opens a UART
window:
# thermo.resc — машина для прогонов прошивки
using sysbus
mach create "thermo"
machine LoadPlatformDescription @platforms/boards/stm32f4_discovery-kit.repl
showAnalyzer sysbus.usart2
$bin ?= @build/thermo.elf
macro reset
"""
sysbus LoadELF $bin
"""
runMacro $reset
start
What matters here:
- ELF, not bin: Renode takes section addresses and the entry point from the ELF and knows the symbols, which helps with GDB and call logs;
$bin ?=is a default value that the pipeline overrides with its own path;- the
resetmacro is what Renode runs on a machine reset, including on a command from the test; showAnalyzeropens a serial port window; in the pipeline there is no window, and the Robot Framework terminal tester replaces it.
Your own device on the bus is added with a second .repl file that
extends the ready one: for example, a sensor model on I2C at address 0x48.
Which sensor models Renode has and what they are called, check against
the model catalogue of your version; when there is no ready one, the model
is written in C# or as a Python peripheral right in the description.
GDB to Renode. The machine StartGdbServer 3333 command in the Renode
monitor or in a script opens a port to which
arm-none-eabi-gdb build/thermo.elf connects with target remote :3333.
Breakpoints, stepping and memory views work as with a real debugger, but
time in the machine stops together with the core: timing bugs under the
debugger neither hide here nor show up differently than without it.
184а.7 A Robot Framework test: wait for a line from UART
Renode ships with a set of keywords for Robot Framework. A test reads as a list of steps:
# tests/thermo.robot — прогон прошивки в Renode
*** Settings ***
Suite Setup Setup
Suite Teardown Teardown
Test Teardown Test Teardown
Resource ${RENODEKEYWORDS}
*** Variables ***
${UART} sysbus.usart2
*** Keywords ***
Create Machine
Execute Command $bin=@${CURDIR}/../build/thermo.elf
Execute Command include @${CURDIR}/../thermo.resc
Create Terminal Tester ${UART} timeout=5
*** Test Cases ***
Should Boot And Report
Create Machine
Start Emulation
Wait For Line On Uart thermo boot ok
Wait For Line On Uart selftest: pass
Should Survive Reset
Create Machine
Start Emulation
Wait For Line On Uart thermo boot ok
Execute Command machine Reset
Wait For Line On Uart thermo boot ok
Running is renode-test tests/thermo.robot (in old versions, the
renode-run-test script; name from memory). The result is
robot_output.xml and a report that turns into JUnit for the pipeline.
What this catches that unit tests do not: the firmware started at all
(vectors, stack, linker script, .data copy), peripherals were enabled in
the right order, the line reached the UART, after a reset the firmware
comes up again. A unit test of the temp.c module sees none of this: it
has neither startup nor registers.
Time in the emulator is virtual. timeout=5 is seconds of emulated
time, not wall-clock time: on a slow runner the test takes longer but does
not fail because the machine is loaded. That is the main difference from
the rig, where the same line with a timeout depends on the real speed of
the port and the board.
184а.8 What Renode models well and what it models poorly
| Models well | Models poorly or not at all |
|---|---|
| Cortex-M instruction execution, exceptions, NVIC | exact time: cycles per instruction, flash wait states, the core pipeline |
| the memory map and faults on access to a non-existent address | analog: the ADC returns what the script set, not a voltage |
| UART as a byte stream, GPIO as levels, timers as counting | DMA subtleties: races with the CPU, half-transfer interrupts at a bad moment, stream priorities |
| reset, restart, several machines in one network | silicon bugs from the errata, electrical effects, power |
| virtual time that does not depend on load | peripherals without a model: their registers stay silent or give a warning |
Hence the rule: interrupt logic and init order go to the emulator, timing and analog to the rig. If a test is green in Renode and red on the board, the first thing to look at is time (delays, timeouts, waiting for flags in a loop) and peripherals without a model.
184а.9 The pipeline: three stages and reports
Stages go from cheap to expensive; each next one runs only if the previous one passed. Images are your own, with pinned versions, as in 110.3.
stages: [unit, build, renode, bench]
unit:
stage: unit
image: registry.local/fw-ceedling:1
script:
- ceedling test:all
artifacts:
when: always
reports:
junit: build/artifacts/test/report_junit.xml
build:
stage: build
image: registry.local/fw-arm:1
script:
- make -C fw BOARD=f407 all
artifacts:
paths: [build/thermo.elf, build/thermo.bin, build/thermo.map]
renode:
stage: renode
image: registry.local/fw-renode:1
needs: [build]
script:
- renode-test --results-dir build/renode tests/thermo.robot
artifacts:
when: always
paths: [build/renode/]
bench:
stage: bench
tags: [bench]
needs: [build, renode]
rules:
- if: $CI_COMMIT_TAG
script:
- pytest bench --image build/thermo.elf --junitxml=build/bench.xml
What matters here:
when: alwayson reports: a report is needed most exactly when the tests failed;- Renode gets the same
thermo.elfthat thebuildstage produced; it is not rebuilt, otherwise you check something other than what goes into the board; - the rig only on a release tag (or on a schedule): it is single and slow; it is covered in detail in section 110б;
- image names and the JUnit report path are your own; the Ceedling report path is from memory and depends on the version and plugin settings.
184а.10 Pitfalls
A fake from the vendor header. CMock will dutifully build fakes for hundreds of functions and trip over CMSIS macros and inline functions. A layer of your own with a few functions, and the fake is clear.
Ignore instead of an expectation. _IgnoreAndReturn is convenient but
accepts any number of calls: the test with ignore did not notice the extra
try in 184а.5. Where the number of accesses matters, only _Expect….
Expectations computed by the same code. The expected −25000 is written as a number from the sensor description. If it were computed by the same formula as in the module, the lost sign would pass.
Tests are built for the computer, and type sizes differ. int and
long on the computer are 32 and 64 bits, on Cortex-M 32 and 32. The
module is written with int32_t and uint16_t, otherwise the test on the
computer and the firmware compute differently.
A green Renode is taken as a timing check. The emulator does not know how many cycles an instruction takes or how long the flash waits. Delays, timeouts and exchange speed are checked on the board.
Board and keyword names from memory. Board descriptions, keywords and
run commands changed between Renode versions; the path in .resc and the
tester name are checked against your installation, and the image is
pinned by version.
A UART line without a newline. Wait For Line On Uart waits for a
whole line; firmware that prints without \n or with a lone \r will
wait out the timeout.
A run without a report. Without when: always, the JUnit report is
lost exactly in the failed build, and you have to dig through the log.
184а.11 Summary
- A pipeline without a board is two stages: unit tests on the computer (Ceedling + CMock) and a run of the same ELF in Renode; the rig with a board is for releases or a schedule.
- CMock builds fakes from your own thin layer over the peripherals; the test checks both the result and the conversation with the hardware: the number and arguments of calls.
- In the run there are six tests: the lost sign gave "Expected -25000 Was
231000", the extra try was caught by the fake, "called more times than
expected"; the test with
_IgnoreAndReturnnever caught it. - Renode executes real instructions and models registers, UART and interrupts; its time is virtual, there is no analog and no DMA subtleties.
- JUnit reports at every stage and with
when: always.
Full sources
test_temp.c: tests of the sensor module.
#include "unity_lite.h"
#include "temp.h"
#include "mock_hal_i2c.h"
void setUp(void) { mock_hal_i2c_Init(); }
void tearDown(void) { mock_hal_i2c_Verify(); }
static void expect_read(uint8_t msb, uint8_t lsb, hal_i2c_status_t ret)
{
uint8_t d[2] = { msb, lsb };
hal_i2c_read_ExpectAndReturn(TEMP_ADDR, TEMP_REG, NULL, 2, ret);
hal_i2c_read_IgnoreArg_buf();
if (ret == HAL_I2C_OK)
hal_i2c_read_ReturnArrayThruPtr_buf(d, 2);
}
void test_plus_25(void)
{
int32_t t = 0;
expect_read(0x19, 0x00, HAL_I2C_OK);
TEST_ASSERT_EQUAL_INT(0, temp_read_mdeg(&t));
TEST_ASSERT_EQUAL_INT(25000, t);
}
void test_fraction(void)
{
int32_t t = 0;
expect_read(0x19, 0x80, HAL_I2C_OK);
TEST_ASSERT_EQUAL_INT(0, temp_read_mdeg(&t));
TEST_ASSERT_EQUAL_INT(25500, t);
}
void test_minus_25(void)
{
int32_t t = 0;
expect_read(0xE7, 0x00, HAL_I2C_OK);
TEST_ASSERT_EQUAL_INT(0, temp_read_mdeg(&t));
TEST_ASSERT_EQUAL_INT(-25000, t);
}
void test_retry_then_ok(void)
{
int32_t t = 0;
expect_read(0, 0, HAL_I2C_ERR);
expect_read(0x00, 0x20, HAL_I2C_OK);
TEST_ASSERT_EQUAL_INT(0, temp_read_mdeg(&t));
TEST_ASSERT_EQUAL_INT(125, t);
}
void test_gives_up_after_3(void)
{
int32_t t = 7;
for (int i = 0; i < TEMP_TRIES; i++)
expect_read(0, 0, HAL_I2C_ERR);
TEST_ASSERT_EQUAL_INT(-1, temp_read_mdeg(&t));
TEST_ASSERT_EQUAL_INT(7, t);
}
void test_bus_dead(void)
{
int32_t t = 7;
hal_i2c_read_IgnoreAndReturn(HAL_I2C_ERR);
TEST_ASSERT_EQUAL_INT(-1, temp_read_mdeg(&t));
}
int main(void)
{
UNITY_BEGIN();
RUN_TEST(test_plus_25);
RUN_TEST(test_fraction);
RUN_TEST(test_minus_25);
RUN_TEST(test_retry_then_ok);
RUN_TEST(test_gives_up_after_3);
RUN_TEST(test_bus_dead);
return UNITY_END();
}
mock_hal_i2c.c: a fake written by hand after the pattern of what CMock generates: an expectation queue, an extra call and a missing call fail.
/* Очередь ожиданий, как в коде, который генерирует CMock: каждый вызов сверяется
* со следующим ожиданием, лишний вызов и недостача вызовов — провал теста. */
#include <string.h>
#include <stdio.h>
#include "unity_lite.h"
#include "mock_hal_i2c.h"
#define MAXQ 8
static struct {
uint8_t addr, reg; uint16_t len; hal_i2c_status_t ret;
uint8_t out[8]; uint16_t out_n;
} q[MAXQ];
static int nq, used, ignore_all;
static hal_i2c_status_t ignore_ret;
void mock_hal_i2c_Init(void) { nq = used = ignore_all = 0; memset(q, 0, sizeof q); }
void mock_hal_i2c_Verify(void)
{
if (!ignore_all && used < nq) {
char m[96];
snprintf(m, sizeof m, "Function hal_i2c_read called fewer times than expected (%d of %d).", used, nq);
TEST_FAIL_MESSAGE(m);
}
}
void hal_i2c_read_ExpectAndReturn(uint8_t addr, uint8_t reg, uint8_t *buf, uint16_t len, hal_i2c_status_t ret)
{
(void)buf; /* указатель сверять незачем: IgnoreArg_buf ниже */
q[nq].addr = addr; q[nq].reg = reg; q[nq].len = len; q[nq].ret = ret;
nq++;
}
void hal_i2c_read_IgnoreArg_buf(void) { }
void hal_i2c_read_ReturnArrayThruPtr_buf(const uint8_t *data, uint16_t n)
{
memcpy(q[nq - 1].out, data, n);
q[nq - 1].out_n = n;
}
void hal_i2c_read_IgnoreAndReturn(hal_i2c_status_t ret) { ignore_all = 1; ignore_ret = ret; }
hal_i2c_status_t hal_i2c_read(uint8_t addr, uint8_t reg, uint8_t *buf, uint16_t len)
{
if (ignore_all)
return ignore_ret;
if (used >= nq)
TEST_FAIL_MESSAGE("Function hal_i2c_read called more times than expected.");
TEST_ASSERT_EQUAL_INT(q[used].addr, addr);
TEST_ASSERT_EQUAL_INT(q[used].reg, reg);
TEST_ASSERT_EQUAL_INT(q[used].len, len);
if (q[used].out_n)
memcpy(buf, q[used].out, q[used].out_n);
return q[used++].ret;
}
Next: section 185 "Dart for the firmware engineer: bytes, numbers, frame parsing".