Skip to content

Firmware Unit Tests

A unit test runs one small part of the code with chosen inputs and checks the result. The unit tests of the Teensy firmware run on your PC, without a Teensy. The tested code talks to stand-ins for the hardware and for the ROS connection, which the tests call fakes. PlatformIO, the tool that builds the firmware, also builds the tests into programs for the PC and runs them (PlatformIO's unit testing).

This page runs one test first. Then it explains which of the two test frameworks a new test uses, and how to write a test suite. CI runs every suite on every pull request (Firmware unit tests on the Testing and CI page).

Run the tests

One test

The goal of this first run is to check that a register write sends the register byte followed by the value byte. The test WireBusTest.WriteRegisterSendsRegisterAndValue checks exactly that, for the firmware's I2C bus code. Run it in the firmware container, which needs only Docker, from the root folder of your diffbot clone:

1
2
3
4
.docker/firmware/run.sh pio test \
  -e native_googletest \
  --filter googletest/test_wire_bus \
  --program-arg=--gtest_filter=WireBusTest.WriteRegisterSendsRegisterAndValue

The test passed when PlatformIO prints its name with [PASSED], and the last line counts one test case that succeeded:

1
2
3
WireBusTest.WriteRegisterSendsRegisterAndValue  [PASSED]
…
================== 1 test cases: 1 succeeded in 00:00:00.496 ==================

The first run of an environment downloads what it needs from PlatformIO's registry, so it needs the internet. For native_googletest that is GoogleTest, for native Unity and rosserial. The libraries land in diffbot_firmware/.pio/libdeps/<environment>. Later runs of the same environment work without the internet. To be able to run every suite offline, run the command for every suite below once while you are online.

The command has four parts:

  • .docker/firmware/run.sh: our script that runs a command in the firmware container, in the folder diffbot_firmware.
  • pio test -e native_googletest: PlatformIO's test command, with the environment that builds the GoogleTest suites. An environment is a section of platformio.ini that says what to build and how.
  • --filter googletest/test_wire_bus: the PlatformIO test suite, a folder below diffbot_firmware/test whose name starts with test_. PlatformIO builds each of these folders into one test program. --filter selects folders, not single tests.
  • --program-arg=--gtest_filter=…: an option that PlatformIO passes on to the test program (pio test's options). GoogleTest's option --gtest_filter runs only the tests whose full name matches (Running a Subset of the Tests).

A test's full name has two parts. GoogleTest groups the tests of a program into GoogleTest test suites, and the name before the dot is that group, here WireBusTest. The name after the dot is the test. The program of googletest/test_wire_bus has twelve tests in two GoogleTest test suites, WireBusTest and ShortReads/WireBusShortReadTest. PlatformIO counts each test as a test case.

All suites, one environment or one suite

Each of these commands runs more than one test. Run them from the same folder.

Run every suite, as CI does:

1
2
.docker/firmware/run.sh pio test \
  -e native -e native_googletest

Run only the Unity suites:

1
2
.docker/firmware/run.sh pio test \
  -e native

Run only the GoogleTest suites:

1
2
.docker/firmware/run.sh pio test \
  -e native_googletest

Run one Unity suite, here the PID controller's:

1
2
.docker/firmware/run.sh pio test \
  -e native --filter test_pid

Run one GoogleTest suite, here the I2C bus code's:

1
2
3
.docker/firmware/run.sh pio test \
  -e native_googletest \
  --filter googletest/test_wire_bus

PlatformIO prints each test's name with [PASSED] or [FAILED]. At the end, a summary lists each PlatformIO test suite with its status, and the last line counts the test cases: 101 for every suite.

The output of every suite: the GoogleTest suite's tests and the summary
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Processing googletest/test_wire_bus in native_googletest environment
--------------------------------------------------------------------------------
Building...
Testing...
WireBusTest.WriteRegisterSendsRegisterAndValue  [PASSED]
WireBusTest.WriteRegisterFailsWhenTheAddressIsNotAcknowledged   [PASSED]
WireBusTest.WriteRegisterFailsWhenTheAddressIsNotAcknowledgedAfterASuccessfulWrite  [PASSED]
WireBusTest.WriteRegisterPassesOnTheAddressRegisterAndValue [PASSED]
WireBusTest.ReadRegistersUsesARepeatedStart [PASSED]
WireBusTest.ReadRegistersPassesOnTheAddressAndRegister  [PASSED]
WireBusTest.ReadRegistersReturnsAllBytesOfASample   [PASSED]
WireBusTest.ReadRegistersFailsWithoutAReadRequestWhenTheRegisterWriteFails  [PASSED]
ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/ReportedShortAllBytesThere  [PASSED]
ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/BothShort   [PASSED]
ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/ReportedInFullOneByteMissing    [PASSED]
ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/ReportedOneShortAllBytesThere   [PASSED]
---- native_googletest:googletest/test_wire_bus [PASSED] Took 1.98 seconds ----

=================================== SUMMARY ===================================
Environment        Test                               Status    Duration
-----------------  ---------------------------------  --------  ------------
native             test_wheel_control                 PASSED    00:00:00.476
native             test_synced_node_handle            PASSED    00:00:00.482
native             test_ros_wheel_command_subscriber  PASSED    00:00:00.511
native             test_pid                           PASSED    00:00:00.448
native             test_imu_publisher                 PASSED    00:00:00.520
native             test_command_timeout               PASSED    00:00:00.450
native             test_bno055                        PASSED    00:00:00.478
native_googletest  googletest/test_wire_bus           PASSED    00:00:01.985
================ 101 test cases: 101 succeeded in 00:00:05.349 ================

With PlatformIO installed on your PC instead, in the virtual environment that Firmware Container sets up, call that environment's pio in the folder diffbot_firmware: ~/.venvs/platformio/bin/pio test -e native -e native_googletest. That route needs a C++17 compiler on the PC. It wasn't tested with the GoogleTest environment.

What a failed test looks like

To see what a failure looks like, change the tested code on purpose. readRegisters() in wire_bus.h compares two counts with the requested length: the count that requestFrom() reports, and the bytes that arrived, wire_.available().

readRegisters(), lines 31–49 of wire_bus.h

readRegisters() is lines 31–49 of wire_bus.h. Line 40 compares both counts with length, and the loop after it reads the bytes that arrived when a count is short:

wire_bus.h: readRegisters()
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
bool readRegisters(uint8_t address, uint8_t reg, uint8_t* data, size_t length) override
{
    wire_.beginTransmission(address);
    wire_.write(reg);
    // A repeated start: the register pointer stays set for the read
    if (wire_.endTransmission(false) != 0)
        return false;
    // Check both the count that requestFrom reports and the bytes really received: on a
    // failed bus acquisition, the Teensy 4's Wire can report a count without data
    if (wire_.requestFrom(address, (uint8_t)length) != length || wire_.available() != (int)length)
    {
        while (wire_.available())
            wire_.read();
        return false;
    }
    for (size_t i = 0; i < length; ++i)
        data[i] = wire_.read();
    return true;
}

This edit replaces both comparisons with one comparison of the two counts with each other:

1
2
3
-if (wire_.requestFrom(address, (uint8_t)length) != length || wire_.available() != (int)length)
+const int reported = wire_.requestFrom(address, (uint8_t)length);
+if (reported != wire_.available())

With that edit, run the wire bus suite from the root folder of your diffbot clone:

1
2
3
.docker/firmware/run.sh pio test \
  -e native_googletest \
  --filter googletest/test_wire_bus

The suite fails in one case, BothShort:

BothShort failed

readRegisters() returned true. The test expects false.

The read requested 18 bytes. requestFrom() reported 4, and 4 bytes arrived. The changed check finds 4 equal to 4.

PlatformIO marks the case with [FAILED] and names the line of the failed check, test_wire_bus.cpp:254. The other eleven tests pass. The summary counts 13 test cases: the twelve tests, and one more with the status ERRORED for the program's exit status.

PlatformIO's output of the failed run
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
WireBusTest.WriteRegisterSendsRegisterAndValue  [PASSED]
WireBusTest.WriteRegisterFailsWhenTheAddressIsNotAcknowledged   [PASSED]
WireBusTest.WriteRegisterFailsWhenTheAddressIsNotAcknowledgedAfterASuccessfulWrite  [PASSED]
WireBusTest.WriteRegisterPassesOnTheAddressRegisterAndValue [PASSED]
WireBusTest.ReadRegistersUsesARepeatedStart [PASSED]
WireBusTest.ReadRegistersPassesOnTheAddressAndRegister  [PASSED]
WireBusTest.ReadRegistersReturnsAllBytesOfASample   [PASSED]
WireBusTest.ReadRegistersFailsWithoutAReadRequestWhenTheRegisterWriteFails  [PASSED]
ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/ReportedShortAllBytesThere  [PASSED]
test/googletest/test_wire_bus/test_wire_bus.cpp:254: ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/BothShort: Failure [FAILED]
ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/ReportedInFullOneByteMissing    [PASSED]
ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/ReportedOneShortAllBytesThere   [PASSED]
Program received signal SIGHUP (Hangup)
---- native_googletest:googletest/test_wire_bus [ERRORED] Took 2.02 seconds ----

=================================== SUMMARY ===================================
Environment        Test                      Status    Duration
-----------------  ------------------------  --------  ------------
native_googletest  googletest/test_wire_bus  ERRORED   00:00:02.015

============ 13 test cases: 1 failed, 11 succeeded in 00:00:02.015 ============

Add -v at the end of the same command, and PlatformIO also prints GoogleTest's own output, which says why the check failed:

GoogleTest's output for the case BothShort, with -v
1
2
3
4
5
6
7
[ RUN      ] ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/BothShort
test/googletest/test_wire_bus/test_wire_bus.cpp:254: Failure
Value of: bus_.readRegisters(DEVICE_ADDRESS, READ_REGISTER, data.data(), data.size())
  Actual: true
Expected: false

[  FAILED  ] ShortReads/WireBusShortReadTest.ReadRegistersFailsAndDrainsTheBytes/BothShort, where GetParam() = requestFrom() reports 4 bytes, 4 bytes arrive (0 ms)

GoogleTest's output has two parts to read:

  • The check that failed: its file and line, the expression, its value and the expected value.
  • The test's name: the name ends with the case, BothShort, and the case's values follow where GetParam() =. The other three cases ran too, and passed.

After the tests of a suite with a failure, PlatformIO 6.2.0 prints Program received signal SIGHUP (Hangup) and gives the suite the status ERRORED. In this run, no signal was sent. The test program ends with the exit status 1 when a test fails, and PlatformIO reads a nonzero status as a signal's number. Signal 1 is SIGHUP. A program that really received the signal SIGHUP gets the same message. So the message doesn't tell you what went wrong: look for a failed check above it. A Unity suite with one failed test shows the same line.

Why exit status 1 reads as SIGHUP: raise_for_status() in PlatformIO 6.2.0

PlatformIO calls raise_for_status() with the test program's exit status when that status isn't 0. The function turns abs(return_code) into a signal, so the exit status 1 and a program killed by signal 1, which Python reports as -1, both become SIGHUP. The function is lines 116–128 of native.py:

native.py: raise_for_status()
116
117
118
119
120
121
122
123
124
125
126
127
128
@staticmethod
def raise_for_status(return_code):
    try:
        sig = signal.Signals(abs(return_code))
        try:
            signal_description = signal.strsignal(sig)
        except AttributeError:
            signal_description = ""
        raise UnitTestError(
            f"Program received signal {sig.name} ({signal_description})"
        )
    except ValueError as exc:
        raise UnitTestError("Program errored with %d code" % return_code) from exc

Undo the edit before you go on.

Which framework for a new test

The firmware's suites are written with two test frameworks, Unity and GoogleTest. A test framework is the library that provides the checks and reports which tests passed. Which framework a test uses depends on the code that it tests:

  • A new test of portable code: GoogleTest. The suite's folder is test/googletest/test_<name>/, and the environment native_googletest runs it. Portable code is code that builds on the PC. That is the firmware's core, the logic that includes no Arduino, rosserial or other vendor library header (Ports and adapters in the firmware's README). An adapter connects the core to a library or to the hardware, and most adapters need the Arduino core. An adapter that takes its library as a template argument, as WireBusT does below, is portable code too.
  • A test of the rosserial code: Unity. Its three suites use rosserial's node handle with a fake serial port, and only the environment native has the rosserial library. Their folders are test/test_<name>/, and native runs them. The suites of the BNO055 driver, the command timeout, the PID controller and the wheel control are Unity suites too. A Unity suite of the core moves to GoogleTest when its code changes.
  • A test that has to run on the Teensy itself: Unity. PlatformIO runs Unity on microcontrollers, and GoogleTest only on the PC and ESP boards (GoogleTest in PlatformIO). The firmware has no such suite yet. Its checks on the Teensy are sketches that you run by hand, such as test/encoders, and the commands on this page leave them out.

GoogleTest is a C++ framework. Tests that share a setup put it into a fixture, and a test that has to run with several values is written once and runs once per value. A failure names the value. GoogleTest also finds the tests by itself, while a Unity suite lists each test by hand. Unity is a small framework written in C for microcontrollers (Unity in PlatformIO). Its checks are C macros, and the firmware's Unity suites are C++ files too. ROS uses GoogleTest for its C++ tests, in ROS 1 (gtest on the ROS wiki) and in ROS 2 (Writing Basic Tests with C++ with GTest).

test/googletest holds one suite, test_wire_bus. It tests WireBusT (wire_bus.h), the adapter that carries out the BNO055 driver's I2C transfers with Arduino's Wire library (How the firmware reads it on the IMU page). WireBusT takes the Wire library's class as a template argument. On the Teensy that is Arduino's TwoWire. The suite passes its fake, FakeWire, so the adapter builds and runs on the PC too.

How PlatformIO keeps the suites apart

One environment builds its suites with one framework. So the firmware has an environment for each framework, and each suite's folder decides which environment runs it:

graph TB subgraph ENVIRONMENTS [platformio.ini: environments] NATIVE[native:<br/>Unity] GOOGLETEST[native_googletest:<br/>GoogleTest] end subgraph SUITES [suites] UNITY_SUITES[test/test_bno055,<br/>test/test_pid, ...] GOOGLETEST_SUITES[test/googletest/<br/>test_wire_bus] end NATIVE -->|builds and runs| UNITY_SUITES GOOGLETEST -->|builds and runs| GOOGLETEST_SUITES

PlatformIO takes every folder below test whose name starts with test_ as a PlatformIO test suite, and names the suite by its path: test_pid, or googletest/test_wire_bus (Test Hierarchy). The settings test_filter and test_ignore of platformio.ini compare patterns with that path:

A --filter on the command line replaces the environment's test_filter, but not its test_ignore. So a call that names a suite for the wrong environment builds nothing with the wrong framework: pio test -e native --filter "googletest/*" runs no suite. PlatformIO then reports 0 test cases and no error. CI also checks the result: its unit test job fails when no test case of one of the two environments passed.

The two excerpts of platformio.ini show these settings. The first one is the shared setting, lines 14–22:

platformio.ini: the shared setting
14
15
16
17
18
19
20
21
22
; The unit tests use two frameworks, and each suite is written for one of them:
;   test/test_<name>/             Unity, which can also run on a Teensy
;   test/googletest/test_<name>/  GoogleTest, which PlatformIO doesn't offer for a Teensy
; The test_ignore of this section holds for every environment, so none of them runs a GoogleTest
; suite. Only native_googletest, at the end of this file, sets a test_ignore of its own. So no
; environment builds a suite with the other framework, also with --filter (pio test -e native
; --filter "googletest/*" runs nothing), unless a call replaces test_ignore with --ignore.
[env]
test_ignore = googletest/*
The two environments for the PC, lines 49–88 of platformio.ini

The second excerpt holds the two environments for the PC, lines 49–88:

platformio.ini: the two environments for the PC
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
; The Unity suites on the PC, without a Teensy: pio test -e native
; Only the suites that don't need the Arduino core run here. Three of them use rosserial's node
; handle with a fake serial port (test/fakes). rosserial's library declares the Arduino
; framework, which the native platform doesn't have, so the compatibility check is off for it.
[env:native]
platform = native
test_framework = unity
test_filter =
    test_bno055
    test_command_timeout
    test_imu_publisher
    test_pid
    test_ros_wheel_command_subscriber
    test_synced_node_handle
    test_wheel_control
lib_deps =
    frankjoshua/Rosserial Arduino Library@^0.9.1
lib_compat_mode = off
; C++17, as on the Teensy, without the GNU extensions, so that the code stays portable
build_flags = -std=c++17 -Wall

; The GoogleTest suites on the PC, without a Teensy: pio test -e native_googletest
; They are for code that includes no Arduino and no rosserial header, such as the firmware's
; core. So this environment has no rosserial library, and a suite that includes one of its
; headers doesn't build here.
[env:native_googletest]
platform = native
test_framework = googletest
test_filter = googletest/*
; Instead of the GoogleTest suites, this environment ignores the Unity suites, which lie
; directly in test/
test_ignore = test_*
; PlatformIO 6.2.0's GoogleTest runner asks for google/googletest@^1.17.0, which is any 1.x
; release from 1.17.0 on. PlatformIO installs the exact version below first, and that version
; satisfies the runner's range. So every PC and CI build the tests with the same GoogleTest.
; When PlatformIO's version changes (.docker/firmware/requirements.txt), check its range again.
lib_deps =
    google/googletest@1.17.0
; The same C++ standard and warnings as the Unity suites
build_flags = ${env:native.build_flags}
  • platform = native: both environments build programs for the PC (PlatformIO's native platform).
  • test_framework: unity or googletest. PlatformIO downloads the framework's library and reads the test program's output in that framework's format.
  • lib_deps: native gets the rosserial library, which three of its suites use. native_googletest gets GoogleTest in one exact version, 1.17.0, so that every PC and CI build the tests with the same GoogleTest. The environment has no rosserial library: a GoogleTest suite that includes a rosserial header doesn't build.
  • build_flags: ${env:native.build_flags} takes the value of native, so both environments compile as C++17 with the same warnings (interpolation of values).

Write a GoogleTest suite

A new suite starts as one file with one test. A fixture comes in when several tests share a setup, and a parameterized test when one behavior needs several inputs. The wire bus suite, test_wire_bus.cpp, shows both.

A first suite: one file, one test

This first suite checks that a CommandTimeout (command_timeout.h) starts timed out, so that the wheels don't turn before the first command. Create the folder diffbot_firmware/test/googletest/test_first_suite/, and in it the file test_first_suite.cpp with this content:

test/googletest/test_first_suite/test_first_suite.cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// A first GoogleTest suite: one test of CommandTimeout (lib/command_timeout/command_timeout.h)
#include <gtest/gtest.h>

#include <stdint.h>

#include "command_timeout.h"

// The timeout of the tested CommandTimeout, in milliseconds
constexpr uint32_t TEST_TIMEOUT_MS = 1000;

TEST(CommandTimeoutTest, IsTimedOutWhenConstructed)
{
    const diffbot::CommandTimeout timeout(TEST_TIMEOUT_MS);

    EXPECT_TRUE(timeout.timedOut());
}

int main(int argc, char** argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

Run the suite from the root folder of your diffbot clone:

1
2
3
.docker/firmware/run.sh pio test \
  -e native_googletest \
  --filter googletest/test_first_suite

The test passed when PlatformIO prints CommandTimeoutTest.IsTimedOutWhenConstructed with [PASSED], and the last line counts 1 test cases: 1 succeeded. The environment native_googletest found the new folder by itself, without a change of platformio.ini.

Then check the new file's includes, also from the root folder of your diffbot clone. The include check tools/check_includes.sh gives clang-tidy the flags that pio test compiles the suite with, and reports each name whose header the file doesn't include itself (Check the includes in the diffbot repository's AGENTS.md):

1
2
.docker/firmware/run.sh tools/check_includes.sh native_googletest \
  test/googletest/test_first_suite/test_first_suite.cpp

The command ends with the exit status 0 also when clang-tidy prints a warning, so read its output: no misc-include-cleaner warning may name the new file. This first suite has none. It includes <gtest/gtest.h> for TEST and EXPECT_TRUE, <stdint.h> for uint32_t, and command_timeout.h for CommandTimeout.

The file has four parts:

  • The includes: <gtest/gtest.h> for GoogleTest, and the header of the tested code. PlatformIO finds the headers in the folders of diffbot_firmware/lib. A suite that uses a fake from test/fakes includes it as "../../fakes/<file>".
  • TEST(CommandTimeoutTest, IsTimedOutWhenConstructed): defines a test. The first argument is the GoogleTest test suite, the second the test's name. The name says the subject, the result and the condition, the project's rule for test names (AGENTS.md of the diffbot repository). GoogleTest's names have no underscores (GoogleTest's FAQ), so each word starts with a capital letter.
  • EXPECT_TRUE(timeout.timedOut()): a check that timedOut() returns true. A failed EXPECT_ check marks the test as failed and lets the test go on, so one run shows every failed check. A failed ASSERT_ check returns from the function that it is in. In a test's body, that ends the test, for a check whose failure makes the rest pointless (Assertions in GoogleTest's primer).
  • main(): PlatformIO's GoogleTest library comes without a main() function, so each suite has its own (GoogleTest in PlatformIO). InitGoogleTest() comes first: it reads GoogleTest's options from the command line, such as --gtest_filter (Writing the main() Function in the primer). Then RUN_ALL_TESTS() runs the tests registered in the program that GoogleTest's filter selects: all of them, unless --gtest_filter names some, as in the first command on this page. A Unity suite runs a test only if main() names it in a RUN_TEST line.

main() returns RUN_ALL_TESTS()'s result as the program's exit status, which is 1 when anything failed. The example on PlatformIO's GoogleTest page returns 0 and leaves the result to the output that PlatformIO reads. In our check with PlatformIO 6.2.0, a failure outside a test's body, in a fixture's SetUpTestSuite(), then ended with pio test reporting success. With the exit status 1, the run fails.

This first suite tests code that a Unity suite, test_command_timeout, tests already. Delete its folder when you are done. A real suite takes the name of the code it tests: test/googletest/test_<name>/test_<name>.cpp.

Tests that share a setup: a fixture

The wire bus suite has eight tests of WireBusT that all need a fake Wire library and a WireBusT on it. A fixture is a class with the objects that every test of a group needs. The fixture WireBusTest holds a FakeWire and a WireBusT on it, lines 121–128:

test_wire_bus.cpp: the fixture
120
121
122
123
124
125
126
127
// A fake Wire library and a WireBusT on it. GoogleTest constructs the fixture anew for every
// test, so no test sees what another one sent or received
class WireBusTest : public ::testing::Test
{
protected:
    FakeWire wire_;
    diffbot::WireBusT<FakeWire> bus_{wire_};
};

GoogleTest creates a new WireBusTest object for each test (Test Fixtures in the primer). So each test starts with an empty wire_, and the order of the tests doesn't matter.

FakeWire stands in for Arduino's Wire library. It records each call of beginTransmission(), write(), endTransmission() and requestFrom() as text, such as beginTransmission(0x28) or write(0x3D), in the list calls, in the order of the calls. available() and read() only hand out the received bytes, and calls doesn't list them. FakeWire also returns the results that a test chooses, for example end_result as the result of endTransmission(). The functions beginTransmissionCall(), writeCall(), endTransmissionCall() and requestFromCall() write a call as text. FakeWire records its calls with them, and the tests write the calls that they expect with the same functions.

FakeWire and the functions that write a call as text, lines 53–118

The functions and the fake are lines 53–118:

test_wire_bus.cpp: FakeWire
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// A byte as text, such as 0x28
std::string hexByte(uint8_t value)
{
    char text[sizeof("0xFF")];
    snprintf(text, sizeof(text), "0x%02X", value);
    return text;
}

// Each Wire call as text, such as beginTransmission(0x28). FakeWire records its calls with these
// functions, and the tests write the calls that they expect with the same functions
std::string beginTransmissionCall(uint8_t address)
{
    return "beginTransmission(" + hexByte(address) + ")";
}
std::string writeCall(uint8_t value) { return "write(" + hexByte(value) + ")"; }
std::string endTransmissionCall(bool stop)
{
    return std::string("endTransmission(") + (stop ? "true" : "false") + ")";
}
std::string requestFromCall(uint8_t address, uint8_t length)
{
    return "requestFrom(" + hexByte(address) + ", " + std::to_string(length) + ")";
}

// The calls of Arduino's TwoWire that WireBusT makes, with results a test can choose. FakeWire
// records the calls that start, fill and end a transfer, in their order. available() and read()
// only hand out the received bytes
class FakeWire
{
public:
    std::vector<std::string> calls;  ///< such as beginTransmission(0x28), write(0x3D)
    std::deque<uint8_t> received;
    uint8_t end_result = 0;        ///< endTransmission(): 0 is success
    int reported_count = -1;       ///< requestFrom()'s result; -1: the requested length
    int delivered_count = -1;      ///< bytes really received; -1: the requested length

    void beginTransmission(uint8_t address) { calls.push_back(beginTransmissionCall(address)); }
    size_t write(uint8_t value)
    {
        calls.push_back(writeCall(value));
        return 1;
    }
    uint8_t endTransmission(bool stop = true)
    {
        calls.push_back(endTransmissionCall(stop));
        return end_result;
    }
    uint8_t requestFrom(uint8_t address, uint8_t length)
    {
        calls.push_back(requestFromCall(address, length));
        received.clear();
        int n = delivered_count < 0 ? length : delivered_count;
        for (int i = 0; i < n; ++i)
            received.push_back((uint8_t)(FIRST_DELIVERED_BYTE + i));
        return (uint8_t)(reported_count < 0 ? length : reported_count);
    }
    int available() { return (int)received.size(); }
    int read()
    {
        if (received.empty())
            return -1;
        int value = received.front();
        received.pop_front();
        return value;
    }
};

TEST_F defines a test that uses a fixture. Its first argument is the fixture, its second the test's name. The four tests of writeRegister() are lines 129–165:

test_wire_bus.cpp: the tests of writeRegister()
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
TEST_F(WireBusTest, WriteRegisterSendsRegisterAndValue)
{
    EXPECT_TRUE(bus_.writeRegister(DEVICE_ADDRESS, WRITTEN_REGISTER, WRITTEN_VALUE));

    const std::vector<std::string> expected_calls{
        beginTransmissionCall(DEVICE_ADDRESS), writeCall(WRITTEN_REGISTER),
        writeCall(WRITTEN_VALUE), endTransmissionCall(WITH_STOP)};
    EXPECT_EQ(wire_.calls, expected_calls);
}

TEST_F(WireBusTest, WriteRegisterFailsWhenTheAddressIsNotAcknowledged)
{
    wire_.end_result = ADDRESS_NOT_ACKNOWLEDGED;

    EXPECT_FALSE(bus_.writeRegister(DEVICE_ADDRESS, WRITTEN_REGISTER, WRITTEN_VALUE));
}

// The result of each write is its own: a successful write before doesn't hide a failure
TEST_F(WireBusTest, WriteRegisterFailsWhenTheAddressIsNotAcknowledgedAfterASuccessfulWrite)
{
    // 1. A write that the device acknowledges
    ASSERT_TRUE(bus_.writeRegister(DEVICE_ADDRESS, WRITTEN_REGISTER, WRITTEN_VALUE));

    // 2. The next write on the same bus, which no device acknowledges
    wire_.end_result = ADDRESS_NOT_ACKNOWLEDGED;
    EXPECT_FALSE(bus_.writeRegister(DEVICE_ADDRESS, WRITTEN_REGISTER, WRITTEN_VALUE));
}

TEST_F(WireBusTest, WriteRegisterPassesOnTheAddressRegisterAndValue)
{
    EXPECT_TRUE(bus_.writeRegister(ALTERNATE_DEVICE_ADDRESS, RESET_REGISTER, RESET_VALUE));

    const std::vector<std::string> expected_calls{
        beginTransmissionCall(ALTERNATE_DEVICE_ADDRESS), writeCall(RESET_REGISTER),
        writeCall(RESET_VALUE), endTransmissionCall(WITH_STOP)};
    EXPECT_EQ(wire_.calls, expected_calls);
}
  • The members: wire_ and bus_ are the fixture's. The first test calls bus_.writeRegister() and then compares wire_.calls with expected_calls: the device's address, the register, the value, and the end of the transfer with a stop.
  • The values: they have names, which the top of the file defines, such as DEVICE_ADDRESS, WRITTEN_REGISTER, WRITTEN_VALUE, ADDRESS_NOT_ACKNOWLEDGED and WITH_STOP.
  • A scenario in phases: the third test checks two calls on the same bus_, in numbered phases. A write that the device acknowledges comes first, and the next write, which no device acknowledges, has to fail. Its first check is an ASSERT_ check, because a failed first write would leave nothing to check in phase 2.
  • A second set of values: the fourth test writes RESET_VALUE to RESET_REGISTER at ALTERNATE_DEVICE_ADDRESS, 0x29, the BNO055's address when its ADR pin is high. Each of these values differs from those of the first three tests, so the test shows that WireBusT passes on the values that it gets.

The pictures show each of the four tests as a time line: the values that the test sets on wire_, its call of bus_, the calls that WireBusT makes on FakeWire, the result, and the checks. In the second test, and in the second write of the third test, endTransmission() returns 2, and that write fails:

The time line of the test WriteRegisterSendsRegisterAndValue bus_.writeRegister(0x28, 0x3D, 0x08) beginTransmission(0x28) starts a transfer write(0x3D) the register write(0x08) the value endTransmission(true) → 0 stop: frees the bus 2 1 returns true 1 EXPECT_TRUE: the call returns true 2 EXPECT_EQ: wire_.calls holds the boxed calls
WriteRegisterSendsRegisterAndValue: The device acknowledges: four calls, and the result true.
The time line of the test WriteRegisterFailsWhenTheAddressIsNotAcknowledged wire_.end_result = 2 no device acknowledges bus_.writeRegister(0x28, 0x3D, 0x08) beginTransmission(0x28) starts a transfer write(0x3D) the register write(0x08) the value endTransmission(true) → 2 not acknowledged 1 returns false 1 EXPECT_FALSE: the call returns false
WriteRegisterFailsWhenTheAddressIsNotAcknowledged: endTransmission() returns 2, so the result is false. The test checks only the result.
The time line of the test WriteRegisterFailsWhenTheAddressIsNotAcknowledgedAfterASuccessfulWrite 1. A write that the device acknowledges bus_.writeRegister(0x28, 0x3D, 0x08) beginTransmission(0x28) starts a transfer write(0x3D) the register write(0x08) the value endTransmission(true) → 0 stop: frees the bus 1 returns true 2. The next write, not acknowledged wire_.end_result = 2 no device acknowledges bus_.writeRegister(0x28, 0x3D, 0x08) beginTransmission(0x28) starts a transfer write(0x3D) the register write(0x08) the value endTransmission(true) → 2 not acknowledged 2 returns false 1 ASSERT_TRUE: the first call returns true 2 EXPECT_FALSE: the second call returns false
WriteRegisterFailsWhenTheAddressIsNotAcknowledgedAfterASuccessfulWrite: Two writes on the same bus_: the first one succeeds, and the second one fails.
The time line of the test WriteRegisterPassesOnTheAddressRegisterAndValue bus_.writeRegister(0x29, 0x3F, 0x20) beginTransmission(0x29) starts a transfer write(0x3F) the register write(0x20) the value endTransmission(true) → 0 stop: frees the bus 2 1 returns true 1 EXPECT_TRUE: the call returns true 2 EXPECT_EQ: wire_.calls holds the boxed calls
WriteRegisterPassesOnTheAddressRegisterAndValue: The second set of values, 0x29, 0x3F and 0x20, arrives unchanged in the calls.
The four tests of writeRegister(), one time line per test. Time runs down. The test calls bus_ with the values of the top line. WireBusT's calls of FakeWire follow, each with a filled dot on the time line: a call that FakeWire records in calls. The result comes back at the bottom. A bold orange value is one that the test sets on wire_ before the call. A number in a blue disc is a check, and the list under the time line names it. The disc on the corner of a box marks the calls that EXPECT_EQ compares.

Three of the four tests of readRegisters() compare wire_.calls the same way. The test of a sample's bytes compares the bytes in data instead. In a read, the register write ends with a repeated start, endTransmission(false), and only then comes the read request, requestFrom(). After a register write that no device acknowledges, no read request may follow. A read of CHIP_ID_REGISTER from ALTERNATE_DEVICE_ADDRESS checks that WireBusT passes on that register, and that address in both the register write and the read request.

The pictures show the four tests of readRegisters() as time lines. After requestFrom(), readRegisters() asks available() how many bytes arrived and reads them with read(), and calls lists neither. In the last test, the calls end after the register write:

The time line of the test ReadRegistersUsesARepeatedStart bus_.readRegisters(0x28, 0x08, data.data(), 3) beginTransmission(0x28) starts a transfer write(0x08) the register endTransmission(false) → 0 repeated start requestFrom(0x28, 3) → 3 read request available() → 3 3 bytes arrived read() × 3 into data 2 1 returns true 1 EXPECT_TRUE: the call returns true 2 EXPECT_EQ: wire_.calls holds the boxed calls
ReadRegistersUsesARepeatedStart: The register write ends with a repeated start, and the read request follows.
The time line of the test ReadRegistersPassesOnTheAddressAndRegister bus_.readRegisters(0x29, 0x00, data.data(), 3) beginTransmission(0x29) starts a transfer write(0x00) the register endTransmission(false) → 0 repeated start requestFrom(0x29, 3) → 3 read request available() → 3 3 bytes arrived read() × 3 into data 2 1 returns true 1 EXPECT_TRUE: the call returns true 2 EXPECT_EQ: wire_.calls holds the boxed calls
ReadRegistersPassesOnTheAddressAndRegister: The address 0x29 and the register 0x00 arrive unchanged in the calls.
The time line of the test ReadRegistersReturnsAllBytesOfASample bus_.readRegisters(0x28, 0x08, data.data(), 18) beginTransmission(0x28) starts a transfer write(0x08) the register endTransmission(false) → 0 repeated start requestFrom(0x28, 18) → 18 read request In the Wire library: 18 bytes 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 available() → 18 18 bytes arrived read() × 18 into data 1 returns true 2 data after the call 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 1 EXPECT_TRUE: the call returns true 2 EXPECT_EQ: data holds the delivered bytes
ReadRegistersReturnsAllBytesOfASample: All 18 bytes arrive, and data holds them in their order. The test checks the result and the bytes, not the calls.
The time line of the test ReadRegistersFailsWithoutAReadRequestWhenTheRegisterWriteFails wire_.end_result = 2 no device acknowledges bus_.readRegisters(0x28, 0x08, data.data(), 3) beginTransmission(0x28) starts a transfer write(0x08) the register endTransmission(false) → 2 not acknowledged requestFrom(0x28, 3) not called 2 1 returns false 1 EXPECT_FALSE: the call returns false 2 EXPECT_EQ: wire_.calls holds the boxed calls
ReadRegistersFailsWithoutAReadRequestWhenTheRegisterWriteFails: No device acknowledges the register write, so no read request follows.
The four tests of readRegisters() with the fixture WireBusTest. The dots, values and numbers read as in the pictures of writeRegister(): time runs down, a filled dot is a call that calls lists, a bold orange value is set by the test, and a number in a blue disc is a check. An open dot is a call that calls doesn't list: available() or read(). A struck-through call on a dashed dot is one that the test expects not to happen. A row of boxes holds bytes in hex, such as 10 for 0x10.
The four tests of readRegisters(), lines 167–219

The tests are lines 167–219 of test_wire_bus.cpp. The third, ReadRegistersReturnsAllBytesOfASample, is the successful read of the next section's table:

test_wire_bus.cpp: the tests of readRegisters()
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
TEST_F(WireBusTest, ReadRegistersUsesARepeatedStart)
{
    std::array<uint8_t, READ_LENGTH_BYTES> data{};

    EXPECT_TRUE(bus_.readRegisters(DEVICE_ADDRESS, READ_REGISTER, data.data(), data.size()));

    // The register write ends with a repeated start, and the read request comes after it
    const std::vector<std::string> expected_calls{
        beginTransmissionCall(DEVICE_ADDRESS), writeCall(READ_REGISTER),
        endTransmissionCall(WITH_REPEATED_START),
        requestFromCall(DEVICE_ADDRESS, READ_LENGTH_BYTES)};
    EXPECT_EQ(wire_.calls, expected_calls);
}

TEST_F(WireBusTest, ReadRegistersPassesOnTheAddressAndRegister)
{
    std::array<uint8_t, READ_LENGTH_BYTES> data{};

    EXPECT_TRUE(
        bus_.readRegisters(ALTERNATE_DEVICE_ADDRESS, CHIP_ID_REGISTER, data.data(), data.size()));

    const std::vector<std::string> expected_calls{
        beginTransmissionCall(ALTERNATE_DEVICE_ADDRESS), writeCall(CHIP_ID_REGISTER),
        endTransmissionCall(WITH_REPEATED_START),
        requestFromCall(ALTERNATE_DEVICE_ADDRESS, READ_LENGTH_BYTES)};
    EXPECT_EQ(wire_.calls, expected_calls);
}

TEST_F(WireBusTest, ReadRegistersReturnsAllBytesOfASample)
{
    std::array<uint8_t, SAMPLE_LENGTH_BYTES> data{};

    EXPECT_TRUE(bus_.readRegisters(DEVICE_ADDRESS, READ_REGISTER, data.data(), data.size()));

    // FIRST_DELIVERED_BYTE, and each further byte one higher
    std::array<uint8_t, SAMPLE_LENGTH_BYTES> delivered_bytes{};
    std::iota(delivered_bytes.begin(), delivered_bytes.end(), FIRST_DELIVERED_BYTE);
    EXPECT_EQ(data, delivered_bytes);
}

TEST_F(WireBusTest, ReadRegistersFailsWithoutAReadRequestWhenTheRegisterWriteFails)
{
    wire_.end_result = ADDRESS_NOT_ACKNOWLEDGED;
    std::array<uint8_t, READ_LENGTH_BYTES> data{};

    EXPECT_FALSE(bus_.readRegisters(DEVICE_ADDRESS, READ_REGISTER, data.data(), data.size()));

    // The register write, and no read request after it
    const std::vector<std::string> expected_calls{
        beginTransmissionCall(DEVICE_ADDRESS), writeCall(READ_REGISTER),
        endTransmissionCall(WITH_REPEATED_START)};
    EXPECT_EQ(wire_.calls, expected_calls);
}

One behavior with several inputs: a parameterized test

A read can come back short in several ways, and readRegisters() has to fail for each of them. The BNO055 driver reads a sample's 18 data bytes in one transfer. readRegisters() asks Wire's requestFrom() for that requested length, and two counts come back:

  • Reported: the count that requestFrom() returns.
  • Arrived: the bytes that are really there, which available() tells.

readRegisters() returns true only when both counts are the requested length. Otherwise it returns false, and it reads the bytes that arrived out of the Wire library, so that none of them is left for the next read. The table shows the successful read and the four short reads of the suite, each with 18 bytes requested, and what readRegisters() returns:

Read Reported Arrived Returns
A sample's data 18 18 true
Both short 4 4 false
Reported short, all bytes there 4 18 false
Reported one short, all bytes there 17 18 false
Reported in full, one byte missing 18 17 false

After each of the five reads, no byte may be left in the Wire library. The successful read copies its 18 bytes into data, and a short read drains the bytes that arrived. The test ReadRegistersReturnsAllBytesOfASample checks that read and the 18 bytes in data. The four short reads are the cases of a parameterized test. Their names in the code join the words of the first column, such as BothShort.

The case BothShort is a read that the Teensy 4's Wire library can deliver when it can't get the bus. Its requestFrom() then returns 4, and it returns before it empties its receive buffer. So available() then counts what an earlier read left there. In BothShort, that is 4 bytes, and both counts agree with each other, but not with the 18 requested bytes. The start of requestFrom() in the Teensy 4's Wire library is lines 155–163 of WireIMXRT.cpp:

WireIMXRT.cpp: the start of requestFrom()
155
156
157
158
159
160
161
162
163
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t length, uint8_t sendStop)
{
    IMXRT_LPI2C_t* port = (IMXRT_LPI2C_t*)portAddr;
    if (!wait_idle()) return 4;
    address = (address & 0x7F) << 1;
    if (length < 1) length = 1;
    if (length > 255) length = 255;
    rxBufferIndex = 0;
    rxBufferLength = 0;

The four cases are examples of short reads, not every possible one. Two have a short reported count with all bytes there, 4 and 17 of 18. One has both counts short, and one has a byte missing behind a full count. They are four inputs to one behavior: readRegisters() fails and drains the bytes. A parameterized test is written once and runs once per case. The type ShortRead describes a case, and the fixture WireBusShortReadTest adds the case to WireBusTest, lines 221–243:

test_wire_bus.cpp: the type of a case and the fixture
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// A count that the Teensy 4's Wire can report after a failed bus acquisition, with or without
// data
constexpr int COUNT_AFTER_FAILED_BUS_ACQUISITION = 4;

// One way in which a read comes back short of the requested SAMPLE_LENGTH_BYTES
struct ShortRead
{
    const char* name;     ///< The case's name in the test's output
    int reported_count;   ///< requestFrom()'s result
    int delivered_count;  ///< The bytes that really arrive
};

// GoogleTest prints a failed test's parameter with this operator
std::ostream& operator<<(std::ostream& output, const ShortRead& short_read)
{
    return output << "requestFrom() reports " << short_read.reported_count << " bytes, "
                  << short_read.delivered_count << " bytes arrive";
}

// The fixture of the parameterized test: WireBusTest's members, and one ShortRead per run
class WireBusShortReadTest : public WireBusTest, public ::testing::WithParamInterface<ShortRead>
{
};

TEST_P defines the test, and INSTANTIATE_TEST_SUITE_P lists the cases, lines 245–274:

test_wire_bus.cpp: the parameterized test and its cases
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// The count that requestFrom() reports and the bytes really received both have to be the
// requested length. GoogleTest runs this test once for each ShortRead below
TEST_P(WireBusShortReadTest, ReadRegistersFailsAndDrainsTheBytes)
{
    const ShortRead& short_read = GetParam();
    wire_.reported_count = short_read.reported_count;
    wire_.delivered_count = short_read.delivered_count;
    std::array<uint8_t, SAMPLE_LENGTH_BYTES> data{};

    EXPECT_FALSE(bus_.readRegisters(DEVICE_ADDRESS, READ_REGISTER, data.data(), data.size()));

    // The read request asked for the whole sample, so the bus came back short of it
    const std::vector<std::string> expected_calls{
        beginTransmissionCall(DEVICE_ADDRESS), writeCall(READ_REGISTER),
        endTransmissionCall(WITH_REPEATED_START),
        requestFromCall(DEVICE_ADDRESS, SAMPLE_LENGTH_BYTES)};
    EXPECT_EQ(wire_.calls, expected_calls);
    EXPECT_EQ(wire_.available(), 0) << "bytes of the short read are left in the Wire library";
}

INSTANTIATE_TEST_SUITE_P(
    ShortReads, WireBusShortReadTest,
    ::testing::Values(
        ShortRead{"ReportedShortAllBytesThere", COUNT_AFTER_FAILED_BUS_ACQUISITION,
                  SAMPLE_LENGTH_BYTES},
        ShortRead{"BothShort", COUNT_AFTER_FAILED_BUS_ACQUISITION,
                  COUNT_AFTER_FAILED_BUS_ACQUISITION},
        ShortRead{"ReportedInFullOneByteMissing", SAMPLE_LENGTH_BYTES, SAMPLE_LENGTH_BYTES - 1},
        ShortRead{"ReportedOneShortAllBytesThere", SAMPLE_LENGTH_BYTES - 1, SAMPLE_LENGTH_BYTES}),
    [](const ::testing::TestParamInfo<ShortRead>& info) { return std::string(info.param.name); });

The pictures show the four cases as time lines. Each case starts with the two counts that it sets on wire_ and ends with the three checks. readRegisters() calls available() in its comparison only when requestFrom() reports the full 18 bytes: || stops at the first comparison that is true. The loop after it reads the bytes that arrived until available() returns 0:

The time line of the case ReportedShortAllBytesThere wire_.reported_count = 4 what requestFrom() reports wire_.delivered_count = 18 the bytes that arrive bus_.readRegisters(0x28, 0x08, data.data(), 18) beginTransmission(0x28) starts a transfer write(0x08) the register endTransmission(false) → 0 repeated start requestFrom(0x28, 18) → 4 read request In the Wire library: 18 of 18 bytes 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 requestFrom() reports 4 read() × 18 dropped 2 1 returns false 3 wire_.available() → 0 no byte left 1 EXPECT_FALSE: the call returns false 2 EXPECT_EQ: wire_.calls holds the boxed calls 3 EXPECT_EQ: wire_.available() is 0
ReportedShortAllBytesThere: requestFrom() reports 4, and all 18 bytes arrive.
The time line of the case BothShort wire_.reported_count = 4 what requestFrom() reports wire_.delivered_count = 4 the bytes that arrive bus_.readRegisters(0x28, 0x08, data.data(), 18) beginTransmission(0x28) starts a transfer write(0x08) the register endTransmission(false) → 0 repeated start requestFrom(0x28, 18) → 4 read request In the Wire library: 4 of 18 bytes 10 11 12 13 requestFrom() reports 4 read() × 4 dropped 2 1 returns false 3 wire_.available() → 0 no byte left 1 EXPECT_FALSE: the call returns false 2 EXPECT_EQ: wire_.calls holds the boxed calls 3 EXPECT_EQ: wire_.available() is 0
BothShort: requestFrom() reports 4, and 4 bytes arrive.
The time line of the case ReportedInFullOneByteMissing wire_.reported_count = 18 what requestFrom() reports wire_.delivered_count = 17 the bytes that arrive bus_.readRegisters(0x28, 0x08, data.data(), 18) beginTransmission(0x28) starts a transfer write(0x08) the register endTransmission(false) → 0 repeated start requestFrom(0x28, 18) → 18 read request In the Wire library: 17 of 18 bytes 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 requestFrom() reports 18 available() → 17 one byte short read() × 17 dropped 2 1 returns false 3 wire_.available() → 0 no byte left 1 EXPECT_FALSE: the call returns false 2 EXPECT_EQ: wire_.calls holds the boxed calls 3 EXPECT_EQ: wire_.available() is 0
ReportedInFullOneByteMissing: requestFrom() reports 18, and 17 bytes arrive.
The time line of the case ReportedOneShortAllBytesThere wire_.reported_count = 17 what requestFrom() reports wire_.delivered_count = 18 the bytes that arrive bus_.readRegisters(0x28, 0x08, data.data(), 18) beginTransmission(0x28) starts a transfer write(0x08) the register endTransmission(false) → 0 repeated start requestFrom(0x28, 18) → 17 read request In the Wire library: 18 of 18 bytes 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 requestFrom() reports 17 read() × 18 dropped 2 1 returns false 3 wire_.available() → 0 no byte left 1 EXPECT_FALSE: the call returns false 2 EXPECT_EQ: wire_.calls holds the boxed calls 3 EXPECT_EQ: wire_.available() is 0
ReportedOneShortAllBytesThere: requestFrom() reports 17, and all 18 bytes arrive.
The four cases of ReadRegistersFailsAndDrainsTheBytes. The dots, values and numbers read as in the pictures of writeRegister() and readRegisters(): time runs down, a filled dot is a call that calls lists, an open dot one that it doesn't list, a bold orange value is set by the test, and a number in a blue disc is a check. Each case requests a sample's 18 bytes. The row of boxes is the Wire library's receive buffer after requestFrom(): a box with a value is a byte that arrived, a dashed box one that didn't. The orange bracket under it spans the count that requestFrom() reports. The read() calls drop the bytes, and the line after the result is the test's own call of available().

Written as a loop inside one Unity test, the cases would end at the first one that fails. Unity's message would name the line of the check, and not the case.

See each test fail once

Break the behavior that one of your checks promises, on purpose, run the suite, read the failure, and undo the change. Then you know that the check can fail. For example, EXPECT_EQ(wire_.available(), 0) promises that a short read leaves no byte behind. Without the loop that drains the bytes in readRegisters(), all four short-read cases fail at that check. A change that breaks a different behavior can pass a test that is focused on one behavior. Another test of the suite has to catch that change.

Before the pull request

Run every suite, with the first command of All suites, one environment or one suite, as CI does. Check the includes of each C++ file that you changed, as for the first suite.

Comments

Comments are GitHub Discussions, shown with giscus. Loading them connects to giscus.app (hosted by Vercel, USA) and GitHub (USA); you need a GitHub account to comment.