Module 22 · Lesson 36 of 64

Mocking and hardware fakes

Replace serial, SSH, subprocess and hardware calls with mocks and in-memory fakes so device-control tests run with no board attached.

  • Beginner to advanced
  • 12 min read
  • 30 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM; Python 3.12 with pytest and pytest-mock installed; no board needed

Your place in the module
By the end you can 4 objectives
  • Replace serial, SSH and subprocess calls with unittest.mock and the pytest-mock mocker fixture
  • Assert call arguments, counts and order on mocks to verify device-control logic
  • Test CLI exit codes and printed output with capsys and a mocked subprocess.run
  • Build in-memory serial, I2C and GPIO fakes that implement the same interface as the real libraries
Video coming soonMocking and hardware fakes
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Fixtures and parametrized tests
  • A yield fixture runs setup before yield and teardown after it, even when the test fails
  • tmp_path gives each test a fresh temporary directory as a pathlib.Path
  • parametrize turns one test function into one test per input, each reported separately
01

Replace hardware calls with mocks

5 min read

In the previous lesson you parametrized tests over sample inputs. This lesson replaces serial, SSH and hardware calls with unittest.mock and in-memory device fakes, and tests CLI exit codes and output without real devices.

The problem is concrete: your CI runner is a cloud VM. It has no /dev/ttyUSB0, no Raspberry Pi on 192.168.1.50, no I2C bus. If read_temperature() opens a real serial port, the test fails on the first line, and it fails for a reason that has nothing to do with your code. The logic you actually want to test is yours: did the function send the right command bytes, parse the reply correctly, and raise a clean error on timeout? The serial driver itself was already exercised against real hardware in the pyserial lesson. A lets you test your logic in isolation, milliseconds per test, on any machine.

Python ships the tool in the standard library: unittest.mock. You do not install anything to use it, and it works under pytest even though the name says unittest. The two workhorses are Mock and MagicMock. A Mock records every call and every attribute access, and it invents child mocks on demand: m.ser.write exists the moment you touch it. You script its answers with return_value (what a call returns) and side_effect (an exception to raise, or an iterable of successive answers). MagicMock is a Mock that also preconfigures the magic methods: __enter__ and __exit__ for with blocks, __len__, __getitem__, and so on. That distinction matters immediately, because pyserial ports are usually used as context managers.

Here is the function under test, in devctl.py:

python
from serial import Serial

def read_temperature(port="/dev/ttyUSB0"):
    with Serial(port, 115200, timeout=1) as ser:
        ser.write(b"TEMP?\n")
        line = ser.readline()
    if not line:
        raise TimeoutError(f"no reply from {port}")
    return float(line.strip())

And the test, using the mocker fixture from the pytest-mock plugin (pip install pytest-mock):

python
import devctl

def test_read_temperature(mocker):
    serial_cls = mocker.patch("devctl.Serial")
    ser = serial_cls.return_value.__enter__.return_value
    ser.readline.return_value = b"23.5\n"

    assert devctl.read_temperature() == 23.5

    serial_cls.assert_called_once_with("/dev/ttyUSB0", 115200, timeout=1)
    ser.write.assert_called_once_with(b"TEMP?\n")

Read the chaining carefully, because it is the part beginners stumble on. mocker.patch("devctl.Serial") replaces the name Serial inside the devctl module with a MagicMock and hands you that mock. Calling it, Serial(port, 115200, timeout=1), returns serial_cls.return_value. The with statement then calls __enter__ on that object, so the name ser inside the function is bound to serial_cls.return_value.__enter__.return_value. You script readline on exactly that object. No port is opened, no bytes move, and the whole test runs in memory.

The assertions are the second half of mocking: a mock is not just a stub that returns canned data, it is a recorder. assert_called_once_with(...) checks that the call happened exactly once with exactly those arguments, so a refactor that silently changes the baud rate or the command bytes fails the test. For multi-call sequences you inspect call_args_list (every call, in order) and call_count, or use assert_has_calls for ordered fragments. If you want the port to time out, set ser.readline.return_value = b"" and wrap the call in pytest.raises(TimeoutError): pyserial returns empty bytes on timeout, and your error path gets tested without waiting a real second.

