### Install Target Libraries and Headers Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Defines the installation rules for the target, specifying destinations for libraries, headers, and components. ```cmake install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}Targets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} COMPONENT library ) ``` -------------------------------- ### Install Configuration Files Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Installs the main CMake configuration file and the version configuration file, making the package discoverable via find_package(). ```cmake install(FILES ${PROJECT_NAME}Config.cmake ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} ) ``` -------------------------------- ### Setup Project with Meson Source: https://github.com/throwtheswitch/unity/blob/master/examples/example_4/readme.txt Run this command to set up the build directory for the project using Meson. ```bash meson setup ``` -------------------------------- ### Overall Unity Test Summary Example Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md An example of the overall test summary output, indicating the total number of tests, total failures, and ignored tests. ```Shell -------------------------- OVERALL UNITY TEST SUMMARY -------------------------- 45 TOTAL TESTS 2 TOTAL FAILURES 1 IGNORED ``` -------------------------------- ### Configure Include Directories Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Sets up include directories for build and installation, differentiating between build-time and install-time paths, and conditionally including extension sources. ```cmake target_include_directories(${PROJECT_NAME} PUBLIC $ $ $ $ $:${CMAKE_CURRENT_SOURCE_DIR}/extras/memory/src>> $:${CMAKE_CURRENT_SOURCE_DIR}/extras/fixture/src>> ) ``` -------------------------------- ### Unity Failed Test Summary Example Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md An example of the failed test summary output format, showing the file, line number, test name, and FAIL status with expected vs. actual values. ```Shell ------------------------- UNITY FAILED TEST SUMMARY ------------------------- blah.c:87:test_sandwiches_should_HaveCondiments:FAIL:Expected 1 was 0 meh.c:38:test_soda_should_BeCalledPop:FAIL:Expected "pop" was "coke" ``` -------------------------------- ### Running Build with Make Source: https://github.com/throwtheswitch/unity/blob/master/examples/example_5/readme.txt To build and run the example, simply execute the 'make' command in your terminal. This will compile and execute the test, producing output that includes detailed error information. ```bash make ``` -------------------------------- ### Minimalist RUN_TEST Macro Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityConfigurationGuide.md This macro handles setup, teardown, and failure protection for a single test case. It declares a new test, executes setUp() and the test function within a protected block, runs tearDown() if applicable, and concludes the test. ```C #define RUN_TEST(testfunc) \ UNITY_NEW_TEST(#testfunc) \ if (TEST_PROTECT()) { \ setUp(); \ testfunc(); \ } \ if (TEST_PROTECT() && (!TEST_IS_IGNORED)) \ tearDown(); \ UnityConcludeTest(); ``` -------------------------------- ### Example of Parameterized Test Output Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md This log output demonstrates how parameterized tests, generated using macros like `TEST_CASE`, appear after the test executable starts. Each line indicates the test file, function, arguments, and result (PASS). ```log tests/test_unity_parameterizedDemo.c:14:test_demoParamFunction(1, 2, 5):PASS tests/test_unity_parameterizedDemo.c:14:test_demoParamFunction(10, 7, 20):PASS ``` -------------------------------- ### Unity Ignored Test Summary Example Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md An example of the ignored test summary output format, showing the file, line number, test name, and IGNORE status. ```Shell -------------------------- UNITY IGNORED TEST SUMMARY -------------------------- blah.c:22:test_sandwiches_should_HaveBreadOnTwoSides:IGNORE ``` -------------------------------- ### Define Suite Setup Function in C Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Define a C function to be executed before any test cases run. Alternatively, provide a `void suiteSetUp(void)` function if your compiler supports weak symbols. ```C void suiteSetUp(void) { // Code to execute before tests } ``` -------------------------------- ### BDD Macro Example in C# Source: https://github.com/throwtheswitch/unity/blob/master/extras/bdd/readme.md Illustrates the usage of GIVEN, WHEN, and THEN macros to structure a test scenario. These macros are purely for descriptive purposes. ```csharp GIVEN("a valid input") { // Test setup and context // ... WHEN("the input is processed") { // Perform the action // ... THEN("the expected outcome occurs") { // Assert the outcome // ... } } } ``` -------------------------------- ### Override Test Setup Function Name Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Use the `:setup_name` option to override the default test `setUp` function name. This can also be specified via the command prompt. ```text :setup_name ``` -------------------------------- ### Unity Memory Extension for Leak Detection Source: https://context7.com/throwtheswitch/unity/llms.txt Include unity_memory.h to intercept memory allocation functions. Use UnityMalloc_MakeMallocFailAfterCount(n) to simulate out-of-memory conditions for error-path testing. setUp and tearDown functions are used to start and end test memory tracking. ```c #include "unity.h" #include "unity_memory.h" #include "my_buffer.h" void setUp(void) { UnityMalloc_StartTest(); } void tearDown(void) { UnityMalloc_EndTest(); /* reports leaks */ } void test_buffer_should_NotLeakOnNormalUsage(void) { Buffer *b = buffer_create(64); TEST_ASSERT_NOT_NULL(b); buffer_write(b, "hello", 5); buffer_destroy(b); /* tearDown will verify malloc/free are balanced */ } void test_buffer_create_should_HandleAllocFailure(void) { /* Force malloc to fail on the very first call */ UnityMalloc_MakeMallocFailAfterCount(0); Buffer *b = buffer_create(64); TEST_ASSERT_NULL(b); /* implementation must handle NULL gracefully */ } void test_buffer_write_should_HandleMidwayAllocFailure(void) { /* Allow 1 malloc to succeed (the buffer struct), then fail */ UnityMalloc_MakeMallocFailAfterCount(1); Buffer *b = buffer_create(64); TEST_ASSERT_NOT_NULL(b); int result = buffer_grow(b, 128); /* triggers a second malloc */ TEST_ASSERT_EQUAL(-1, result); /* must return error code */ buffer_destroy(b); } ``` -------------------------------- ### Install Target Export Files Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Installs the CMake export files for the target, enabling targets to be found by other CMake projects using find_package(). ```cmake install(EXPORT ${PROJECT_NAME}Targets NAMESPACE ${PROJECT_NAME}:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} ) ``` -------------------------------- ### C Test Case Signatures Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Example C function signatures that `generate_test_runner.rb` will detect as test cases. Functions starting with 'test' or 'spec' are recognized. ```C void testVerifyThatUnityIsAwesomeAndWillMakeYourLifeEasier(void) { ASSERT_TRUE(1); } void test_FunctionName_should_WorkProperlyAndReturn8(void) { ASSERT_EQUAL_INT(8, FunctionName()); } void spec_Function_should_DoWhatItIsSupposedToDo(void) { ASSERT_NOT_NULL(Function(5)); } ``` -------------------------------- ### Unity Test File Structure Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityGettingStartedGuide.md A typical Unity test file includes header includes, setUp and tearDown functions, test functions prefixed with 'test_' or 'spec_', and a main function to run the tests. ```C #include "unity.h" #include "file_to_test.h" void setUp(void) { // set stuff up here } void tearDown(void) { // clean stuff up here } void test_function_should_doBlahAndBlah(void) { //test stuff } void test_function_should_doAlsoDoBlah(void) { //more test stuff } // not needed when using generate_test_runner.rb int main(void) { UNITY_BEGIN(); RUN_TEST(test_function_should_doBlahAndBlah); RUN_TEST(test_function_should_doAlsoDoBlah); return UNITY_END(); } ``` -------------------------------- ### Example Test Execution Output Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md This log shows the output of tests generated by TEST_MATRIX, demonstrating the various combinations of parameters that were executed. ```Log tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 10, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 10, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 8, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 8, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 2, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 2, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 1, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(3, 1, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 10, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 10, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 8, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 8, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 2, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 2, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 1, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(4, 1, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 10, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 10, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 8, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 8, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 2, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 2, 20.0f):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 1, 30u):PASS tests/test_unity_parameterizedDemo.c:18:test_demoParamFunction(7, 1, 20.0f):PASS ``` -------------------------------- ### Generate Test Runner with Ruby Hash Options Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Example of using `generate_test_runner.rb` directly within a Ruby script, passing configuration options as a hash. ```Ruby require "generate_test_runner.rb" options = { :includes => ["stdio.h", "microdefs.h"], :cexception => 1, :suite_setup => "blah = malloc(1024);", :suite_teardown => "free(blah);" } UnityTestRunnerGenerator.new.run(testfile, runner_name, options) ``` -------------------------------- ### Non-Standard C Integer Size Example Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityAssertionsReference.md Demonstrates a scenario where a compiler might deviate from standard integer size guarantees due to target architecture constraints. This example shows a 12-bit int. ```C char (8 bit) <= short (12 bit) <= int (12 bit) <= long (16 bit) ``` -------------------------------- ### YAML Configuration for Test Runner Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Example YAML file content for configuring `generate_test_runner.rb`. This format is compatible with Unity and CMock. ```YAML :unity: :includes: - stdio.h - microdefs.h :cexception: 1 :suite_setup: "blah = malloc(1024);" :suite_teardown: "free(blah);" ``` -------------------------------- ### Configure Unity Test Framework with unity_config.h Source: https://context7.com/throwtheswitch/unity/llms.txt Customize Unity's behavior for embedded targets by defining macros in `unity_config.h`. This example shows settings for a 16-bit target with UART output, excluding floating-point support, and enabling execution timing and formatted print messages. ```c /* unity_config.h — example for a 16-bit embedded target with UART output */ /* ---- Integer widths ---- */ #define UNITY_INT_WIDTH 16 /* native int is 16 bits */ #define UNITY_LONG_WIDTH 32 /* long is 32 bits */ #define UNITY_POINTER_WIDTH 16 /* pointers are 16 bits */ /* ---- Floating point ---- */ #define UNITY_EXCLUDE_FLOAT /* no FPU available */ #define UNITY_EXCLUDE_DOUBLE /* ---- Output routing to UART ---- */ #include "uart_driver.h" #define UNITY_OUTPUT_CHAR(c) UART_putc((char)(c)) #define UNITY_OUTPUT_START() UART_init(115200) #define UNITY_OUTPUT_FLUSH() UART_flush() #define UNITY_OUTPUT_COMPLETE() UART_close() /* ---- Colorized output (ANSI) ---- */ #define UNITY_OUTPUT_COLOR /* ---- Execution timing ---- */ #define UNITY_INCLUDE_EXEC_TIME #define UNITY_CLOCK_MS system_get_ms /* returns uint32_t ms count */ /* ---- printf-style debug messages in tests ---- */ #define UNITY_INCLUDE_PRINT_FORMATTED /* ---- Parameterized test support ---- */ #define UNITY_SUPPORT_TEST_CASES ``` -------------------------------- ### C/C++ Whitespace Example Source: https://github.com/throwtheswitch/unity/blob/master/docs/ThrowTheSwitchCodingStandard.md Use 4 spaces for indentation in C/C++. Indent further for wrapped lines to align code neatly. ```c if (stuff_happened) { do_something(); } ``` -------------------------------- ### Example Error Output with Source Annotation Source: https://github.com/throwtheswitch/unity/blob/master/examples/example_5/readme.txt This output demonstrates the detailed error reporting provided by Unity. Each part of the error message is annotated with its source within the test code, aiding in quick error identification. ```text test/TestProductionCode.c:36:test_BitExtractor:FAIL: Expected 0 Was 1. During call BitExtractor. During call BitExtractor. Bit Position 6. Bit Mask 0x02. Unexpected bit value ``` -------------------------------- ### C/C++ Brace Style Example Source: https://github.com/throwtheswitch/unity/blob/master/docs/ThrowTheSwitchCodingStandard.md Place the left brace on the next line after the declaration and the right brace directly below it. Use braces even for single-line blocks. ```c while (blah) { //Like so. Even if only one line, we use braces. } ``` -------------------------------- ### Unity Boolean and Validity Assertions Source: https://context7.com/throwtheswitch/unity/llms.txt Showcases various assertion macros for checking boolean conditions, pointer validity, and string emptiness. Includes examples for failing and ignoring tests. ```c #include "unity.h" #include "sensor.h" void test_sensor_should_ReturnValidPointerOnInit(void) { Sensor *s = sensor_init(SENSOR_TYPE_TEMP); TEST_ASSERT_NOT_NULL(s); /* fails if s == NULL */ TEST_ASSERT_NOT_EMPTY(s->name); /* fails if s->name[0] == '\0' */ sensor_destroy(s); } void test_sensor_should_ReturnNullForInvalidType(void) { Sensor *s = sensor_init(SENSOR_TYPE_INVALID); TEST_ASSERT_NULL(s); /* fails if s != NULL */ } void test_sensor_isReady_should_ReturnTrueAfterWarmup(void) { Sensor *s = sensor_init(SENSOR_TYPE_TEMP); sensor_warmup(s, 100 /*ms*/); TEST_ASSERT_TRUE(sensor_is_ready(s)); sensor_destroy(s); } void test_feature_notYetImplemented(void) { TEST_IGNORE_MESSAGE("Calibration API not implemented yet"); } void test_process_should_FailOnCorruptPacket(void) { uint8_t bad_pkt[] = {0xFF, 0xFF}; if (packet_is_corrupt(bad_pkt, sizeof(bad_pkt))) { TEST_FAIL_MESSAGE("Corrupt packet was not rejected by handler"); } } ``` -------------------------------- ### Example of Generated Test Calls Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md This shows the C code that is generated by using the `TEST_CASE` macro with a test function. These calls are treated as independent unit tests by Unity. ```c test_demoParamFunction(1, 2, 5); test_demoParamFunction(10, 7, 20); ``` -------------------------------- ### Example Commit Message Format Source: https://github.com/throwtheswitch/unity/blob/master/docs/CONTRIBUTING.md Follow this format for commit messages, separating the subject from the body with a blank line. The body should explain the 'why' behind the change, not the 'what' or 'how'. ```git :palm_tree: Summary of Amazing Feature Here Add a more detailed explanation here, if necessary. Possibly give some background about the issue being fixed, etc. The body of the commit message can be several paragraphs. Further paragraphs come after blank lines and please do proper word-wrap. Wrap it to about 72 characters or so. In some contexts, the first line is treated as the subject of the commit and the rest of the text as the body. The blank line separating the summary from the body is critical (unless you omit the body entirely); various tools like `log`, `shortlog` and `rebase` can get confused if you run the two together. Explain the problem that this commit is solving. Focus on why you are making this change as opposed to how or what. The code explains how or what. Reviewers and your future self can read the patch, but might not understand why a particular solution was implemented. Are there side effects or other unintuitive consequences of this change? Here's the place to explain them. - Bullet points are awesome, too - A hyphen should be used for the bullet, preceded by a single space, with blank lines in between Note the fixed or relevant GitHub issues at the end: Resolves: #123 See also: #456, #789 ``` -------------------------------- ### Omit Unity Begin/End Calls Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Set `:omit_begin_end` to `true` to prevent `UnityBegin` and `UnityEnd` from being called for test state setup and cleanup. This can also be specified via the command prompt. ```text :omit_begin_end ``` -------------------------------- ### Unity Fixture Extension for Test Groups Source: https://context7.com/throwtheswitch/unity/llms.txt Use `unity_fixture.h` for CppUTest-style test groups, setup, and teardown functions. This approach is recommended for readers of James Grenning's 'Test-Driven Development for Embedded C' and supports a command-line runner. ```c /* test_led_fixture.c */ #include "unity_fixture.h" #include "led_driver.h" TEST_GROUP(LedDriver); TEST_SETUP(LedDriver) { LedDriver_Create(); /* called before each TEST() in this group */ } TEST_TEAR_DOWN(LedDriver) { LedDriver_Destroy(); /* called after each TEST() */ } TEST(LedDriver, AllLedsOffAfterCreate) { TEST_ASSERT_EQUAL_HEX16(0x0000, LedDriver_GetLeds()); } TEST(LedDriver, TurnOnLedOne) { LedDriver_TurnOn(1); TEST_ASSERT_EQUAL_HEX16(0x0001, LedDriver_GetLeds()); } TEST(LedDriver, TurnOffLedOne) { LedDriver_TurnOn(1); LedDriver_TurnOff(1); TEST_ASSERT_EQUAL_HEX16(0x0000, LedDriver_GetLeds()); } /* In a separate runner file: */ TEST_GROUP_RUNNER(LedDriver) { RUN_TEST_CASE(LedDriver, AllLedsOffAfterCreate); RUN_TEST_CASE(LedDriver, TurnOnLedOne); RUN_TEST_CASE(LedDriver, TurnOffLedOne); } ``` -------------------------------- ### Get Unity Test Runner Generator with Meson Source: https://github.com/throwtheswitch/unity/blob/master/docs/MesonGeneratorRunner.md Obtain the test runner generator from the Unity subproject in Meson. This is the first step to automating test runner creation. ```meson unity_proj = subproject('unity') runner_gen = unity_proj.get_variable('gen_test_runner') ``` -------------------------------- ### Generate Test Cases with TEST_CASE Macro Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Use the `TEST_CASE` macro to generate individual test calls for a parameterized test function. Each macro call creates one test instance with specified arguments. These generated calls are wrapped with standard Unity setup and teardown. ```c TEST_CASE(1, 2, 5) TEST_CASE(10, 7, 20) ``` -------------------------------- ### Build Project with Ninja Source: https://github.com/throwtheswitch/unity/blob/master/examples/example_4/readme.txt After setting up with Meson, use Ninja to build the project. Ensure you replace with your actual build directory. ```bash ninja -C ``` -------------------------------- ### Basic Unity main() Function Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityConfigurationGuide.md Initialize your system and run tests. Call UNITY_BEGIN() before tests and UNITY_END() after all tests have completed. The return value of UNITY_END() indicates the total number of failures. ```C int main(void) { UNITY_BEGIN(); RUN_TEST(test_TheFirst); RUN_TEST(test_TheSecond); RUN_TEST(test_TheThird); return UNITY_END(); } ``` -------------------------------- ### Unity Test File Structure and Runner Lifecycle Source: https://context7.com/throwtheswitch/unity/llms.txt Demonstrates the basic structure of a Unity test file, including includes, setup/teardown functions, test function declarations, and the main runner lifecycle. ```c /* test_calculator.c */ #include "unity.h" #include "calculator.h" /* module under test */ void setUp(void) { /* Called before EACH test function */ calculator_reset(); } void tearDown(void) { /* Called after EACH test function */ } void test_add_should_ReturnSumOfTwoPositiveIntegers(void) { TEST_ASSERT_EQUAL_INT(5, calculator_add(2, 3)); } void test_add_should_HandleNegativeNumbers(void) { TEST_ASSERT_EQUAL_INT(-1, calculator_add(2, -3)); } void test_divide_should_ReturnZeroOnDivisionByZero(void) { TEST_ASSERT_EQUAL_INT(0, calculator_divide(10, 0)); } int main(void) { UNITY_BEGIN(); /* initialize Unity internals */ RUN_TEST(test_add_should_ReturnSumOfTwoPositiveIntegers); RUN_TEST(test_add_should_HandleNegativeNumbers); RUN_TEST(test_divide_should_ReturnZeroOnDivisionByZero); return UNITY_END(); /* returns total number of failures */ } /* Expected output: test_calculator.c:16:test_add_should_ReturnSumOfTwoPositiveIntegers:PASS test_calculator.c:20:test_add_should_HandleNegativeNumbers:PASS test_calculator.c:24:test_divide_should_ReturnZeroOnDivisionByZero:PASS ----------------------- 3 Tests 0 Failures 0 Ignored OK */ ``` -------------------------------- ### Run Tests with Meson Source: https://github.com/throwtheswitch/unity/blob/master/examples/example_4/readme.txt Meson provides native support for running tests. Use this command to execute tests for your project. ```bash meson test -C ``` -------------------------------- ### Run Unity Test Summary Script on Windows Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Execute the script on a Windows system, specifying the build directory and root path using Windows-style path separators. ```Shell ruby unity_test_summary.rb build\test\ C:\projects\myproject\ ``` -------------------------------- ### Set Minimum CMake Version Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Specifies the minimum version of CMake required for this project. Ensure your CMake installation meets this requirement. ```cmake cmake_minimum_required(VERSION 3.12) ``` -------------------------------- ### Configure Build Options Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Sets up boolean options for enabling Unity extensions (fixture, memory) and 64-bit integer support. These options can be controlled at build time. ```cmake option(UNITY_EXTENSION_FIXTURE "Compiles Unity with the \"fixture\" extension." OFF) option(UNITY_EXTENSION_MEMORY "Compiles Unity with the \"memory\" extension." OFF) option(UNITY_SUPPORT_INT64 "Enable 64bit integer support. OFF means autodetect." OFF) ``` -------------------------------- ### Enable and Use UNITY_INCLUDE_PRINT_FORMATTED Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityConfigurationGuide.md Enable Unity's basic printf-like string output implementation. Ensure UNITY_SUPPORT_64 is true if using long long types for correct printing. ```c #define UNITY_INCLUDE_PRINT_FORMATTED int a = 0xfab1; TEST_PRINTF("Decimal %d\n", -7); TEST_PRINTF("Unsigned %u\n", 987); TEST_PRINTF("Float %f\n", 3.1415926535897932384); TEST_PRINTF("Binary %b\n", 0xA); TEST_PRINTF("Hex %X\n", 0xFAB); TEST_PRINTF("Pointer %p\n", &a); TEST_PRINTF("Character %c\n", 'F'); TEST_PRINTF("String %s\n", "My string"); TEST_PRINTF("Percent %%\n"); TEST_PRINTF("Unsigned long long %llu\n", 922337203685477580); TEST_PRINTF("Color Red \033[41mFAIL\033[0m\n"); TEST_PRINTF("\n"); TEST_PRINTF("Multiple (%d) (%i) (%u) (%x)\n", -100, 0, 200, 0x12345); ``` -------------------------------- ### Configure Source File Extensions Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Specify the pattern for matching acceptable source file extensions. The default accepts cpp, cc, C, c, and ino files. ```string '(?:cpp|cc|ino|C|c)' ``` -------------------------------- ### Configure Mock Prefix and Suffix in Ruby Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Unity automatically generates calls to Init, Verify, and Destroy for mock files. Configure the prefix and suffix to match your mock file naming conventions. ```Ruby :mock_prefix => "Mock", :mock_suffix => "" ``` -------------------------------- ### Generate Test Runner with YAML and Extra Headers Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Command-line usage including a YAML configuration file and additional header files to be included in the runner. Extra headers must follow the YAML file. ```Shell ruby generate_test_runner.rb TestFile.c my_config.yml extras.h ``` -------------------------------- ### Conditional Build Messages Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Prints status messages to the console if specific Unity extensions or features are enabled during the build configuration. This provides feedback on the build setup. ```cmake if(${UNITY_EXTENSION_FIXTURE}) message(STATUS "Unity: Building with the fixture extension.") endif() if(${UNITY_EXTENSION_MEMORY}) message(STATUS "Unity: Building with the memory extension.") endif() if(${UNITY_SUPPORT_INT64}) message(STATUS "Unity: Building with 64bit integer support.") endif() ``` -------------------------------- ### Enable 64-bit Support in Unity Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityConfigurationGuide.md Define UNITY_SUPPORT_64 to enable 64-bit support if it's not automatically detected by Unity (e.g., through pointer width or integer sizes). Be mindful of potential size and speed impacts on small targets. ```c #define UNITY_SUPPORT_64 ``` -------------------------------- ### Run Unity Test Summary Script with Root Path Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Execute the script with a build directory and an optional root path. This is useful for integrating with IDEs that use relative paths. ```Shell ruby unity_test_summary.rb build/test/ ~/projects/myproject/ ``` -------------------------------- ### Run Unity Test Summary Script Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Execute the script with a specified build directory. This is the basic usage for aggregating test results. ```Shell ruby unity_test_summary.rb build/test/ ``` -------------------------------- ### RUN_TEST Macro Variants Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityGettingStartedGuide.md Two variants of the RUN_TEST macro are available for executing test functions. The classic variant includes a line number, while the simpler replacement starts from the beginning of the function. ```C RUN_TEST(func, linenum) ``` ```C RUN_TEST(func) ``` -------------------------------- ### Provide Main Export Declaration Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Use `main_export_decl` to provide any `cdecl` for the `main()` test function. It is empty by default. ```text main_export_decl ``` -------------------------------- ### Construct Absolute Path for Test File in Meson Source: https://github.com/throwtheswitch/unity/blob/master/docs/MesonGeneratorRunner.md Get the absolute path of your test file using `meson.source_root()`. This is necessary because the generator requires the full path, which can be tricky with Meson subprojects. ```meson test_runner = meson.source_root() / 'test/test_example.c' ``` -------------------------------- ### Instantiate Generator for Multiple Runners Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Ruby code demonstrating how to instantiate `UnityTestRunnerGenerator` with options and then use it to generate multiple test runners for different test files. ```Ruby gen = UnityTestRunnerGenerator.new(options) test_files.each do |f| gen.run(f, File.basename(f,'.c')+"Runner.c") end ``` -------------------------------- ### Unity Command Line Arguments Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md List of available command-line options for modifying test execution. These options require Unity to be compiled with UNITY_USE_COMMAND_LINE_ARGS defined. ```text | Option | Description | | --------- | ------------------------------------------------- | | `-l` | List all tests and exit | | `-f NAME` | Filter to run only tests whose name includes NAME | | `-n NAME` | Run only the test named NAME | | `-h` | show the Help menu that lists these options | | `-q` | Quiet/decrease verbosity | | `-v` | increase Verbosity | | `-x NAME` | eXclude tests whose name includes NAME | ``` -------------------------------- ### Configure Header File Extensions Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Specify the pattern for matching acceptable header file extensions. The default accepts hpp, hh, H, and h files. ```string '(?:hpp|hh|H|h)' ``` -------------------------------- ### C Integer Size Ordering Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityAssertionsReference.md Illustrates the standard ordering of integer types in C. This is guaranteed by the C standard. ```C char <= short <= int <= long <= long long ``` -------------------------------- ### Configure Custom Serial Output with Unity Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityConfigurationGuide.md Define UNITY_OUTPUT_CHAR, UNITY_OUTPUT_START, UNITY_OUTPUT_FLUSH, and UNITY_OUTPUT_COMPLETE to route test results to a custom serial function instead of stdout. This is useful for embedded systems lacking stdout support. ```c #include "RS232_header.h" ... #define UNITY_OUTPUT_CHAR(a) RS232_putc(a) #define UNITY_OUTPUT_START() RS232_config(115200,1,8,0) #define UNITY_OUTPUT_FLUSH() RS232_flush() #define UNITY_OUTPUT_COMPLETE() RS232_close() ``` -------------------------------- ### Enable Command Line Arguments Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md When set to true, the generated test runner can accept options to modify how tests are run. Ensure Unity is compiled with UNITY_USE_COMMAND_LINE_ARGS defined. ```C #define UNITY_USE_COMMAND_LINE_ARGS ``` -------------------------------- ### Generate Test Runner from Command Line Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Basic command-line usage for `generate_test_runner.rb` to create a test runner file. Specify the test file and the desired runner file name. ```Shell ruby generate_test_runner.rb TestFile.c NameOfRunner.c ``` -------------------------------- ### Define Unity Project Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Defines the project name as 'unity' with its version derived from the header file and specifies the programming language as C. Includes a description for the project. ```cmake project(unity VERSION ${UNITY_HEADER_VERSION_MAJOR}.${UNITY_HEADER_VERSION_MINOR}.${UNITY_HEADER_VERSION_BUILD} LANGUAGES C DESCRIPTION "C Unit testing framework." ) ``` -------------------------------- ### Parameterized Tests with TEST_CASE, TEST_RANGE, TEST_MATRIX Source: https://context7.com/throwtheswitch/unity/llms.txt Enable parameterized tests by defining `UNITY_SUPPORT_TEST_CASES` and passing `--use_param_tests=1` to the runner generator. Use `TEST_CASE` for specific argument sets, `TEST_RANGE` for numeric sweeps, and `TEST_MATRIX` for Cartesian products. ```c /* test_math_params.c — compile with UNITY_SUPPORT_TEST_CASES defined */ #include "unity.h" #include "calculator.h" /* Each TEST_CASE generates one independent test invocation */ TEST_CASE(2, 3, 5) TEST_CASE(0, 0, 0) TEST_CASE(-1, 1, 0) TEST_CASE(100, -50, 50) void test_add_should_ReturnCorrectSum(int a, int b, int expected) { TEST_ASSERT_EQUAL_INT(expected, calculator_add(a, b)); } /* TEST_RANGE: [start, stop, step] inclusive / exclusive */ TEST_RANGE([1, 5, 1]) /* a in {1,2,3,4,5} */ void test_factorial_should_BePositive(int n) { TEST_ASSERT_GREATER_THAN_INT(0, factorial(n)); } /* TEST_MATRIX: all combinations of [vals_a] x [vals_b] — 2*3 = 6 tests */ TEST_MATRIX([1, 2], [10, 20, 30]) void test_multiply_should_BeCommutative(int a, int b) { TEST_ASSERT_EQUAL_INT(calculator_mul(a, b), calculator_mul(b, a)); } /* Expected runner output (partial): test_math_params.c:9:test_add_should_ReturnCorrectSum(2, 3, 5):PASS test_math_params.c:9:test_add_should_ReturnCorrectSum(0, 0, 0):PASS test_math_params.c:9:test_add_should_ReturnCorrectSum(-1, 1, 0):PASS test_math_params.c:9:test_add_should_ReturnCorrectSum(100, -50, 50):PASS */ ``` -------------------------------- ### Define Individual Test Cases with TEST_CASE Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Generate individual TEST_CASE commands from the parameters defined by TEST_RANGE. Each TEST_CASE represents a specific test execution. ```C TEST_CASE(3, 10, 30) ``` ```C TEST_CASE(3, 8, 30) ``` ```C TEST_CASE(3, 6, 30) ``` ```C TEST_CASE(4, 10, 30) ``` ```C TEST_CASE(4, 8, 30) ``` ```C TEST_CASE(4, 6, 30) ``` -------------------------------- ### Signed and Unsigned Integer Equality Assertions Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityAssertionsReference.md A comprehensive set of macros for comparing signed and unsigned integers of various bit widths (8, 16, 32, 64, and default/platform-specific). These assertions are crucial for verifying the exact numerical equality between expected and actual integer values. ```APIDOC ## Signed and Unsigned Integers (of all sizes) Large integer sizes can be disabled for build targets that do not support them. For example, if your target only supports up to 16 bit types, by defining the appropriate symbols Unity can be configured to omit 32 and 64 bit operations that would break compilation (see Unity documentation for more). Refer to Advanced Asserting later in this document for advice on dealing with other word sizes. #### `TEST_ASSERT_EQUAL_INT (expected, actual)` #### `TEST_ASSERT_EQUAL_INT8 (expected, actual)` #### `TEST_ASSERT_EQUAL_INT16 (expected, actual)` #### `TEST_ASSERT_EQUAL_INT32 (expected, actual)` #### `TEST_ASSERT_EQUAL_INT64 (expected, actual)` #### `TEST_ASSERT_EQUAL_UINT (expected, actual)` #### `TEST_ASSERT_EQUAL_UINT8 (expected, actual)` #### `TEST_ASSERT_EQUAL_UINT16 (expected, actual)` #### `TEST_ASSERT_EQUAL_UINT32 (expected, actual)` #### `TEST_ASSERT_EQUAL_UINT64 (expected, actual)` ``` -------------------------------- ### Assertion Parameter Convention Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityAssertionsReference.md The general order for assertion parameters in Unity's assertion library. ```c TEST_ASSERT_X( {modifiers}, {expected}, actual, {size/count} ) ``` -------------------------------- ### Enable Parameterized Tests Source: https://github.com/throwtheswitch/unity/blob/master/docs/UnityHelperScriptsGuide.md Enable parameterized test usage, allowing tests to accept arguments from TEST_CASE and TEST_RANGE macros. Ensure UNITY_SUPPORT_TEST_CASES is defined for successful compilation. ```C #define UNITY_USE_PARAMETRIZED_TESTS ``` -------------------------------- ### Set Target Properties Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Configures properties for the project target, including C standard version, requirement, extensions, and public header list. ```cmake set_target_properties(${PROJECT_NAME} PROPERTIES C_STANDARD 11 C_STANDARD_REQUIRED ON C_EXTENSIONS OFF PUBLIC_HEADER "${${PROJECT_NAME}_PUBLIC_HEADERS}" EXPORT_NAME framework ) ``` -------------------------------- ### Read Unity Version from Header Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Reads the Unity version (MAJOR, MINOR, BUILD) from the src/unity.h file using regular expressions. This ensures the project version matches the header. ```cmake set(UNITY_HEADER "src/unity.h") file(STRINGS "${UNITY_HEADER}" UNITY_HEADER_CONTENT REGEX "^#define UNITY_VERSION_(MAJOR|MINOR|BUILD) +[0-9]+$" ) set(UNITY_HEADER_VERSION_MAJOR 0) set(UNITY_HEADER_VERSION_MINOR 0) set(UNITY_HEADER_VERSION_BUILD 0) foreach(VERSION_LINE IN LISTS UNITY_HEADER_CONTENT) foreach(VERSION_PART MAJOR MINOR BUILD) string(CONCAT REGEX_STRING "#define UNITY_VERSION_" "${VERSION_PART}" " +([0-9]+)" ) if(VERSION_LINE MATCHES "${REGEX_STRING}") set(UNITY_HEADER_VERSION_${VERSION_PART} "${CMAKE_MATCH_1}") endif() endforeach() endforeach() ``` -------------------------------- ### Generate Package Version File Source: https://github.com/throwtheswitch/unity/blob/master/CMakeLists.txt Creates a CMake configuration version file used for package management and version checking with find_package(). ```cmake write_basic_package_version_file(${PROJECT_NAME}ConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion ) ``` -------------------------------- ### Unity Integer Range and Comparison Assertions Source: https://context7.com/throwtheswitch/unity/llms.txt Verify that a value falls within a specified range using TEST_ASSERT_INT_WITHIN or check ordering relationships with GREATER_THAN, LESS_THAN, and their variants. Size-specific macros are available. ```c #include "unity.h" #include "adc.h" void test_adc_reading_should_BeWithinCalibrationTolerance(void) { int32_t reading = adc_read_channel(0); /* Value must be 1000 ± 50, i.e. in range [950, 1050] */ TEST_ASSERT_INT32_WITHIN(50, 1000, reading); } void test_pwm_duty_should_BePositive(void) { uint16_t duty = pwm_get_duty_cycle(); TEST_ASSERT_GREATER_THAN_UINT16(0, duty); /* duty > 0 */ TEST_ASSERT_LESS_OR_EQUAL_UINT16(1000, duty); /* duty <= 1000 */ } void test_temperature_should_BeInSafeOperatingRange(void) { int16_t temp_c = temp_sensor_read(); TEST_ASSERT_GREATER_OR_EQUAL_INT16(-40, temp_c); /* temp >= -40°C */ TEST_ASSERT_LESS_THAN_INT16(125, temp_c); /* temp < 125°C */ } ``` -------------------------------- ### Unity Integer Equality Assertions Source: https://github.com/throwtheswitch/unity/blob/master/README.md Compare integers for equality. Variants exist for specific bit sizes and for displaying values as signed, unsigned, or hexadecimal. TEST_ASSERT_EQUAL is an alias for TEST_ASSERT_EQUAL_INT. ```c TEST_ASSERT_EQUAL_INT(expected, actual) TEST_ASSERT_EQUAL_INT8(expected, actual) TEST_ASSERT_EQUAL_INT16(expected, actual) TEST_ASSERT_EQUAL_INT32(expected, actual) TEST_ASSERT_EQUAL_INT64(expected, actual) Compare two integers for equality and display errors as signed integers. A cast will be performed to your natural integer size so often this can just be used. When you need to specify the exact size, you can use a specific version. ``` ```c TEST_ASSERT_EQUAL_UINT(expected, actual) TEST_ASSERT_EQUAL_UINT8(expected, actual) TEST_ASSERT_EQUAL_UINT16(expected, actual) TEST_ASSERT_EQUAL_UINT32(expected, actual) TEST_ASSERT_EQUAL_UINT64(expected, actual) Compare two integers for equality and display errors as unsigned integers. Like INT, there are variants for different sizes also. ``` ```c TEST_ASSERT_EQUAL_HEX(expected, actual) TEST_ASSERT_EQUAL_HEX8(expected, actual) TEST_ASSERT_EQUAL_HEX16(expected, actual) TEST_ASSERT_EQUAL_HEX32(expected, actual) TEST_ASSERT_EQUAL_HEX64(expected, actual) Compares two integers for equality and display errors as hexadecimal. Like the other integer comparisons, you can specify the size... here the size will also affect how many nibbles are shown (for example, `HEX16` will show 4 nibbles). ``` ```c TEST_ASSERT_EQUAL(expected, actual) Another way of calling TEST_ASSERT_EQUAL_INT ```