Testing a C-code with system calls

TL;DR

A project template for testing C-code with system calls see on github. It uses FFF for mocking and Catch2 as a testing framework. The solution is based on linker --wrap feature.

Intro

If you ever wrote a low-level library that uses system calls you know that it’s not easy to test such code. In this short post I want to share a “turn key” template with FFF and Catch2 testing frameworks that allows easy test such code.

The Problem

Let’s say we have a function that checks if we run on a multi or single-core system.

The Solution

We will use a wrap trick provided by a GCC linker (also available in LLVM’s gold linker). By specifying the linker option --wrap=get_nprocs_conf, we will get a chance to redefine get_nprocs_conf() as we want.

gcc main.c && ./a.out
gcc -Wl,--wrap=get_nprocs_conf main.c && ./a.out

Mocking And Testing With FFF and Catch2

Now let’s try to do the same, but using proper frameworks.

What’s next?

You can clone and compile my template. It includes both FFF and Catch2 as third_party dependencies (they both header-only).

git clone https://github.com/r7vme/testing-c-code-with-system-calls
./build_and_test.sh

Systems Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store