pytest-mock is a thin convenience layer over unittest.mock: mocker.patch behaves like unittest.mock.patch but automatically undoes every patch at the end of the test, so a leaked mock can never poison the next test. Without the plugin you would write with patch("devctl.Serial") as serial_cls: inside each test, or decorate it with @patch("devctl.Serial"). All three forms do the same replacement; the fixture just removes the boilerplate and the risk of forgetting cleanup.

SSH gets the same treatment. Suppose devctl.py also has:

python
import paramiko

def uptime(host):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.connect(host, username="root")
    _, out, _ = client.exec_command("cat /proc/uptime")
    data = out.read().decode()
    client.close()
    return float(data.split()[0])

exec_command returns a three-tuple of file-like objects. One subtlety: a MagicMock supports iteration, but its default __iter__ yields nothing, so unpacking three names from a bare mock's return value would raise ValueError. Set the tuple explicitly:

python
def test_uptime(mocker):
    cls = mocker.patch("devctl.paramiko.SSHClient")
    client = cls.return_value
    out = mocker.Mock()
    out.read.return_value = b"123.45 456.78\n"
    client.exec_command.return_value = (mocker.Mock(), out, mocker.Mock())

    assert devctl.uptime("192.168.1.50") == 123.45
    client.connect.assert_called_once_with("192.168.1.50", username="root")
    client.exec_command.assert_called_once_with("cat /proc/uptime")

The uptime values are test data you chose, not a reading from any machine. No TCP connection is made, no host key is checked, and the test still proves that your function connects with the right username, runs the right command, and parses the first field correctly.

One mocked serial testTestread_temperatureMagicMockpatch devctl.Serialcall functionSerial(port, 115200)write(TEMP?)readline: 23.5assert calls1. Test → MagicMockpatch devctl.Serial2. Test → read_temperaturecall function3. read_temperature →MagicMockSerial(port, 115200)4. read_temperature →MagicMockwrite(TEMP?)5. MagicMock →read_temperaturereadline: 23.56. Test → MagicMockassert calls
One mocked test: the patch swaps the class, the function talks to the MagicMock, and the test asserts the recorded calls.
02

Test CLIs and subprocess without running anything

3 min read

The command-line tool lesson built the pattern this section tests: a main(argv) function that returns an integer exit code, and a thin entry point that does raise SystemExit(main()). That shape is testable for free. You call main(["kernel"]) like any function and assert on the return value; you only need pytest.raises(SystemExit) when you test the entry point itself, and then the code is in exc.value.code. The convention comes from the operating system: a process terminates with a status via exit(3), the parent collects it with waitpid(2), and only the low 8 bits survive, which is why exit codes live in 0 to 255, with 0 meaning success. Under the hood subprocess.run creates a child process and executes a program through the fork and execve(2) machinery; in a unit test you replace all of that with one mock.

For output, pytest gives you the capsys fixture. It swaps sys.stdout and sys.stderr for capture buffers; capsys.readouterr() returns an object with .out and .err strings and empties the buffers, so each assertion sees only what was printed since the last read. Here is a small CLI in cli.py and its tests:

python
import subprocess
import sys

def main(argv):
    if argv != ["kernel"]:
        print("usage: devctl kernel", file=sys.stderr)
        return 2
    result = subprocess.run(["uname", "-r"], capture_output=True, text=True)
    print(result.stdout, end="")
    return result.returncode

The structure is the point: validate, run, print, return a code.

python
import subprocess
import cli

def test_kernel_ok(mocker, capsys):
    run = mocker.patch("cli.subprocess.run")
    run.return_value = subprocess.CompletedProcess(
        args=["uname", "-r"], returncode=0,
        stdout="6.8.0-test\n", stderr="")

    assert cli.main(["kernel"]) == 0
    assert capsys.readouterr().out == "6.8.0-test\n"
    run.assert_called_once_with(["uname", "-r"],
                                capture_output=True, text=True)

def test_usage_error(capsys):
    assert cli.main([]) == 2
    assert "usage" in capsys.readouterr().err

