A testing micro framework for creating function test doubles

Overview

Fake Function Framework (fff)


Build Status Build status Gitter chat

A Fake Function Framework for C

fff is a micro-framework for creating fake C functions for tests. Because life is too short to spend time hand-writing fake functions for testing.

Hello Fake World!

Say you are testing an embedded user interface and you have a function that you want to create a fake for:

// UI.c
...
void DISPLAY_init();
...

Here's how you would define a fake function for this in your test suite:

// test.c(pp)
#include "fff.h"
DEFINE_FFF_GLOBALS;
FAKE_VOID_FUNC(DISPLAY_init);

And the unit test might look something like this:

TEST_F(GreeterTests, init_initialises_display)
{
    UI_init();
    ASSERT_EQ(DISPLAY_init_fake.call_count, 1);
}

So what has happened here? The first thing to note is that the framework is header only, all you need to do to use it is download fff.h and include it in your test suite.

The magic is in the FAKE_VOID_FUNC. This expands a macro that defines a function returning void which has zero arguments. It also defines a struct "function_name"_fake which contains all the information about the fake. For instance, DISPLAY_init_fake.call_countis incremented every time the faked function is called.

Under the hood it generates a struct that looks like this:

typedef struct DISPLAY_init_Fake {
    unsigned int call_count;
    unsigned int arg_history_len;
    unsigned int arg_histories_dropped;
    void(*custom_fake)();
} DISPLAY_init_Fake;
DISPLAY_init_Fake DISPLAY_init_fake;

Capturing Arguments

Ok, enough with the toy examples. What about faking functions with arguments?

// UI.c
...
void DISPLAY_output(char * message);
...

Here's how you would define a fake function for this in your test suite:

FAKE_VOID_FUNC(DISPLAY_output, char *);

And the unit test might look something like this:

TEST_F(UITests, write_line_outputs_lines_to_display)
{
    char msg[] = "helloworld";
    UI_write_line(msg);
    ASSERT_EQ(DISPLAY_output_fake.call_count, 1);
    ASSERT_EQ(strncmp(DISPLAY_output_fake.arg0_val, msg, 26), 0);
}

There is no more magic here, the FAKE_VOID_FUNC works as in the previous example. The number of arguments that the function takes is calculated, and the macro arguments following the function name defines the argument type (a char pointer in this example).

A variable is created for every argument in the form "function_name"fake.argN_val

Return Values

When you want to define a fake function that returns a value, you should use the FAKE_VALUE_FUNC macro. For instance:

// UI.c
...
unsigned int DISPLAY_get_line_capacity();
unsigned int DISPLAY_get_line_insert_index();
...

Here's how you would define fake functions for these in your test suite:

FAKE_VALUE_FUNC(unsigned int, DISPLAY_get_line_capacity);
FAKE_VALUE_FUNC(unsigned int, DISPLAY_get_line_insert_index);

And the unit test might look something like this:

TEST_F(UITests, when_empty_lines_write_line_doesnt_clear_screen)
{
    // given
    DISPLAY_get_line_insert_index_fake.return_val = 1;
    char msg[] = "helloworld";
    // when
    UI_write_line(msg);
    // then
    ASSERT_EQ(DISPLAY_clear_fake.call_count, 0);
}

Of course you can mix and match these macros to define a value function with arguments, for instance to fake:

double pow(double base, double exponent);

you would use a syntax like this:

FAKE_VALUE_FUNC(double, pow, double, double);

Resetting a Fake

Good tests are isolated tests, so it is important to reset the fakes for each unit test. All the fakes have a reset function to reset their arguments and call counts. It is good practice is to call the reset function for all the fakes in the setup function of your test suite.

void setup()
{
    // Register resets
    RESET_FAKE(DISPLAY_init);
    RESET_FAKE(DISPLAY_clear);
    RESET_FAKE(DISPLAY_output_message);
    RESET_FAKE(DISPLAY_get_line_capacity);
    RESET_FAKE(DISPLAY_get_line_insert_index);
}

You might want to define a macro to do this:

/* List of fakes used by this unit tester */
#define FFF_FAKES_LIST(FAKE)            \
  FAKE(DISPLAY_init)                    \
  FAKE(DISPLAY_clear)                   \
  FAKE(DISPLAY_output_message)          \
  FAKE(DISPLAY_get_line_capacity)       \
  FAKE(DISPLAY_get_line_insert_index)

void setup()
{
  /* Register resets */
  FFF_FAKES_LIST(RESET_FAKE);

  /* reset common FFF internal structures */
  FFF_RESET_HISTORY();
}

Call History

Say you want to test that a function calls functionA, then functionB, then functionA again, how would you do that? Well fff maintains a call history so that it is easy to assert these expectations.

Here's how it works:

FAKE_VOID_FUNC(voidfunc2, char, char);
FAKE_VALUE_FUNC(long, longfunc0);

TEST_F(FFFTestSuite, calls_in_correct_order)
{
    longfunc0();
    voidfunc2();
    longfunc0();

    ASSERT_EQ(fff.call_history[0], (void *)longfunc0);
    ASSERT_EQ(fff.call_history[1], (void *)voidfunc2);
    ASSERT_EQ(fff.call_history[2], (void *)longfunc0);
}

