Package: autofff
AutoFFFAuto-generateFFFfake definitions for C API header files.Incorporate this script into your normal build environment (likemake) and automatically generate test-headers with faked function definitions ready-to-use withFFF's owngtestor some other unit-testing-framework.The Idea Behind FakingEspecially in the embedded world, compiling your (unit-)tests against the actual target platform isn't feasible, as the architecture you're executing the test on and your target platform you're writing the code for are generally not the same.This is where faking a specific platform API might help you. Instead of calling the actual target platform API, you link your code-under-test (CuT) against a faked version of said API. Now, whenever your CuT tries to access the platform API,it is instead calling the fake-implementation which you can easily configure in your test-cases' setup phase.FFF(fake-functions-framework) is a framework designed to easily create faked definitions of your API function-declarations, allowing you to configure return values and inspect call and argument histories that were called during the tests' runtime. Check out their awesome project onGithub. AutoFFF utilizes the ability to easily create fake definitions provided by FFF, but could also be adapted to other mocking frameworks.The problem with faking an API in embedded C is usually the infeasibility of using dynamic linking and C's lack of techniques like 'reflection' to manipulate your CuT during runtime. This makes the process of writing fake definitions a tedious, labor intensive and error prone matter.IntroducingAutoFFF, an attempt at automating the process of writing so called test-headers (headers which include the faked definitions).Two Philosophies of FakingWhen writing fakes you will notice that there are two approaches of laying out your fake.Banningthe original API headerThis strategybansthe original header by defining the API headers include guard, making it impossible to include the original function, variable and type declarations. This gives you ultimate freedom in the test-header, but also means that you will have to manually declare any types, functions and variables the API-user might expect. It also allows you to control the include hierarchy and maybe skip some headers which aren't compatible with your test-runner's architecture. In general this approach usually involves a lot of copy&pasting and is therefore more prone to"code rot". You also need to deep-dive any header you want to fake, understand its structure and inspect all the declarations and defines very closely. Not the optimal strategy if you're looking for an easy-to-maintain way of managing test-headers.Wrappingthe original API headerConversely to the banning method, thewrappingstrategy directly includes the original API header, and thereby imports any type, variable and function declarations. Also the include hierarchy is taken over from the original. The only thing to add into the test-header are the fake definitions. This method evidently grants you less freedom in the test-header, but is usually much shorter and slightly less prone to"rot"over time.It should become obvious which method is better suited for automation.AutoFFFfollows thewrappingapproach of writing test-headers, which for most cases should be good enough.Finally it must be stated, that these two philosophies seldomly mix well!InstallationUsepipto download and installAutoFFFfrom thePyPirepositories:py-3.6-mpipinstallautofffOr install from source:py-3.6-mpipinstall.Note that you'll most likely require the pycparserfake_libc_includes header collection for AutoFFF to work. Thepippackage doesnotship with this external code. You may download the faked libc headers frompycparsers Github, or check out the project as a submodule (when installing from source rungit submodule update --init).UsageAs a Modulepy-3.6-mautofff\./examples/driver.h\-O./output/driver_th.h\-I./examples\-F./dependencies/pycparser/utils/fake_libc_includeUsing the provided MakefileTo run build and run the tests, simply execute:makerun_testsYou can also let the makefile do the installation ofAutoFFFfor you.makeinstall_autofffRunning the 'Generate Fakes' Examplemake-fexamples/generate-via-makefile/generate_fakes.mkCRAWL_PATHS=examplesAs a Python Packageimportautofffimportos.pathtargetHeader=input("Enter the path of the header you would like to scan: ")outputHeader=input("Enter the path of the target header file which shall be generated: ")fakes='./autofff/dependencies/pycparser/utils/fake_libc_include'scnr=autofff.GCCScanner(targetHeader,fakes)# Create GCC code scannerresult=scnr.scan()# Scan for function declarations and definitionsgen=autofff.SimpleFakeGenerator(os.path.splitext(os.path.basename(outputHeader))[0],targetHeader)# Create new generator with name output-header and path to target-headerifnotos.path.exists(os.path.dirname(outputHeader)):dirname=os.path.dirname(outputHeader)os.makedirs(dirname)withopen(outputHeader,"w")asfs:gen.generate(result,fs)# Generate fff-fakes from scanner-resultHow Fakes Are GeneratedThe format of the generated test-header obviously depends on the specifics of theFakeGeneratorbeing used.TheBareFakeGeneratorwill only generate theFAKE_VALUE_- andFAKE_VOID_FUNCmacros without any decorations, like include guards or header includes. Use this generator if you want to add your own (shell-based-)processing on top.TheSimpleFakeGeneratorwill generate a "minimum viable test header", meaning the result should be compilable without too much effort.In-Header Defined FunctionsIn some API headers functions may be defined within the header. This will cause issues when trying to fake this function, because by including the header the function definition is copied into each translation unit. If we try to apply a fake definition the usual way, we will end up with a"redefinition of functionx"error.AutoFFFimplements a workaround to avoid this redefinition error and allowing to fake the original function. This workaround simply consists of some defines which will re-route any call to the original in-header definition to our faked one. For this to work it is required that the test-header is included (and thereby pre-processed)beforeany function call to the function under consideration is instructed, i.e. the test-header must be includedbeforethe CuT. Any function call that is processed before the workaround is being pre-processed will leave this function call targeted towards the original in-header definition.In practice the workaround looks like this:/* api.h */#ifndef API_HEADER_H_#define API_HEADER_H_constchar*foo(void){return"Definitions inside headers are great!";}#endif/* api_th.h */#ifndef TEST_HEADER_H_#define TEST_HEADER_H_#include"fff.h"#include"api.h"/* Re-route any call to 'foo' to 'foo_fff' (our fake definition). */#define foo foo_fff/* By re-routing the '_fake' and '_reset' type and function the workaround becomes invisible in the test-case. */#define foo_fake Foo_fff_fake#define foo_reset Foo_fff_reset/* Create the fake definition using the now re-routed 'foo'-symbol. */FAKE_VALUE_FUNC(constchar*,foo);#endif/* cut.c - code-under-test */#include"api.h"#include<stdio.h>constchar*bar(void){constchar*str=foo();returnstr;}/* test.c */#include"fff.h"#include"api_th.h"/* fakes + workaround */#include"cut.c"setup(void){RESET_FAKE(foo);}TEST_F(foo,ReturnBar_Success){constchar*expected_retval="Definitions inside headers make faking difficult!";foo_fake.return_val=expected_retvalconstchar*str=bar();ASSERT_STREQ(expected_retval,str);}Working withobscureinclude policiesSome libraries like FreeRTOS or CMSIS require you to include their API headers in a very specific way. AutoFFF can't guess these policies (yet! ;P) from source-code alone. For cases where the include policy of your vendor lib does not allow each header to be preprocessed individually check out the-D(--define) and-i(--includefile) command line options. They may allow you to fix/trick the broken include chain.
As an example, for FreeRTOS'list.hrun:py-3.6-mautofff[...]/include/list.h-o[...]-i[...]/include/FreeRTOS.h<<<injectFreeRTOS.hbeforepreprocessinglist.h-F[...]