### CppUTest Setup and Teardown Example Source: https://cpputest.github.io/manual Demonstrates how to implement setup and teardown methods within a CppUTest test group. Setup is executed before each test, and teardown after each test in the group. ```cpp TEST_GROUP(FooTestGroup) { void setup() { // Init stuff } void teardown() { // Un-init stuff } }; TEST(FooTestGroup, Foo) { // Test FOO } TEST(FooTestGroup, MoreFoo) { // Test more FOO } TEST_GROUP(BarTestGroup) { void setup() { // Init Bar } }; TEST(BarTestGroup, Bar) { // Test Bar } ``` -------------------------------- ### Pure C Test Example Source: https://cpputest.github.io/manual Demonstrates how to write tests in a .c file using CppUTest's C interface. Includes mock setup, test case definitions, and assertions. ```c #include "PureCTests_c.h" /** the offending C header */ #include "CppUTest/TestHarness_c.h" #include "CppUtestExt/MockSupport_c.h"/** Mock for function internal() */ int internal(int new) { mock_c()->actualCall("internal") ->withIntParameters("new", new); return mock_c()->returnValue().value.intValue; } /** Implementation of function to test */ int private (int new) { return internal(new); } /** Setup and Teardown per test group (optional) */ TEST_GROUP_C_SETUP(mygroup) { } TEST_GROUP_C_TEARDOWN(mygroup) { mock_c()->checkExpectations(); mock_c()->clear(); } /** The actual tests for this test group */ TEST_C(mygroup, test_success) { mock_c()->expectOneCall("internal")->withIntParameters("new", 5)->andReturnIntValue(5); int actual = private(5); CHECK_EQUAL_C_INT(5, actual); } TEST_C(mygroup, test_mockfailure) { mock_c()->expectOneCall("internal")->withIntParameters("new", 2)->andReturnIntValue(5); int actual = private(5); CHECK_EQUAL_C_INT(5, actual); } TEST_C(mygroup, test_equalfailure) { mock_c()->expectOneCall("internal")->withIntParameters("new", 5)->andReturnIntValue(2); int actual = private(5); CHECK_EQUAL_C_INT(5, actual); } ``` -------------------------------- ### MockSupportPlugin Setup in C++ Source: https://cpputest.github.io/plugin_manual Illustrates the setup and usage of the MockSupportPlugin in C++ for simplifying mock interactions. It shows how to install custom comparators and the plugin itself into the test registry. ```C++ #include "CppUTest/TestRegistry.h" #include "CppUTestExt/MockSupportPlugin.h"MyDummyComparator dummyComparator; MockSupportPlugin mockPlugin; mockPlugin.installComparator("MyDummyType", dummyComparator); TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin); ``` -------------------------------- ### CppUTest Setup for IEEE754ExceptionsPlugin Source: https://cpputest.github.io/plugin_manual Example C++ code demonstrating how to set up and use the IEEE754ExceptionsPlugin within a CppUTest test suite. It includes installing the plugin and defining test groups to check for floating-point errors. ```C++ #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestRegistry.h" #include "CppUTestExt/IEEE754ExceptionsPlugin.h" int main(int ac, char** av) { IEEE754ExceptionsPlugin ieee754Plugin; TestRegistry::getCurrentRegistry()->installPlugin(&ieee754Plugin); return CommandLineTestRunner::RunAllTests(ac, av); } static volatile float f; TEST_GROUP(CatchFloatingPointErrors) { void setup() { IEEE754ExceptionsPlugin::disableInexact(); } }; TEST(CatchFloatingPointErrors, underflow) { f = 0.01f; while (f > 0.0f) f *= f; CHECK(f == 0.0f); } TEST(CatchFloatingPointErrors, inexact) { IEEE754ExceptionsPlugin::enableInexact(); f = 10.0f; DOUBLES_EQUAL(f / 3.0f, 3.333f, 0.001f); } ``` -------------------------------- ### Install CppUTest on Debian/Ubuntu Source: https://cpputest.github.io/index Installs CppUTest using the apt-get package manager on Debian-based Linux distributions. ```bash $ apt-get install cpputest ``` -------------------------------- ### Install CppUTest on MacOSX Source: https://cpputest.github.io/index Installs CppUTest using the Homebrew package manager on macOS. ```bash $ brew install cpputest ``` -------------------------------- ### CppUTest Visual Studio Project Setup Source: https://cpputest.github.io/index Instructions for opening and building CppUTest projects in Visual Studio. It mentions specific solution files for different VS versions and the process of running tests after a successful build. ```text Depending on your VS version double click either * **CppUTest_VS201x.sln** - for VS 2010 and later * **CppUTest.sln** - for pre VS 2010 Say yes to suggested conversions. Select the menu item corresponding to run without debugging. CppUTest should build (probably with warnings). When the build completes the test runner runs. You should see over 1000 tests passing and no test failures. The build also produced a static library (cpputest/lib) holding CppUTest you can link your tests to. ``` -------------------------------- ### CppUTest AllTests.cpp Example Source: https://cpputest.github.io/stories This code demonstrates the content for AllTests.cpp, a file used to set up and run all tests within a CppUTest project. It shows how to use CommandLineTestRunner and override command-line arguments. ```C++ #include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { const char * av_override[] = { "exe", "-v" }; //turn on verbose mode //return CommandLineTestRunner::RunAllTests(ac, av); return CommandLineTestRunner::RunAllTests(2, av_override); } ``` -------------------------------- ### Gdb Session Example Source: https://cpputest.github.io/plugin_manual Illustrates a typical Gdb session for debugging a floating-point error. It shows commands for starting Gdb, setting breakpoints, running the program, setting watchpoints, and observing changes in variable values. ```Shell $ gdb ./example.exe GNU gdb (GDB) 7.6.50.20130728-cvs (cygwin-special) #...more gdb output here... Reading symbols from /cygdrive/c/data/00_Dev/06_Faking/MiscellanousTests/example.exe...done. (gdb) (gdb) break main Breakpoint 1 at 0x4011ab: file example.cpp, line 8. (gdb) run Starting program: /cygdrive/c/data/00_Dev/06_Faking/MiscellanousTests/example.exe [New Thread 6476.0x2038] [New Thread 6476.0x239c] Breakpoint 1, main () at example.cpp:8 8 f /= 0.0f; (gdb) (gdb) watch IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag() Watchpoint 2: IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag() (gdb) (gdb) next Watchpoint 2: IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag() Old value = false New value = true 0x004011b5 in main () at example.cpp:8 8 f /= 0.0f; (gdb) ``` -------------------------------- ### Makefile: CppUTest Path Configuration Source: https://cpputest.github.io/manual This snippet illustrates how to define the CPPUTEST_HOME environment variable or Makefile variable to specify the installation path of the CppUTest framework. ```Makefile CPPUTEST_HOME = /Users/vodde/workspace/cpputest ``` -------------------------------- ### Build CppUTest with Autoconf Source: https://cpputest.github.io/index Builds CppUTest from source using autoconf, automake, and libtool. Requires these GNU autotools to be installed. ```bash $ cd cpputest_build $ autoreconf .. -i $ ../configure $ make ``` -------------------------------- ### Clone CppUTest Repository Source: https://cpputest.github.io/index Clones the CppUTest GitHub repository for source installation or direct use. ```bash $ git clone https://github.com/cpputest/cpputest.git ``` ```bash $ git clone git@github.com:cpputest/cpputest.git ``` -------------------------------- ### CppUTest MyCodeTest.cpp Example Source: https://cpputest.github.io/stories This snippet shows the content for MyCodeTest.cpp, which includes the code under test and defines test groups and individual tests using CppUTest macros. It demonstrates a basic test case with a failure. ```C++ extern "C" { #include "..\MyCode.h" } #include "CppUTest/TestHarness.h" TEST_GROUP(FirstTestGroup) { void setup() {} void teardown() {} }; TEST(FirstTestGroup, FirstTest) { FAIL("Fail me!"); } TEST(FirstTestGroup, SecondTest) { STRCMP_EQUAL("hello", "world"); } ``` -------------------------------- ### C Mocking Framework Interface Source: https://cpputest.github.io/mocking_manual Demonstrates how to use the C interface of the CppUTest mocking framework. This includes setting expectations, specifying parameters, checking return values, installing and removing comparators, and clearing mock data. ```c #include "CppUTestExt/MockSupport_c.h" // Expecting and returning values mock_c()->expectOneCall("foo")->withIntParameters("integer", 10)->andReturnDoubleValue(1.11); return mock_c()->actualCall("foo")->withIntParameters("integer", 10)->returnValue().value.doubleValue; // Installing and removing comparators mock_c()->installComparator("type", equalMethod, toStringMethod); mock_scope_c("scope")->expectOneCall("bar")->withParameterOfType("type", "name", object); mock_scope_c("scope")->actualCall("bar")->withParameterOfType("type", "name", object); mock_c()->removeAllComparators(); // Setting integer data mock_c()->setIntData("important", 10); // Checking expectations and clearing mocks mock_c()->checkExpectations(); mock_c()->clear(); ``` ```c // Specifying actual return values (v3.8) return mock_c()->actualCall("foo")->withIntParameters("integer", 10)->doubleReturnValue(); return mock_c()->doubleReturnValue(); // Specifying default return values (v3.8) return mock_c()->actualCall("foo")->withIntParameters("integer", 10)->returnDoubleValueOrDefault(2.25); return mock_c()->returnDoubleValueOrDefault(2.25); ``` -------------------------------- ### Gdb Example for Division by Zero Source: https://cpputest.github.io/plugin_manual A minimal C++ example demonstrating how to use Gdb to debug a division by zero error. It involves compiling the code with debugging symbols, setting a breakpoint, running the program, and setting a watchpoint on the relevant checking function. ```C++ #include "CppUTest/TestHarness.h" #include "CppUTestExt/IEEE754ExceptionsPlugin.h" static volatile float f = 1.0; static volatile IEEE754ExceptionsPlugin plugin; // Make sure this is linked, so the debugger knows it int main(int, char**) { f /= 0.0f; // the offending statement return 0; } ``` -------------------------------- ### Gdb Compilation Command Source: https://cpputest.github.io/plugin_manual Example command for compiling a C++ program with Gdb debugging flags, including optimization levels and standard C++ version, for use with the IEEE754ExceptionsPlugin. ```Shell $ g++ -Wextra -Wall -Werror -g3 -O0 -std=c++11 -Iinclude -Llib example.cpp -lCppUTest -lCppUTestExt -o example.exe ``` -------------------------------- ### Using Google Mock in CppUTest Tests Source: https://cpputest.github.io/manual Example of how to use Google Mock within CppUTest tests. This includes including the GMock header, defining a mock class, and setting up expectations using EXPECT_CALL. ```cpp #include "CppUTestExt/GMock.h" class MyMock : public ProductionInterface { public: MOCK_METHOD0(methodName, int()); }; TEST(TestUsingGMock, UsingMyMock) { NiceMock mock; EXPECT_CALL(mock, methodName()).Times(2).WillRepeatedly(Return(1)); productionCodeUsing(mock); } ``` -------------------------------- ### CppUTest Memory Leak Detection Setup Source: https://cpputest.github.io/manual Instructions for enabling CppUTest's memory leak detection macros in your Makefile for C++ and C code. ```makefile CXXFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorNewMacros.h CFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h ``` -------------------------------- ### CppUTest: Custom Object Parameter Comparison Source: https://cpputest.github.io/mocking_manual Demonstrates how to mock functions with custom object parameters by installing a custom comparator. This involves defining a comparator class that implements `MockNamedValueComparator` for equality checks and string representation. ```C++ mock().expectOneCall("function").withParameterOfType("myType", "parameterName", object); ``` ```C++ MyTypeComparator comparator; mock().installComparator("myType", comparator); ``` ```C++ class MyTypeComparator : public MockNamedValueComparator { public: virtual bool isEqual(const void* object1, const void* object2) { return object1 == object2; } virtual SimpleString valueToString(const void* object) { return StringFrom(object); } }; ``` ```C++ mock().removeAllComparatorsAndCopiers(); ``` -------------------------------- ### Enable/Disable Mocking Framework in CppUTest Source: https://cpputest.github.io/mocking_manual Shows how to temporarily disable the CppUTest mocking framework to perform actions without mock interference, and then re-enable it. Useful during initialization or complex setup phases. ```cpp mock().disable(); doSomethingThatWouldOtherwiseBlowUpTheMockingFramework(); mock().enable(); ``` -------------------------------- ### Build Configuration for Google Mock Source: https://cpputest.github.io/manual Steps to configure and build CppUTest with Google Mock support. This involves setting the GMOCK_HOME environment variable and running the configure script with the --enable-gmock flag. ```bash $ GMOCK_HOME = /location/of/gmock $ configure --enable-gmock $ make $ make install ``` -------------------------------- ### CppUTest Build with CMake Source: https://cpputest.github.io/index Provides the command-line steps to build CppUTest using CMake. This includes changing the directory, running cmake, and then making the build. ```bash $ cd cpputest_build $ cmake .. $ make ``` -------------------------------- ### Simple Function Call Mocking Source: https://cpputest.github.io/mocking_manual Demonstrates how to mock a single function call using CppUTest. It shows setting up an expectation for one call to 'productionCode' and verifying it. ```cpp #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(MockDocumentation) { void teardown() { mock().clear(); } }; void productionCode() { mock().actualCall("productionCode"); } TEST(MockDocumentation, SimpleScenario) { mock().expectOneCall("productionCode"); productionCode(); mock().checkExpectations(); } ``` ```cpp mock().expectOneCall("productionCode"); ``` ```cpp mock().checkExpectations(); ``` ```cpp void productionCode() { mock().actualCall("productionCode"); } ``` ```cpp mock().expectNCalls(5, "productionCode"); ``` -------------------------------- ### Build CppUTest with MakefileWorker and gcc Source: https://cpputest.github.io/index Sets up CppUTest for use with MakefileWorker and gcc. This involves cloning the repository, configuring, building the test targets, and exporting the CPPUTEST_HOME environment variable. ```bash $ cd cpputest $ autoreconf . -i $ ./configure $ make tdd $ export CPPUTEST_HOME=$(pwd). ``` -------------------------------- ### C++ Wrapper for C Tests Source: https://cpputest.github.io/manual Shows how to create a C++ file that wraps C test groups and individual tests for execution with CppUTest's test runner. ```cpp #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestHarness_c.h"/** For each C test group */ TEST_GROUP_C_WRAPPER(mygroup) { TEST_GROUP_C_SETUP_WRAPPER(mygroup); /** optional */ TEST_GROUP_C_TEARDOWN_WRAPPER(mygroup); /** optional */ }; /** For each C test */ TEST_C_WRAPPER(mygroup, test_success); TEST_C_WRAPPER(mygroup, test_mockfailure); TEST_C_WRAPPER(mygroup, test_equalfailure); /** Test main as usual */ int main(int ac, char** av) { return RUN_ALL_TESTS(ac, av); } ``` -------------------------------- ### Mocking Object Methods Source: https://cpputest.github.io/mocking_manual Illustrates how to mock methods of an object using CppUTest. It shows replacing a real object with a mock and verifying calls to its methods, including checking the object instance. ```cpp class ClassFromProductionCodeMock : public ClassFromProductionCode { public: virtual void importantFunction() { mock().actualCall("importantFunction"); } }; TEST(MockDocumentation, SimpleScenarioObject) { mock().expectOneCall("importantFunction"); ClassFromProductionCode* object = new ClassFromProductionCodeMock; /* create mock instead of real thing */ object->importantFunction(); mock().checkExpectations(); delete object; } ``` ```cpp mock().expectOneCall("importantFunction").onObject(object); ``` ```cpp mock().actualCall("importantFunction").onObject(this); ``` -------------------------------- ### Build Configuration for Google Test Only Source: https://cpputest.github.io/manual Steps to configure and build CppUTest with Google Test support enabled, without Google Mock. This involves setting the GTEST_HOME environment variable and running the configure script with the --enable-real-gtest flag. ```bash $ GMOCK_HOME = /location/of/gtest $ configure --enable-real-gtest $ make $ make install ``` -------------------------------- ### IAR Project Options Configuration for CppUTest Source: https://cpputest.github.io/stories This section outlines the necessary project configuration changes within the IAR IDE to successfully build and run CppUTest projects. It covers general options, compiler settings, and linker configurations. ```APIDOC General Options -> change Device to your target device General Options -> Library Configuration -> check "Use CMSIS" if it used in your target project C/C++ Compiler -> Language 1 -> Language = Auto C/C++ Compiler -> Language 1 -> C++ Dialect = C++ C/C++ Compiler -> Preprocessor -> Additional include directories = path\to\cpputest\include C/C++ Compiler -> Preprocessor -> add any necessary #defines from the target project to Defined symbols C/C++ Compiler -> Diagnostics -> Suppress these diagnostics = Pa050 Linker -> Config -> Override default with icf file used by target project ``` -------------------------------- ### CppUTest Mocking Support Overview Source: https://cpputest.github.io/mocking_manual This section details the mocking support within the CppUTest framework. Key design goals include suitability for embedded systems, no code generation, minimal use of magic macros, simplicity, and developer control. The focus is on facilitating manual mocking. ```C++ #include // Example of a simple mock object class MockMyClass : public MockSupport { public: virtual ~MockMyClass() {} // Mock methods go here }; // Example of setting expectations and verifying calls TEST(MockTest, SimpleMock) { MockMyClass mock; mock.expectOneCall("methodName"); // ... call code that uses the mock ... mock.assertComplete(); } ``` -------------------------------- ### Basic CppUTest Test Structure Source: https://cpputest.github.io/index Illustrates the fundamental structure for writing a unit test in CppUTest. It shows how to define a test group and a simple test case that intentionally fails. ```cpp TEST_GROUP(FirstTestGroup) { }; TEST(FirstTestGroup, FirstTest) { FAIL("Fail me!"); } ``` -------------------------------- ### Mocking Function Parameters Source: https://cpputest.github.io/mocking_manual Explains how to verify parameters passed to mocked functions using CppUTest. It demonstrates recording expected parameter values and checking actual calls against these expectations. ```cpp mock().expectOneCall("function").onObject(object).withParameter("p1", 2).withParameter("p2", "hah"); ``` ```cpp mock().actualCall("function").onObject(this).withParameter("p1", p1).withParameter("p2", p2); ``` -------------------------------- ### CppUTest Coverage Report Generation Source: https://cpputest.github.io/index Demonstrates how to generate code coverage reports for CppUTest's own tests using 'make check_coverage'. It explains the output files generated and how to view the HTML report with lcov. ```bash $ make check_coverage ``` -------------------------------- ### CPPUTest Mocking: Output Parameters with Custom Copiers Source: https://cpputest.github.io/mocking_manual Demonstrates how to handle output parameters in CPPUTest mocks using custom type copiers. It shows how to set up expectations with output parameters, implement a custom copier by inheriting from MockNamedValueCopier, and install/remove copiers. ```C++ MyType outputValue = 4; mock().expectOneCall("Foo").withOutputParameterOfTypeReturning("MyType", "bar", &outputValue); ``` ```C++ void Foo(MyType *bar) { mock().actualCall("Foo").withOutputParameterOfType("MyType", "bar", bar); } ``` ```C++ MyTypeCopier copier; mock().installCopier("myType", copier); ``` ```C++ class MyTypeCopier : public MockNamedValueCopier { public: virtual void copy(void* out, const void* in) { *(MyType*)out = *(const MyType*)in; } }; ``` ```C++ mock().removeAllComparatorsAndCopiers(); ``` -------------------------------- ### CppUTest: Basic Main Function for Test Execution Source: https://cpputest.github.io/manual This snippet shows a standard main function for a CppUTest project. It utilizes the CommandLineTestRunner to discover and execute all defined tests. ```C++ #include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { return CommandLineTestRunner::RunAllTests(ac, av); } ``` -------------------------------- ### CppUTest Includes Order Source: https://cpputest.github.io/manual A recommendation to place CppUTest includes after your own project's includes to preemptively avoid potential conflicts, especially in test files where custom code might interact with CppUTest's macros. ```cpp // Include your headers first // #include "my_header.h" // Then include CppUTest headers // #include "CppUTest/TestHarness.h" ``` -------------------------------- ### Configure CppUTest Library Build in IAR Source: https://cpputest.github.io/stories Steps to configure an IAR Embedded Workbench project to build the CppUTest library. This includes setting the target core, output format, language settings, include directories, and suppressing specific compiler warnings. ```IAR Project Configuration Project -> Options -> General Options -> Target -> Core = Cortex-M3. Project -> Options -> General Options -> Output -> Output file = Library Project -> Options -> General Options -> Output -> Executables/libraries = Debug (removed exe subdirectory) Project -> Options -> C/C++ Compiler -> Language 1 -> Language = C++ Project -> Options -> C/C++ Compiler -> Language 1 -> Language conformance = Standard Project -> Options -> C/C++ Compiler -> Language 1 -> C++ Dialect = C++ (leave exceptions checked) Project -> Options -> C/C++ Compiler -> Preprocessor -> Additional include directories = $PROJ_DIR$\include Project -> Options -> C/C++ Compiler -> Diagnostics -> Suppress these diagnostics = Pa050 (turn off warning about non-standard line endings) Added all .cpp files in src\CppUTest\ Added src\Platforms\Iar\UtestPlatform.cpp ``` -------------------------------- ### CppUTest Test Runner Main Function Source: https://cpputest.github.io/index Shows the essential main function required to run all CppUTest unit tests. It utilizes the CommandLineTestRunner to execute the test suite. ```cpp int main(int ac, char** av) { return CommandLineTestRunner::RunAllTests(ac, av); } ``` -------------------------------- ### Configure CppUTest Tests Build in IAR Source: https://cpputest.github.io/stories Instructions for setting up an IAR Embedded Workbench project to build and run CppUTest tests. This involves configuring the target, library interface, compiler, linker settings, and specifying necessary files and modifications. ```IAR Project Configuration Project -> Options -> General Options -> Target -> Core = Cortex-M3. Project -> Options -> General Options -> Library Configuration -> Library low-level interface implementation = Semihosted Project -> Options -> C/C++ Compiler -> Language 1 -> Language = Auto Project -> Options -> C/C++ Compiler -> Language 1 -> Language conformance = Standard Project -> Options -> C/C++ Compiler -> Language 1 -> C++ Dialect = C++ (leave exceptions checked) Project -> Options -> C/C++ Compiler -> Preprocessor -> Additional include directories = $PROJ_DIR$\include Project -> Options -> C/C++ Compiler -> Diagnostics -> Suppress these diagnostics = Pa050 (turn off warning about non-standard line endings) Project -> Options -> Linker -> Config -> Override default -> Edit -> Stack/Heap Sizes -> CSTACK = 0x600 Project -> Options -> Linker -> Config -> Override default -> Edit -> Stack/Heap Sizes -> HEAP = 0x8000 Added all .cpp and .c files in tests\ Added Debug\CppUTest.a Changed line 16 of tests\AllocLetTestFree.c to explicit cast to (AllocLetTestFree) to satisfy compiler Changed line 22 of tests\AllocLetTestFree.c to type AllocLetTestFree instead of void* to satisfy compiler Changed tests\AllTests.cpp to declare a const char*[] with "-v" as the second element, so it can be passed to RunAllTests to turn on verbose mode in IAR ``` -------------------------------- ### CppUTest: Define a Test Group and a Test Source: https://cpputest.github.io/manual This snippet demonstrates how to define a test group and a basic test case using CppUTest macros. It includes a failing test and a test with a string comparison assertion. ```C++ #include "CppUTest/TestHarness.h" TEST_GROUP(FirstTestGroup) { }; TEST(FirstTestGroup, FirstTest) { FAIL("Fail me!"); } TEST(FirstTestGroup, SecondTest) { STRCMP_EQUAL("hello", "world"); } ``` -------------------------------- ### Add CppUTest as Git Submodule Source: https://cpputest.github.io/index Adds the CppUTest repository as a submodule to an existing Git repository. ```bash $ git submodule add https://github.com/cpputest/cpputest.git ``` -------------------------------- ### Makefile: Linker Flags for CppUTest Libraries Source: https://cpputest.github.io/manual This snippet details the linker flags required to link the CppUTest libraries, including the main library and the extensions library for features like mocking. ```Makefile LD_LIBRARIES = -L$(CPPUTEST_HOME)/lib -lCppUTest -lCppUTestExt ``` -------------------------------- ### CPPUTest OrderedTest C Wrapper Syntax Source: https://cpputest.github.io/plugin_manual Demonstrates the C-style syntax for defining ordered tests using the TEST_C macro, which is typically used with TEST_ORDERED_C_WRAPPER in C++ code. This allows C functions to be integrated into the ordered test execution flow. ```c #include "CppUTest/TestHarness_c.h" TEST_C(TestOrdered, Test2) { // 2. Test } TEST_C(TestOrdered, Test5) { // 5. Test } ``` -------------------------------- ### CppUTest Command Line Switches Source: https://cpputest.github.io/manual Provides a list of command-line switches for controlling CppUTest test execution, such as filtering, output formatting, and test repetition. ```APIDOC -c: colorize output, print green if OK, or red if failed -g group: only run test whose group contains the substring group -k: package name, Add a package name in JUnit output (for classification in CI systems) -lg: print a list of group names, separated by spaces -ln: print a list of test names in the form of group.name, separated by spaces -n name: only run test whose name contains the substring name -ojunit: output to JUnit ant plugin style xml files (for CI systems) -oteamcity: output to xml files (as the name suggests, for TeamCity) -p: run tests in a separate process. -r# repeat the tests some number (#) of times, or twice if # is not specified. This is handy if you are experiencing memory leaks. A second run that has no leaks indicates that someone is allocating statics and not releasing them. -sg group: only run test whose group exactly matches the string group -sn name: only run test whose name exactly matches the string name -v: verbose, print each test name as it runs -xg group: exclude tests whose group contains the substring group (v3.8) -xn name: exclude tests whose name contains the substring name (v3.8) "TEST(group, name)": only run test whose group and name matches the strings group and name. This can be used to copy-paste output from the -v option on the command line. ``` -------------------------------- ### Link Tests in Library with GNU Linker Source: https://cpputest.github.io/manual Demonstrates how to link tests within libraries using the GNU linker by specifying the '-Wl,-whole-archive' and '-Wl,-no-whole-archive' options to prevent the linker from discarding tests. ```bash gcc -o test_executable production_library.a -Wl,-whole-archive test_library.a -Wl,-no-whole-archive $(OTHER_LIBRARIES) ``` -------------------------------- ### CppUTest Per-Test Process Execution Source: https://cpputest.github.io/manual Enables running tests in a separate process on a per-test basis within CppUTest. ```cpp TestRegistry::getCurrentRegistry()->setRunTestsInSeperateProcess(); ``` -------------------------------- ### CppUTest: Mocking Output Parameters Source: https://cpputest.github.io/mocking_manual Illustrates how to specify and verify output parameters in CppUTest mocks. This is used for parameters passed by reference that the function modifies to return values. ```C++ int outputValue = 4; mock().expectOneCall("Foo").withOutputParameterReturning("bar", &outputValue, sizeof(outputValue)); ``` ```C++ void Foo(int *bar) { mock().actualCall("Foo").withOutputParameter("bar", bar); } ``` -------------------------------- ### CppUTest Additional Test Assertions Source: https://cpputest.github.io/index Demonstrates adding more tests within the same test group using various CppUTest assertion macros like STRCMP_EQUAL, LONGS_EQUAL, and CHECK. ```cpp TEST(FirstTestGroup, SecondTest) { STRCMP_EQUAL("hello", "world"); LONGS_EQUAL(1, 2); CHECK(false); } ``` -------------------------------- ### CPPUTest Mocking: Setting Return Values Source: https://cpputest.github.io/mocking_manual Explains how to configure mock functions in CPPUTest to return specific values. It covers using `andReturnValue` and retrieving the return value within the actual mock implementation using `returnIntValue` or `intReturnValue`. ```C++ mock().expectOneCall("function").andReturnValue(10); ``` ```C++ int function () { return mock().actualCall("function").returnIntValue(); } ``` ```C++ int function () { mock().actualCall("function"); return mock().intReturnValue(); } ``` -------------------------------- ### CppUTest Test Definition Macros Source: https://cpputest.github.io/manual Defines the fundamental macros for structuring and naming tests within CppUTest. Includes macros for defining tests, ignoring tests, and declaring test groups. ```cpp TEST(group, name) - define a test IGNORE_TEST(group, name) - turn off the execution of a test TEST_GROUP(group) - Declare a test group to which certain tests belong. This will also create the link needed from another library. TEST_GROUP_BASE(group, base) - Same as TEST_GROUP, just use a different base class than Utest IMPORT_TEST_GROUP(group) - Export the name of a test group so it can be linked in from a library (also see Advanced Stuff) ``` -------------------------------- ### CppUTest: Mocking Memory Buffer Parameters Source: https://cpputest.github.io/mocking_manual Shows how to mock functions that accept memory buffers as parameters. This allows checking the content of the data pointed to by the buffer, not just the pointer itself. ```C++ mock().expectOneCall("function").onObject(object).withMemoryBufferParameter("buffer", buffer, length); ``` ```C++ mock().actualCall("function").onObject(this).withMemoryBufferParameter("buffer", buffer, length); ``` -------------------------------- ### Makefile: Compiler Flags for CppUTest Source: https://cpputest.github.io/manual This snippet shows the necessary compiler flags for CppUTest, including adding the include directory and setting up memory leak detection macros for both C and C++ code. ```Makefile CPPFLAGS += -I$(CPPUTEST_HOME)/include CXXFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorNewMacros.h CFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h ``` -------------------------------- ### IAR Embedded Workbench RAM Usage Breakdown Source: https://cpputest.github.io/stories A breakdown of RAM usage for a CppUTest project on a Cortex-M3 target using IAR Embedded Workbench, showing the distribution between static data, heap, dynamic exit routines, and stack. ```Map File Analysis Static: 21056 bytes Heap: 32768 bytes iar.dynexit (atexit statics): 8760 Stack: 1536 bytes Total: 64120 bytes out of 65535 bytes. ``` -------------------------------- ### SetPointerPlugin Usage in C++ Source: https://cpputest.github.io/plugin_manual Demonstrates how to use the SetPointerPlugin to manage and restore pointer values within C++ unit tests. It shows setting up the plugin in main and overriding function pointers for testing purposes. ```C++ int main(int ac, char** av) { TestRegistry* r = TestRegistry::getCurrentRegistry(); SetPointerPlugin ps("PointerStore"); r->installPlugin(&ps); return CommandLineTestRunner::RunAllTests(ac, av); } TEST_GROUP(HelloWorld) { static int output_method(const char* output, ...) { va_list arguments; va_start(arguments, output); cpputest_snprintf(buffer, BUFFER_SIZE, output, arguments); va_end(arguments); return 1; } void setup() { // overwrite the production function pointer witha an output method that captures // output in a buffer. UT_PTR_SET(helloWorldApiInstance.printHelloWorld_output, &output_method); } void teardown() { } }; TEST(HelloWorld, PrintOk) { printHelloWorld(); STRCMP_EQUAL("Hello World!\n", buffer) } // Hello.h #ifndef HELLO_H_ #define HELLO_H_ extern void printHelloWorld(); struct helloWorldApi { int (*printHelloWorld_output) (const char*, ...); }; #endif // Hello.c #include #include "hello.h"// in production, print with printf. struct helloWorldApi helloWorldApiInstance = { &printf }; void printHelloWorld() { helloWorldApiInstance.printHelloWorld_output("Hello World!\n"); } ``` -------------------------------- ### CPPUTest OrderedTest Macros Source: https://cpputest.github.io/plugin_manual Defines the macros used for creating ordered tests in CPPUTest. TEST_ORDERED is for C++ tests, and TEST_ORDERED_C_WRAPPER is for C++ wrappers around C tests. Tests are executed based on the provided level, from lowest to highest. ```cpp #include "CppUTest/TestHarness.h" #include "CppUTestExt/OrderedTest.h" TEST_GROUP(TestOrderedTest) {} TEST_ORDERED(TestOrdered, Test3, 3) { // 3. Test } TEST_ORDERED(TestOrdered, Test1, 1) { // 1. Test } TEST_ORDERED(TestOrdered, Test4, 3) { // 4. Test } TEST_ORDERED_C_WRAPPER(TestOrdered, Test2, 2) TEST_ORDERED_C_WRAPPER(TestOrdered, Test5, 5) ``` -------------------------------- ### Clear Mock Expectations and Settings in CppUTest Source: https://cpputest.github.io/mocking_manual Demonstrates the use of `mock().clear()` to reset all mock expectations, settings, and comparators. This is typically used after `checkExpectations` to prepare for subsequent test phases. ```cpp mock().clear(); ``` -------------------------------- ### Debugging Floating Point Failures with Gdb Source: https://cpputest.github.io/plugin_manual Provides guidance on using Gdb to debug floating-point failures detected by the IEEE754ExceptionsPlugin. It details setting up watchpoints on specific checking functions to pinpoint the source of errors. ```APIDOC IEEE754ExceptionsPlugin::checkIeee754OverflowExceptionFlag(); IEEE754ExceptionsPlugin::checkIeee754UnderflowExceptionFlag(); IEEE754ExceptionsPlugin::checkIeee754InexactExceptionFlag(); IEEE754ExceptionsPlugin::checkIeee754DivByZeroExceptionFlag(); ```