The right object to return from a mocked subprocess.run is a real subprocess.CompletedProcess: it is a simple container with args, returncode, stdout and stderr, and with capture_output=True, text=True the streams are strings. Building a real one instead of a mock means your code can touch any of its attributes without extra setup. The "6.8.0-test\n" string is invented fixture data, not output from a real uname; on your machine the real kernel release string will differ, and that is exactly why the test must not depend on it.

Failure paths are where subprocess mocking earns its keep, because producing them for real is awkward. A nonzero exit is just returncode=1 in the CompletedProcess. If your code uses check=True, run raises subprocess.CalledProcessError instead of returning, and you simulate that with side_effect:

python
run.side_effect = subprocess.CalledProcessError(127, ["uname", "-r"])

Now the test exercises your exception handler, retry logic or error message without needing a command that actually fails. You can also simulate FileNotFoundError (the binary does not exist) or subprocess.TimeoutExpired the same way: three failure modes, three lines of setup, zero real processes.

capsys does not see real child output

capsys captures at the Python level: it replaces sys.stdout and sys.stderr. If you let subprocess.run actually execute, the child writes to file descriptors 1 and 2 directly, bypassing those Python objects, and capsys.readouterr().out comes back empty. For fd-level capture pytest offers capfd. In unit tests the cleaner answer is to mock subprocess.run and feed it a CompletedProcess, as above; save capfd for the rare integration test that must run a real child.

CLI path under testmain(argv)Check argssubprocess.runmocked intestsprintstdoutExit from step 2: bad argsreturn 2return 0main(argv)Check argsExit from step 2: bad argsreturn 2subprocess.runmocked intestsprintstdoutreturn 0
The CLI path under test: argument validation can exit early with code 2; the mocked subprocess.run decides the remaining exit code.
03

In-memory fakes for serial, I2C and GPIO

6 min read

Mocks are perfect for one question: "did my code make the right call?" They get clumsy when the device is stateful, when a test drives a multi-step exchange, or when a parser needs a realistic stream of replies. For that you write a . The rule that makes fakes trustworthy: implement the same interface, with the same method names, argument shapes and return types as the real library. Then the code under test cannot tell the difference, and the same test suite can later run against real hardware in the board-in-the-loop lesson.

A fake serial port that mirrors the slice of pyserial your code uses:

python
from collections import deque