They are reset by calling FFF_RESET_HISTORY();

Default Argument History

The framework will by default store the arguments for the last ten calls made to a fake function.

TEST_F(FFFTestSuite, when_fake_func_called_then_arguments_captured_in_history)
{
    voidfunc2('g', 'h');
    voidfunc2('i', 'j');
    ASSERT_EQ('g', voidfunc2_fake.arg0_history[0]);
    ASSERT_EQ('h', voidfunc2_fake.arg1_history[0]);
    ASSERT_EQ('i', voidfunc2_fake.arg0_history[1]);
    ASSERT_EQ('j', voidfunc2_fake.arg1_history[1]);
}

There are two ways to find out if calls have been dropped. The first is to check the dropped histories counter:

TEST_F(FFFTestSuite, when_fake_func_called_max_times_plus_one_then_one_argument_history_dropped)
{
    int i;
    for(i = 0; i < 10; i++)
    {
        voidfunc2('1'+i, '2'+i);
    }
    voidfunc2('1', '2');
    ASSERT_EQ(1u, voidfunc2_fake.arg_histories_dropped);
}

The other is to check if the call count is greater than the history size:

ASSERT(voidfunc2_fake.arg_history_len < voidfunc2_fake.call_count);

The argument histories for a fake function are reset when the RESET_FAKE function is called

User Defined Argument History

If you wish to control how many calls to capture for argument history you can override the default by defining it before include the fff.h like this:

// Want to keep the argument history for 13 calls
#define FFF_ARG_HISTORY_LEN 13
// Want to keep the call sequence history for 17 function calls
#define FFF_CALL_HISTORY_LEN 17

#include "../fff.h"

Function Return Value Sequences

Often in testing we would like to test the behaviour of sequence of function call events. One way to do this with fff is to specify a sequence of return values with for the fake function. It is probably easier to describe with an example:

// faking "long longfunc();"
FAKE_VALUE_FUNC(long, longfunc0);

TEST_F(FFFTestSuite, return_value_sequences_exhausted)
{
    long myReturnVals[3] = { 3, 7, 9 };
    SET_RETURN_SEQ(longfunc0, myReturnVals, 3);
    ASSERT_EQ(myReturnVals[0], longfunc0());
    ASSERT_EQ(myReturnVals[1], longfunc0());
    ASSERT_EQ(myReturnVals[2], longfunc0());
    ASSERT_EQ(myReturnVals[2], longfunc0());
    ASSERT_EQ(myReturnVals[2], longfunc0());
}

By specifying a return value sequence using the SET_RETURN_SEQ macro, the fake will return the values given in the parameter array in sequence. When the end of the sequence is reached the fake will continue to return the last value in the sequence indefinitely.

Custom Return Value Delegate

You can specify your own function to provide the return value for the fake. This is done by setting the custom_fake member of the fake. Here's an example:

#define MEANING_OF_LIFE 42
long my_custom_value_fake(void)
{
    return MEANING_OF_LIFE;
}
TEST_F(FFFTestSuite, when_value_custom_fake_called_THEN_it_returns_custom_return_value)
{
    longfunc0_fake.custom_fake = my_custom_value_fake;
    long retval = longfunc0();
    ASSERT_EQ(MEANING_OF_LIFE, retval);
}

Custom Return Value Delegate Sequences

Say you have a function with an out parameter, and you want it to have a different behaviour on the first three calls, for example: set the value 'x' to the out parameter on the first call, the value 'y' to the out parameter on the second call, and the value 'z' to the out parameter on the third call. You can specify a sequence of custom functions to a non-variadic function using the SET_CUSTOM_FAKE_SEQ macro. Here's an example:

void voidfunc1outparam_custom_fake1(char *a)
{
    *a = 'x';
}

void voidfunc1outparam_custom_fake2(char *a)
{
    *a = 'y';
}

void voidfunc1outparam_custom_fake3(char *a)
{
    *a = 'z';
}

TEST_F(FFFTestSuite, custom_fake_sequence_not_exausthed)
{
    void (*custom_fakes[])(char *) = {voidfunc1outparam_custom_fake1,
                                      voidfunc1outparam_custom_fake2,
                                      voidfunc1outparam_custom_fake3};
    char a = 'a';

    SET_CUSTOM_FAKE_SEQ(voidfunc1outparam, custom_fakes, 3);

    voidfunc1outparam(&a);
    ASSERT_EQ('x', a);
    voidfunc1outparam(&a);
    ASSERT_EQ('y', a);
    voidfunc1outparam(&a);
    ASSERT_EQ('z', a);
}

The fake will call your custom functions in the order specified by the SET_CUSTOM_FAKE_SEQ macro. When the last custom fake is reached the fake will keep calling the last custom fake in the sequence. This macro works much like the SET_RETURN_SEQ macro.

Return Value History

Say you have two functions f1 and f2. f2 must be called to release some resource allocated by f1, but only in the cases where f1 returns zero. f1 could be pthread_mutex_trylock and f2 could be pthread_mutex_unlock. fff will save the history of returned values so this can be easily checked, even when you use a sequence of custom fakes. Here's a simple example:

TEST_F(FFFTestSuite, return_value_sequence_saved_in_history)
{
    long myReturnVals[3] = { 3, 7, 9 };
    SET_RETURN_SEQ(longfunc0, myReturnVals, 3);
    longfunc0();
    longfunc0();
    longfunc0();
    ASSERT_EQ(myReturnVals[0], longfunc0_fake.return_val_history[0]);
    ASSERT_EQ(myReturnVals[1], longfunc0_fake.return_val_history[1]);
    ASSERT_EQ(myReturnVals[2], longfunc0_fake.return_val_history[2]);
}

You access the returned values in the return_val_history field.

Variadic Functions

You can fake variadic functions using the macros FAKE_VALUE_FUNC_VARARG and FAKE_VOID_FUNC_VARARG. For instance:

FAKE_VALUE_FUNC_VARARG(int, fprintf, FILE *, const char*, ...);

In order to access the variadic parameters from a custom fake function, declare a va_list parameter. For instance, a custom fake for fprintf() could call the real fprintf() like this:

int fprintf_custom(FILE *stream, const char *format, va_list ap) {
  if (fprintf0_fake.return_val < 0) // should we fail?
    return fprintf0_fake.return_val;
  return vfprintf(stream, format, ap);
}

Just like return value delegates, you can also specify sequences for variadic functions using SET_CUSTOM_FAKE_SEQ. See the test files for examples.

Common Questions

How do I specify calling conventions for my fake functions?

fff has a limited capability for enabling specification of Microsoft's Visual C/C++ calling conventions, but this support must be enabled when generating fff's header file fff.h.

ruby fakegen.rb --with-calling-conventions > fff.h

By enabling this support, all of fff's fake function scaffolding will necessitate the specification of a calling convention, e.g. __cdecl for each VALUE or VOID fake.

Here are some basic examples: take note that the placement of the calling convention being specified is different depending on whether the fake is a VOID or VALUE function.

FAKE_VOID_FUNC(__cdecl, voidfunc1, int);
FAKE_VALUE_FUNC(long, __cdecl, longfunc0);

How do I fake a function that returns a value by reference?

The basic mechanism that fff provides you in this case is the custom_fake field described in the Custom Return Value Delegate example above.

You need to create a custom function (e.g. getTime_custom_fake) to produce the output optionally by use of a helper variable (e.g. getTime_custom_now) to retrieve that output from. Then some creativity to tie it all together. The most important part (IMHO) is to keep your test case readable and maintainable.

In case your project uses a C compiler that supports nested functions (e.g. GCC) you can even combine all this in a single unit test function so you can easily oversee all details of the test.

/* The time structure */
typedef struct {
   int hour, min;
} Time;

/* Our fake function */
FAKE_VOID_FUNC(getTime, Time*);

/* A test using the getTime fake function */
TEST_F(FFFTestSuite, when_value_custom_fake_called_THEN_it_returns_custom_output)
{
    Time t;
    Time getTime_custom_now;
    void getTime_custom_fake(Time *now) {
        *now = getTime_custom_now;
    }
    getTime_fake.custom_fake = getTime_custom_fake;

    /* given a specific time */
    getTime_custom_now.hour = 13;
    getTime_custom_now.min  = 05;

    /* when getTime is called */
    getTime(&t);

    /* then the specific time must be produced */
    ASSERT_EQ(t.hour, 13);
    ASSERT_EQ(t.min,  05);
}

How do I fake a function with a function pointer parameter?

Using fff to stub functions that have function pointer parameter can cause problems when trying to stub them. Presented here is an example how to deal with this situation.

If you need to stub a function that has a function pointer parameter, e.g. something like:

/* timer.h */
typedef int timer_handle;
extern int timer_start(timer_handle handle, long delay, void (*cb_function) (int arg), int arg);

Then creating a fake like below will horribly fail when trying to compile because the fff macro will internally expand into an illegal variable int (*)(int) arg2_val.

/* The fake, attempt one */
FAKE_VALUE_FUNC(int,
                timer_start,
                timer_handle,
                long,
                void (*) (int argument),
                int);

The solution to this problem is to create a bridging type that needs only to be visible in the unit tester. The fake will use that intermediate type. This way the compiler will not complain because the types match.

/* Additional type needed to be able to use callback in fff */
typedef void (*timer_cb) (int argument);

/* The fake, attempt two */
FAKE_VALUE_FUNC(int,
                timer_start,
                timer_handle,
                long,
                timer_cb,
                int);

Here are some ideas how to create a test case with callbacks.