class FakeSerial:
    def __init__(self, port, baudrate=9600, timeout=None):
        self.port = port
        self.written = []
        self.responses = deque()

    def queue(self, *lines):
        self.responses.extend(lines)

    def write(self, data):
        self.written.append(data)
        return len(data)

    def readline(self):
        if not self.responses:
            return b""
        return self.responses.popleft()

    def close(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()

The details match pyserial on purpose: write returns the number of bytes written, and readline returns b"" when nothing arrives before the timeout. To install it, use pytest's built-in monkeypatch fixture with a factory that captures the instance so the test can inspect it afterwards:

python
import devctl

def test_temperature_fake(monkeypatch):
    made = []
    def factory(*args, **kwargs):
        ser = FakeSerial(*args, **kwargs)
        ser.queue(b"23.5\n")
        made.append(ser)
        return ser

    monkeypatch.setattr(devctl, "Serial", factory)
    assert devctl.read_temperature() == 23.5
    assert made[0].written == [b"TEMP?\n"]

monkeypatch.setattr replaces the attribute and restores it after the test, just like mocker.patch, but it installs whatever object you give it and records nothing itself: the fake's written list does the recording. Combine it with the previous lesson's @pytest.mark.parametrize to sweep replies and expected values, including the empty-reply timeout case, from one test function.

The same pattern covers the buses from the hardware session. smbus2 centres on read_byte_data(addr, reg) and write_byte_data(addr, reg, value), so a fake I2C bus is a dict keyed by (addr, reg):

python
class FakeI2C:
    def __init__(self):
        self.regs = {}

    def write_byte_data(self, addr, reg, value):
        self.regs[(addr, reg)] = value

    def read_byte_data(self, addr, reg):
        return self.regs.get((addr, reg), 0)

Seed regs with the register map from a sensor datasheet and your driver code reads plausible data with no bus attached. For GPIO, fake the thin wrapper your project uses (a set_value(pin, value) / get_value(pin) pair backed by a dict); the gpiod lesson builds that wrapper, and keeping hardware access behind it is exactly what makes this substitution possible. A fake GPIO can also model behaviour a mock cannot easily express, such as a button pin whose value flips after three reads.

Choosing between the two is a judgement call, not a rule. Reach for a mock when the assertion is about an interaction ("the flasher invoked subprocess.run with these exact arguments") and the dependency is called once or twice. Reach for a fake when the test is about behaviour over time: a protocol handshake, a log parser fed fifty lines, a retry loop that must see two failures then a success. Over-mocking is a real failure mode: a test that scripts every return value of a five-step exchange mostly re-states the implementation, and breaks on every refactor while proving little. A fake with simple, honest state usually survives refactors better.

Going deeperExplore the mechanism

Patch where the name is looked up, not where it is defined. This is the single most common mocking bug. devctl.py does from serial import Serial, which copies a reference into the devctl namespace at import time. Patching serial.Serial afterwards replaces the attribute on the serial module, but devctl.Serial still points at the original class, so the test opens a real port (or fails with no port present). The correct target is "devctl.Serial". If the module instead did import serial and called serial.Serial(...), the lookup goes through the serial module at call time, and "serial.Serial" (equivalently "devctl.serial.Serial") is correct. The same rule applies to monkeypatch.setattr(devctl, "Serial", ...): you are rebinding the name in the consumer's namespace. A related pitfall: patching after an object was already created does nothing, because the instance holds its own references; patch before the code under test constructs anything.

autospec for signature correctness. A bare MagicMock accepts any call: Serial() with no arguments, ser.write("text", 42) with nonsense arguments, all silently recorded. Your test then passes against an API the real library would reject. mocker.patch("devctl.Serial", autospec=True) builds the mock from the real class's signature, so a call with wrong arguments raises TypeError inside the test, and the constraint applies to the instance's methods too. One catch with context managers: the object a with block binds is __enter__.return_value, which is a plain MagicMock that checks nothing (verified: ser.write(b"x", 7) was accepted through it). Alias it to the autospecced instance first:

python
cls = mocker.patch("devctl.Serial", autospec=True)
ser = cls.return_value
cls.return_value.__enter__.return_value = ser   # now ser.write(b"x", 7) raises TypeError

Note the difference from spec=Serial: spec only restricts which attributes exist (accessing an undefined one raises AttributeError) but does not check call signatures. Use autospec=True by default when mocking hardware libraries: when pyserial or paramiko changes an API, your mocks fail loudly instead of drifting away from reality.

Mock, fake or real boardMockFakeReal boardStatenone, recordscallsin-memoryphysicalVerifiescalls andargumentsbehaviourover timedrivers andtimingHardware needednonoyesRuns in CIyesyesonly with arigBest forinteractiontestsprotocollogicfinalvalidation
Mocks record interactions, fakes implement behaviour, and the real board validates the drivers and timing; the same interface lets one suite move between them.

With doubles in place, your device tooling now has a fast, hardware-free test suite: mocked interactions, stateful fakes, and CLI tests that check exit codes and output. The next lesson asks how much of the code those tests actually exercise and how to keep the growing suite organized: coverage, test organization and async tests, including how the same mocking ideas extend to async device services.

Key takeaways

  • Patch the namespace where a name is looked up (devctl.Serial), not the module where it is defined (serial.Serial)
  • mocker.patch creates a MagicMock by default, so context managers and other magic methods work; plain Mock does not support them
  • capsys captures Python-level sys.stdout and sys.stderr only; output of a real child process needs capfd
  • autospec=True makes a mock enforce the real call signature, so wrong arguments raise TypeError; mocks record interactions while fakes carry state for multi-step protocol logic
Reflect
  1. Explain to a colleague, in two sentences: replace serial, SSH and subprocess calls with unittest.mock and the pytest-mock mocker fixture
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close