/* Unit test */
TEST_F(FFFTestSuite, test_fake_with_function_pointer)
{
    int cb_timeout_called = 0;
    int result = 0;

    void cb_timeout(int argument)
    {
      cb_timeout_called++;
    }

    int timer_start_custom_fake(timer_handle handle,
                          long delay,
                          void (*cb_function) (int arg),
                          int arg)
    {
      if (cb_function) cb_function(arg);
      return timer_start_fake.return_val;
    }

    /* given the custom fake for timer_start */
    timer_start_fake.return_val = 33;
    timer_start_fake.custom_fake = timer_start_custom_fake;

    /* when timer_start is called
     * (actually you would call your own function-under-test
     *  that would then call the fake function)
     */
    result = timer_start(10, 100, cb_timeout, 55);

    /* then the timer_start fake must have been called correctly */
    ASSERT_EQ(result, 33);
    ASSERT_EQ(timer_start_fake.call_count, 1);
    ASSERT_EQ(timer_start_fake.arg0_val,   10);
    ASSERT_EQ(timer_start_fake.arg1_val,   100);
    ASSERT_EQ(timer_start_fake.arg2_val,   cb_timeout); /* callback provided by unit tester */
    ASSERT_EQ(timer_start_fake.arg3_val,   55);

    /* and ofcourse our custom fake correctly calls the registered callback */
    ASSERT_EQ(cb_timeout_called, 1);
}

How do I reuse a fake across multiple test-suites?

fff functions like FAKE_VALUE_FUNC will perform both the declaration AND the definition of the fake function and the corresponding data structs. This cannot be placed in a header, since it will lead to multiple definitions of the fake functions.

The solution is to separate declaration and definition of the fakes, and place the declaration into a public header file, and the definition into a private source file.

Here is an example of how it could be done:

/* Public header file */
#include "fff.h"

DECLARE_FAKE_VALUE_FUNC(int, value_function, int, int);
DECLARE_FAKE_VOID_FUNC(void_function, int, int);
DECLARE_FAKE_VALUE_FUNC_VARARG(int, value_function_vargs, const char *, int, ...);
DECLARE_FAKE_VOID_FUNC_VARARG(void_function_vargs, const char *, int, ...);


/* Private source file file */
#include "public_header.h"

DEFINE_FAKE_VALUE_FUNC(int, value_function, int, int);
DEFINE_FAKE_VOID_FUNC(void_function, int, int);
DEFINE_FAKE_VALUE_FUNC_VARARG(int, value_function_vargs, const char *, int, ...);
DEFINE_FAKE_VOID_FUNC_VARARG(void_function_vargs, const char *, int, ...);

Specifying GCC Function Attributes

You can specify GCC function attributes for your fakes using the FFF_GCC_FUNCTION_ATTRIBUTES directive.

Weak Functions

One usful attribute is the weak attribute that marks a function such that it can be overridden by a non-weak variant at link time. Using weak functions in combination with fff can help simplify your testing approach.

For example:

  • Define a library of fake functions, e.g. libfake.a.
  • Link a binary (you might have many) that defines a subset of real variants of the fake functions to the aforementioned fake library.
  • This has the benefit of allowing a binary to selectively use a subset of the required fake functions while testing the real variants without the need for many different make targets.

You can mark all fakes with the weak attribute like so:

#define FFF_GCC_FUNCTION_ATTRIBUTES __attribute__((weak))
#include "fff.h"

See the example project that demonstrates the above approach: ./examples/weak_linking.

Find Out More

Look under the examples directory for full length examples in both C and C++. There is also a test suite for the framework under the test directory.


Benefits

So whats the point?

  • To make it easy to create fake functions for testing C code.
  • It is simple - just include a header file and you are good to go.
  • To work in both C and C++ test environments

Under the Hood

  • The fff.h header file is generated by a ruby script
  • There are tests under ./test
  • There is an example for testing an embedded UI and a hardware driver under ./examples
  • There is an example of weak_linking under ./examples

Cheat Sheet

Macro Description Example
FAKE_VOID_FUNC(fn [,arg_types*]); Define a fake function named fn returning void with n arguments FAKE_VOID_FUNC(DISPLAY_output_message, const char*);
FAKE_VALUE_FUNC(return_type, fn [,arg_types*]); Define a fake function returning a value with type return_type taking n arguments FAKE_VALUE_FUNC(int, DISPLAY_get_line_insert_index);
FAKE_VOID_FUNC_VARARG(fn [,arg_types*], ...); Define a fake variadic function returning void with type return_type taking n arguments and n variadic arguments FAKE_VOID_FUNC_VARARG(fn, const char*, ...)
FAKE_VALUE_FUNC_VARARG(return_type, fn [,arg_types*], ...); Define a fake variadic function returning a value with type return_type taking n arguments and n variadic arguments FAKE_VALUE_FUNC_VARARG(int, fprintf, FILE*, const char*, ...)
RESET_FAKE(fn); Reset the state of fake function called fn RESET_FAKE(DISPLAY_init);
Comments
  • Update generator & fff.h to support custom function signatures

    Update generator & fff.h to support custom function signatures

    Update generator & fff.h to support custom function signatures

    Add the ability of the includer to override the function signature from the C standard function pointer to any other format of their choosing. This particularly is useful if developers want to use std::function (or some variant of it) which will allow capture groups of C++ lambdas.

    Fixes #110

    opened by yperess 17
  • Multiple definition error

    Multiple definition error

    This is what I have:

    #include "lib/fff.h"
    DEFINE_FFF_GLOBALS;
    FAKE_VALUE_FUNC(bool_t, probe_is_ok, adc_probe_t);
    /* List of fakes used by this unit tester */
    #define FFF_FAKES_LIST(FAKE)            \
      FAKE(probe_is_ok)                    \
    

    And this is what I get when I build

    ../app/middleware/libmiddleware.a(probe.c.o): In function `probe_is_ok':
    ~/AppProject/app/middleware/probe.c:19: multiple definition of `probe_is_ok'
    CMakeFiles/unit_tests.dir/AppTest.cpp.o:~/AppProject/test/AppTestTest.cpp:16: first defined here
    
    opened by anat0lius 9
  • old version fff to latest transition trouble due to extern

    old version fff to latest transition trouble due to extern "C"

    I work at Cisco and we took a TDD class from James Grenning a while back and he introduced us to FFF. That was many years ago and we've been using an old version. We need to move to the latest because of our need for the ____VARARG fakes. However, in looking at the changes, there has been a lot of advancement since we pulled our copy - most notably there is a lot of changes regarding extern "C" declarations throughout dependent on #ifdef __cplusplus.

    In particular, this is causing most of my existing unit tests to fail - probably because we took matters into our hands to address the placement of extern "C" - so as example, I have a unit under test in a C file that calls getpid. The test program is a CPP file and that is where FFF is included and getpid is faked.

    On the call to FAKE_VALUE_FUNC(pid_t, getpid) it fails because of inconsistency:

    In function 'pid_t getpid()': declaration of 'pid_t getpid()' with C language linkage
    conflicts with previous declaration 'pid_t getpid()' due to different exception specifications
    

    So my issue is - can you summarize what has changed in regard to extern C and how to handle that since the various upgrades through the years?

    Should I be using extern C at all in my CPP test programs?

    TODDL Cisco Systems.

    Support 
    opened by tlawork 7
  • Unable to mock static inline functions

    Unable to mock static inline functions

    Hi there, I am trying to mock a couple of functions from the linux/i2c-dev.h header, which declaration is as follows:

    static inline __s32 i2c_smbus_write_word_data(int file, __u8 command, __u16 value) { ... } static inline __s32 i2c_smbus_write_word_data(int file, __u8 command, __u8 value) { ... }

    Unfortunately, FFF doesn't seem to be taking my mocks as valid mocks for these functions calls. I am not getting de return sequence according to what I've set. I'm always getting the same value (which I assume it's because the real functions are being called instead of the mock ones).

    My mock declarations are the following: FAKE_VALUE_FUNC( __s32, i2c_smbus_write_word_data, int, __u8, __u16); FAKE_VALUE_FUNC( __s32, i2c_smbus_write_byte_data, int, __u8, __u8);

    Does it have something to do with the way the functions are declared?

    Thank you! Regards,

    opened by jverce 7
  • Migrate to standard github workflows

    Migrate to standard github workflows

    Update the CI for FFF to use github workflows which don't depend on MS VC. The workflow added will verify the pull requests sent to master buy running 'buildandtest' which mirrors the developer workflow.

    Signed-off-by: Yuval Peress [email protected]

    opened by yperess 5
  • GCC warning for variadic with no arguments when compiling ISO c11 strict

    GCC warning for variadic with no arguments when compiling ISO c11 strict

    I'm mocking several functions with declarations similar to this:

    void SCHEMAinitialize();

    using: FAKE_VOID_FUNC(SCHEMAinitialize)

    currently results in a compiler warning:

    /home/chorler/projects/src/stepcode/src/express/test/test_express.c:56:32: warning: ISO C99 requires at least one argument for the "..." in a variadic macro
     FAKE_VOID_FUNC(SCHEMAinitialize)
                                    ^
    

    current workaround: FAKE_VOID_FUNC0(SCHEMAinitalize)

    as the FAKE_VOID_FUNC is declared as #define FAKE_VOID_FUNC(...) EXPAND(FUNC_VOID_(PP_NARG_MINUS1(__VA_ARGS__), __VA_ARGS__))

    I guess the preprocessor warning applies to a macro definition deeper in fff.h, possibly an unintended consequence of the EXPAND macro?

    Support Limitation 
    opened by cshorler 5
  • Cannot compile in Visual Studio 2015

    Cannot compile in Visual Studio 2015

    I'm trying to use FFF from within Visual Studio 2015 and VC++, and the example I tried (attached) does not want to compile. Here's the test file:

    
    extern "C"
    {
    #include "driver.h"
    #include "registers.h"
    }
    #include <stdint.h>
    #include "CppUnitTest.h"
    #include "fff.h"
    
    DEFINE_FFF_GLOBALS;
    
    FAKE_VOID_FUNC(IO_MEM_WR8, uint32_t, uint8_t);
    FAKE_VALUE_FUNC(uint8_t, IO_MEM_RD8, uint32_t);
    
    using namespace Microsoft::VisualStudio::CppUnitTestFramework;
    
    namespace FFFTestProject
    {		
    	TEST_CLASS(UnitTest1)
    	{
    	public:
        TEST_METHOD_INITIALIZE(Init)
        {
          /*RESET_FAKE(IO_MEM_WR8);
          RESET_FAKE(IO_MEM_RD8);
          FFF_RESET_HISTORY();*/
        }
    		
    		TEST_METHOD(TestMethod1)
    		{
    			// TODO: Your test code here
    		}
    
    	};
    }`
    
    

    The FAKE_VOID_FUNC and FAKE_VALUE_FUNC macros are generating the following warning.

    Warning C4003 not enough actual parameters for macro 'PP_ARG_MINUS1_N' FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12

    Trying to compile generates the following errors, all stemming from the FAKE_VOID_FUNC and FAKE_VALUE_FUNC macros.

    Error C2065 'IO_MEM_WR8': undeclared identifier FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C2065 'IO_MEM_WR8': undeclared identifier FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C2275 'uint32_t': illegal use of this type as an expression FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C2275 'uint32_t': illegal use of this type as an expression FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C2275 'uint8_t': illegal use of this type as an expression FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C2275 'uint8_t': illegal use of this type as an expression FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C2440 'initializing': cannot convert from 'initializer list' to 'int' FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12 Error C2440 'initializing': cannot convert from 'initializer list' to 'int' FFFTestProject c:\temp\projects\ffftestproject\ffftestproject\unittest1.cpp 12

    FFFTestProject.zip

    opened by CurtisHx 5
  • Add documentation and tests for VARARG fakes

    Add documentation and tests for VARARG fakes

    FFF also supports faking VARARG functions, e.g. void voidfunc3var(const char *fmt, int argc, ...); could be faked with FAKE_VOID_FUNC_VARARG(voidfunc3var, char *, int, ...);

    But how to use this is not described in the readme. Additionally the unit tests for VARARGs are not sufficient. There are no assertions. I think there should be at least be a test for argument capturing. Also the custom_fake for VARARGs should be covered by unit tests.

    opened by usr42 5
  • Question that might need to be addressed in the wiki.

    Question that might need to be addressed in the wiki.

    When using a fake void function such as

    FAKE_VOID_FUNC(getTime, Time*);

    where a value is "returned" via reference how would fff handle this?

    Sorry if this is not the appropriate place to ask.

    opened by gsrunion 5
  • Adding a section explaining how to fake variadic functions

    Adding a section explaining how to fake variadic functions

    This commit adds a new section to the README explaning how to fake variadic functions and how to access variadic parameters from a custom fake function.

    opened by rubiot 4
  • (Feature request) Change call_history type to a function pointer

    (Feature request) Change call_history type to a function pointer

    Could fff be changed so that instead of fff_globals_t.call_history being an array of void pointers it is an array of function pointers? The reason for asking is that I am using fff in an embedded project which uses IAR for msp430, although I think you'd come across this with other compilers/architectures too. The particular processor architecture I'm using can address 20 bits but the data pointer size varies (16/16 or 32 bits) with the model selected (Small/Medium or Large respectively) in the project options whereas the function pointer size is always 32 bits. The function pointers in the call history get truncated in Small/Medium models because void * is treated as a data pointer and therefore its size changes with the model.

    Changing from void *call_history[FFF_CALL_HISTORY_LEN]; to something like:

    typedef void (*fft_function_t)(void);
    
    typedef struct { 
        fff_function_t call_history[FFF_CALL_HISTORY_LEN];
    

    would allow this to work correctly for this scenario and maintain compliance with C99 (section 6.3.2.3, paragraph 8 - I assume also other versions of the standard but haven't checked). The user would then cast their mock functions to (fff_function_t) when comparing to the call history elements.

    Also the definition of REGISTER_CALL(function) would have to change to e.g.

    #define REGISTER_CALL(function) \
       if(fff.call_history_idx < FFF_CALL_HISTORY_LEN) \
           fff.call_history[fff.call_history_idx++] = (fff_function_t)function;
    
    opened by dmcminniwc 4
  • fake.callcount is always 0 when reuse a fake across multiple test-suites

    fake.callcount is always 0 when reuse a fake across multiple test-suites

    Describe the bug A clear and concise description of what the bug is. When reuse a fake across multiple test-suites, Functions with parameters faked as the instruction described, but the callcount is always 0, however the functions without parameters callcount is normal. To Reproduce Steps to reproduce the behavior: 1.Fake a function with parameters as instruction described, with DECLARE_FAKE_VOID_FUNC in a public .h file; 2. use DEFINE_FAKE_VOID_FUNC in a private .c file 3. Reference faked function in a Google Test test suit TEST_F; 4. When I try to use the FUN_fake.callcount, it is always 0; 5. but if i fake the function directly in the test source file, the callcount is OK.

    Expected behavior A clear and concise description of what you expected to happen.

    Screenshots image

    Compiler, toolset, platform (please complete the following information): gcc.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0 vscode V1.72

    opened by Darwin-Li-001 2
  • Linking issue in the example project

    Linking issue in the example project

    Hello people,

    I've tried expanding the example project to play a bit with it, but i am getting a linking error, which i am not able to solve.

    What have i added?

    In the hardware_abstraction.h I've added the function declaration with this signature: uint8_t IO_READ_CHARS(uint8_t* chars_array, uint8_t number_of_chars);

    In driver.c I've added following function:

    uint8_t testonia() {
        uint8_t buffer[100] = {0};
        uint8_t charNum = 0;
        uint8_t sumReturn  = HARDWARE_REV_A;
    
        sumReturn = IO_READ_CHARS(buffer, HARDWARE_REV_A);
    
        return buffer[3];
    }
    

    In driver.test.fff.cpp added the fake value func like so: FAKE_VALUE_FUNC(uint8_t, IO_READ_CHARS, uint8_t*, uint8_t);

    declared a custom fake function:

    uint8_t cust_fake(uint8_t* chars, uint8_t number) {
        chars[0] = 1u;
        chars[1] = 2u;
        chars[2] = 5u;
        chars[3] = 100u;
    
        return 3u;
    }
    

    And my test is in the following listing:

    TEST_F(DriverTestFFF, Some_fake_test) {
        uint8_t ret = 0;
        IO_READ_CHARS_fake.custom_fake = cust_fake;
    
        IO_READ_CHARS_fake.return_val = 1;
    
        ret = testonia();
    
        ASSERT_EQ(ret, 100u);
    }
    

    The error I get on linking is that there is an undefined reference to IO_READ_CHARS.

    FAILED: examples/driver_testing/driver_test 
    : && /usr/bin/c++   examples/driver_testing/CMakeFiles/driver_test.dir/src/driver.c.o examples/driver_testing/CMakeFiles/driver_test.dir/src/driver.test.cpp.o -o examples/driver_testing/driver_test  gtest/libgtest.a  -lpthread  -static-libstdc++ && :
    /usr/bin/ld: examples/driver_testing/CMakeFiles/driver_test.dir/src/driver.c.o: in function `testonia':
    driver.c:(.text+0xcf): undefined reference to `IO_READ_CHARS'
    

    Can somebody please tell me what did i do wrong?

    opened by ivankvolik 1
  • Adding a preamble to mocked function name

    Adding a preamble to mocked function name

    The change in this patch modifies fff macro generation script to support a CLI option --preamble that can be used to set a preamble for generated mock function names.

    On some embedded systems if we want to perform testing with HW in the loop, there are system functions or driver functions that cannot be mocked safely. For example the SW running on a micro-controller may need to maintain communication with another subsystem, replacing the functions that do this with mocks will put the system in a bad state.

    To be able to mock such functions and keep the system in a good state we prepend a preamble to the mock function name and inside the mock function do intrumentation and then call the real function to keep the system in a good state. We can leverage the 'custom_fake' field created by fff to call the real function.

    For example, we can name the mock of function XYZ() as __wrap_XYZ() and use the GNU linker option -Wl,--wrap XYZ to re-route all references to XYZ() to __wrap_XYZ() (see https://ftp.gnu.org/old-gnu/Manuals/ld-2.9.1/html_node/ld_3.html). Now, inside __wrap_XYZ() we can invoke XYZ() in addition to instrumentation. We can leverage the 'custom_fake' field created by fff to call the real version of XYZ(), this will be named as __real_XYZ(). Note, this is just an example the same can be acheived by custom tooling and not using GNU linkers --wrap flag.

    Signed-off-by: Ramzi El-khater [email protected]

    Thank you for your contribution.

    Before submitting this PR, please make sure:

    • [x] Your code builds clean without any errors or warnings
    • [x] You are not breaking consistency
    • [x] You have added unit tests
    • [x] All tests and other checks pass
    opened by ramzie80 5
  • How to install and to use?

    How to install and to use?

    Hello,

    the Readme does not give any clue on how to add this to a project... Is the fff.h already sufficient? What is the purpose of the gtest folder? Does it replace the normal gtest library? What is the ruby script for? Do I need to run it once when I add the files to my project or every time I add some tests?

    opened by SevHub 2
  • #pragma pack(1) breaks Function Return Value Sequences

    #pragma pack(1) breaks Function Return Value Sequences

    Describe the bug I'm using Ceedling with Unity and FFF to unit test some embedded code. To make some things work I need to specify #pragma pack(1) for some structures. I was trying to mock a sequence of return values for a function and the results were not as expected. Some hours later I have trimmed it down to a minimal reproduction case:

    To Reproduce make sure you have Ceedling and FFF set up etc... This was on Windows 10 with MinGW Unzip the TestFFFseq.zip, start a command prompt in the TestFFFseq folder and run ceedling test:all

    the result will be

    FAILED TEST SUMMARY

    [test_FFFseq.c] Test: test_One At line (28): "Expected 1 Was 0"

    OVERALL TEST SUMMARY

    TESTED: 1 PASSED: 0 FAILED: 1 IGNORED: 0

    Expected behavior

    OVERALL TEST SUMMARY

    TESTED: 1 PASSED: 1 FAILED: 0 IGNORED: 0

    Compiler, toolset, platform (please complete the following information):

    • Windows 10 Home
    • MinGW, Ceedling 0.31.1, latest FFF (Feb 2022)

    If one comments out the #pragma pack(1) on line 3 of test_FFFseq.c then the test passes.

    I tried but couldn't reproduce without Ceedling generating the fake.

    This can be avoided by using #pragma pack(push, 1) and #pragma pack(pop) where one needs it in one's code

    TestFFFseq.zip

    opened by alexsconway 1
Releases(v1.1)
Owner
Mike Long
Mike Long
A C++ micro-benchmarking framework

Nonius What is nonius? Nonius is an open-source framework for benchmarking small snippets of C++ code. It is very heavily inspired by Criterion, a sim

Nonius 338 Nov 28, 2022
A unit testing framework for C

Check Table of Contents About Installing Linking Packaging About Check is a unit testing framework for C. It features a simple interface for defining

null 923 Nov 27, 2022
The fastest feature-rich C++11/14/17/20 single-header testing framework

master branch Windows All dev branch Windows All doctest is a new C++ testing framework but is by far the fastest both in compile times (by orders of

Viktor Kirilov 4.4k Nov 23, 2022
CppUTest unit testing and mocking framework for C/C++

CppUTest CppUTest unit testing and mocking framework for C/C++ More information on the project page Slack channel: Join if link not expired Getting St

CppUTest 1.1k Nov 26, 2022
Googletest - Google Testing and Mocking Framework

GoogleTest OSS Builds Status Announcements Release 1.10.x Release 1.10.x is now available. Coming Soon Post 1.10.x googletest will follow Abseil Live

Google 28.5k Nov 25, 2022
Minimal unit testing framework for C

MinUnit Minunit is a minimal unit testing framework for C/C++ self-contained in a single header file. It provides a way to define and configure test s

David Siñuela Pastor 451 Nov 18, 2022
A lightweight unit testing framework for C++

Maintenance of UnitTest++, recently sporadic, is officially on hiatus until 26 November 2020. Subscribe to https://github.com/unittest-cpp/unittest-cp

UnitTest++ 509 Nov 24, 2022
🧪 single header unit testing framework for C and C++

?? utest.h A simple one header solution to unit testing for C/C++. Usage Just #include "utest.h" in your code! The current supported platforms are Lin

Neil Henning 544 Dec 1, 2022
A modern, C++-native, header-only, test framework for unit-tests, TDD and BDD - using C++11, C++14, C++17 and later (or C++03 on the Catch1.x branch)

Catch2 v3 is being developed! You are on the devel branch, where the next major version, v3, of Catch2 is being developed. As it is a significant rewo

Catch Org 15.9k Nov 25, 2022
A modern, C++-native, header-only, test framework for unit-tests, TDD and BDD - using C++11, C++14, C++17 and later (or C++03 on the Catch1.x branch)

Catch2 v3 is being developed! You are on the devel branch, where the next major version, v3, of Catch2 is being developed. As it is a significant rewo

Catch Org 15.9k Nov 24, 2022
test framework

Photesthesis This is a small, experimental parameterized-testing tool. It is intended to be used in concert with another unit-testing framework (eg. C

Graydon Hoare 11 Jun 2, 2021
Simple Unit Testing for C

Unity Test Copyright (c) 2007 - 2021 Unity Project by Mike Karlesky, Mark VanderVoord, and Greg Williams Welcome to the Unity Test Project, one of the

Throw The Switch 2.8k Nov 24, 2022
Implementations of FizzBuzz test, with different optimisations

fizzbuzz Optimisation of classic FizzBuzz test. supernaive The least efficient implementation, with 3 ifs and two printfs per number. It is so ineffic

Ilya Caramishev 123 Oct 25, 2022
DotX64Dbg aims to provide a seamless way to write and test plugins for X64Dbg using .Net 5.0 and C#.

DotX64Dbg (EARLY ALPHA) Plugins and Scripting with C# for x64Dbg. Create Plugins for X64Dbg with ease DotX64Dbg aims to provide a seamless way to writ

ζeh Matt 7 Oct 16, 2022
C++ Benchmark Authoring Library/Framework

Celero C++ Benchmarking Library Copyright 2017-2019 John Farrier Apache 2.0 License Community Support A Special Thanks to the following corporations f

John Farrier 723 Nov 24, 2022
A simple framework for compile-time benchmarks

Metabench A simple framework for compile-time microbenchmarks Overview Metabench is a single, self-contained CMake module making it easy to create com

Louis Dionne 162 Oct 23, 2022
UT: C++20 μ(micro)/Unit Testing Framework

"If you liked it then you "should have put a"_test on it", Beyonce rule [Boost::ext].UT / μt | Motivation | Quick Start | Overview | Tutorial | Exampl

boost::ext 929 Nov 26, 2022
UT: C++20 μ(micro)/Unit Testing Framework

"If you liked it then you "should have put a"_test on it", Beyonce rule UT / μt | Motivation | Quick Start | Overview | Tutorial | Examples | User Gui

boost::ext 928 Nov 22, 2022
Tau - A Micro (1k lines of code) Unit Test Framework for C/C++

Tau τ A Micro Unit Testing Framework for >C11/C++11 projects, with the promise of always being tiny - about 1k lines of code. This framework is a much

Jason Dsouza 110 Nov 5, 2022
C++ Unit Testing Easier: A Header-only C++ unit testing framework

CUTE C++ Unit Testing Easier: A Header-only C++ unit testing framework usually available as part of the Cevelop C++ IDE (http://cevelop.com) Dependenc

Peter Sommerlad 35 Aug 31, 2022