### CMockGenerator Initialization Example Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md Example demonstrating how to create and initialize a CMockGenerator instance with necessary dependencies. ```ruby config = CMockConfig.new file_writer = CMockFileWriter.new(config) utils = CMockGeneratorUtils.new(config) plugins = CMockPluginManager.new(config, utils) generator = CMockGenerator.new(config, file_writer, utils, plugins) ``` -------------------------------- ### Example CMockPluginManager Initialization Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockPluginManager.md Demonstrates how to create a CMockPluginManager with specific plugins configured. This example shows the instantiation of CMockConfig and CMockGeneratorUtils, followed by the creation of the plugin manager. ```ruby config = CMockConfig.new(:plugins => [:array, :callback]) utils = CMockGeneratorUtils.new(config) plugin_mgr = CMockPluginManager.new(config, utils) # Loads: expect, array, callback (in priority order) ``` -------------------------------- ### Install CMock via Gem or Git Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Instructions for installing CMock using either the Ruby gem or by cloning the Git repository. ```bash # Via gem gem install cmock # Via git clone git clone --recursive https://github.com/throwtheswitch/cmock.git ``` -------------------------------- ### Example: main Function Cleanup Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockRuntime.md Shows how to call CMock_Guts_MemFreeFinal after running tests in the main function for final resource deallocation. ```c int main(void) { UNITY_BEGIN(); // Run tests... int result = UNITY_END(); CMock_Guts_MemFreeFinal(); return result; } ``` -------------------------------- ### Example Function Prototype Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md This is an example of a function prototype that CMock can process. ```c int DoesSomething(int a, int b); ``` -------------------------------- ### Example Iteration over Plugins Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockPluginManager.md Shows how to access the `plugins` attribute of a CMockPluginManager instance and iterate over each plugin to display its class name and priority. ```ruby plugin_mgr = CMockPluginManager.new(config, utils) plugin_mgr.plugins.each do |plugin| puts plugin.class.name puts "Priority: #{plugin.priority}" end ``` -------------------------------- ### Install RubyGems for CMock Development Source: https://github.com/throwtheswitch/cmock/blob/master/README.md Install all necessary RubyGems for contributing to or testing CMock. ```bash bundle install ``` -------------------------------- ### Example Usage of CMockPluginManager.run Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockPluginManager.md Demonstrates how to instantiate CMockPluginManager and use the run method with and without arguments to collect mock code generation results from plugins. ```ruby plugin_mgr = CMockPluginManager.new(config, utils) # Invoke method with no arguments result = plugin_mgr.run(:mock_function_declarations) # Invoke method with function data result = plugin_mgr.run(:mock_implementation, function_data) # Result is concatenated output from all plugins that implement the method mock_code = result # Combined C code from all plugins ``` -------------------------------- ### CMockFileWriter Usage Example Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Demonstrates the complete workflow of using CMockFileWriter, including configuration, directory creation, writing mock files, creating and appending to skeleton files, and checking file paths. ```ruby # Setup config = CMockConfig.new({ :mock_path => 'test/mocks', :skeleton_path => 'test/skeletons', :subdir => 'generated' }) writer = CMockFileWriter.new(config) # Create directories writer.create_subdir(nil) writer.create_skeleton_subdir(nil) writer.create_subdir('drivers') # Create mock file writer.create_file('Mocked.h', 'drivers') do |file, name| file << "#ifndef MOCK_H\n" file << "#define MOCK_H\n" file << "// mock content\n" file << "#endif\n" end # Create skeleton file writer.create_skeleton_file('stub.c', 'drivers') do |file, name| file << "// Skeleton code\n" end # Append to existing skeleton writer.append_file('stub.c', 'drivers') do |file, name| file << "// Additional implementation\n" end # Check path path = writer.skeleton_file_path('stub.c', 'drivers') # => 'test/skeletons/generated/drivers/stub.c' ``` -------------------------------- ### Example Usage of ptr_or_str? Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGeneratorUtils.md Provides examples of calling the `ptr_or_str?` method with different C type strings to demonstrate its boolean return values. ```ruby utils.ptr_or_str?('int*') # => true utils.ptr_or_str?('void*') # => true utils.ptr_or_str?('char*') # => true utils.ptr_or_str?('int') # => false utils.ptr_or_str?('my_handle_t') # => depends on treat_as mapping ``` -------------------------------- ### CMock Generator Setup and Usage Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md Demonstrates the complete process of setting up CMock, parsing a C header file, and generating a mock file. This is useful for integrating mock objects into your test suite. ```ruby # Setup config = CMockConfig.new({ :mock_path => 'test/mocks', :plugins => [:array, :callback], :enforce_strict_ordering => true }) file_writer = CMockFileWriter.new(config) utils = CMockGeneratorUtils.new(config) plugins = CMockPluginManager.new(config, utils) generator = CMockGenerator.new(config, file_writer, utils, plugins) parser = CMockHeaderParser.new(config) # Parse header header = File.read('src/calculator.h') parsed = parser.parse('calculator', header) # Generate mock generator.create_mock('calculator', parsed, '.h') # Now test can include Mockcalculator.h and use: # - add_Expect(1, 2) # - add_ExpectAndReturn(1, 2, 3) # - Mock_calculator_Verify() ``` -------------------------------- ### Ceedling Installation Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Install Ceedling, a test harness that includes CMock, via the command line. ```bash gem install ceedling ``` -------------------------------- ### Stop Ignore Example 1 (Works) Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Demonstrates the correct usage of StopIgnore where it immediately cancels the ignore, allowing subsequent expectations to be set. ```c Blah_Ignore(); funcThatMightCallBlahButWeDoNotCare(); Blah_StopIgnore(); funcThatWeWantToMakeSureDoesNotCallBlah(); ``` -------------------------------- ### Example: Generate Verification Code Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGeneratorUtils.md Illustrates generating C code for verifying a specific function argument's expectation using `code_verify_an_arg_expectation`. ```ruby # Generate verification code function = { :name => 'process', :args => [...] } arg = { :name => 'value', :type => 'int', :ptr? => false } verification_code = utils.code_verify_an_arg_expectation(function, arg) ``` -------------------------------- ### CMock Usage via Command Line Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Examples of using the CMock executable from the command line to generate mocks or configuration files. ```bash # Command line ruby lib/cmock.rb --mock_path=mocks src/calculator.h ruby lib/cmock.rb -ocmock.yml src/calculator.h ``` -------------------------------- ### CMock Module Verification Example Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md Shows the structure of a generated verification function for a mocked module, used to ensure all expectations were met. ```c void Mock_calculator_Verify(void) { // Verify each queued expectation was matched } ``` -------------------------------- ### Example: tearDown Function Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockRuntime.md Demonstrates the usage of CMock_Guts_MemFreeAll within a tearDown function to clean up mock state between tests. ```c void tearDown(void) { Mock_add_Verify(); Mock_add_Destroy(); CMock_Guts_MemFreeAll(); } ``` -------------------------------- ### Strict Ordering Example (C) Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Demonstrates the use of strict ordering in CMock. Incorrect call order will result in an error upon `Mock_Verify()`. ```c add_ExpectAndReturn(1, 2, 3); multiply_ExpectAndReturn(3, 4, 12); multiply(3, 4); // ERROR: wrong order add(1, 2); Mock_Verify(); ``` -------------------------------- ### Example: Generate Base Expectation Code Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGeneratorUtils.md Demonstrates generating the initial C code for setting up a function's base expectation using `code_add_base_expectation`. ```ruby # Generate memory allocation code init_code = utils.code_add_base_expectation('process') ``` -------------------------------- ### Example: Generate Argument Declaration Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGeneratorUtils.md Shows how to generate a C declaration for a function argument, including array dimensions and `const` qualifiers. ```ruby # Generate declarations arg_array = { :name => 'buffer', :type => 'int', :array_dims => [10, 20], :const? => true } puts utils.arg_declaration(arg_array) # => "const int buffer[10][20]" ``` -------------------------------- ### Complete CMock YAML Configuration Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/configuration.md This is a full example of a CMock configuration file in YAML format. It demonstrates all available options for customizing mock generation, including paths, framework settings, plugins, type mappings, and include paths. ```yaml :cmock: # File paths :mock_path: 'test/mocks' :skeleton_path: 'test/skeletons' :mock_prefix: 'Mock' :mock_suffix: '' :subdir: 'generated' :weak: '' # Framework and behavior :framework: :unity :verbosity: 2 :enforce_strict_ordering: false :fail_on_unexpected_calls: true :when_no_prototypes: :warn :when_ptr: :smart # Plugins :plugins: - :array - :callback - :cexception - :expect_any_args # Type handling :treat_as: 'custom_status_t': 'INT' 'my_handle_t': 'HEX32' :treat_as_array: {} :treat_as_void: - 'void' :memcmp_if_unknown: true # Parser :attributes: - __ramfunc - __irq - __fiq - register - extern :c_calling_conventions: - __stdcall - __cdecl - __fastcall :strippables: - '(?:__attribute__\s*\([ (]*.*?[ )]*\)+)' :treat_externs: :exclude :treat_inlines: :exclude # Array support :array_size_name: 'size|len|count' :array_size_type: - 'size_t' # Includes :includes: - 'project_types.h' :includes_h_pre_orig_header: - 'stdint.h' :includes_h_post_orig_header: [] :includes_c_pre_header: [] :includes_c_post_header: - 'project_config.h' :unity_helper_path: [] # Callback behavior :callback_include_count: true :callback_after_arg_check: false # Other :exclude_setjmp_h: false :create_error_stubs: true :skeleton: false :debug_output: false ``` -------------------------------- ### CMock Memory Allocation Example Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md Demonstrates how to allocate memory for a call instance using CMock's internal memory management functions. ```c CMOCK_MEM_INDEX_TYPE cmock_guts_index = CMock_Guts_MemNew( sizeof(CMOCK_func_CALL_INSTANCE) ); void* addr = CMock_Guts_GetAddressFor(cmock_guts_index); Mock.func_CallInstance = CMock_Guts_MemChain( Mock.func_CallInstance, cmock_guts_index ); ``` -------------------------------- ### Mock Source File Structure (C) Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md This is an example of a generated mock source file. It provides the actual mock implementations, including argument verification, call count checks, and return value handling based on set expectations. It also contains the definitions for control and verification interfaces. ```c #include "Mockcalculator.h" #include "unity.h" static struct { CMOCK_add_CALL_INSTANCE* add_CallInstance; // ... more fields ... } Mock; // Actual mock implementation replacing original function: int add(int a, int b) { CMOCK_add_CALL_INSTANCE* cmock_call_instance = /* ... */; // Verify arguments // Verify call count // Return value from expectation } // Control interfaces: void add_Expect(int a, int b) { /* ... */ } void add_ExpectAndReturn(int a, int b, int return_value) { /* ... */ } // Verification: void Mock_add_VerifyAll(void) { /* ... */ } ``` -------------------------------- ### Mock Header File Structure (C) Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md This is an example of a generated mock header file. It declares mock functions with various expectation setting methods (e.g., `_Expect`, `_ExpectAndReturn`, `_Ignore`) and provides interfaces for verification and initialization. ```c #ifndef MOCKCALCULATOR_H #define MOCKCALCULATOR_H #include "unity.h" #include "calculator.h" // Mock function declarations for control: void add_Expect(int a, int b); void add_ExpectAndReturn(int a, int b, int return_value); void add_ExpectAnyArgs(void); void add_ExpectAnyArgsAndReturn(int return_value); void add_Ignore(void); void add_IgnoreAndReturn(int return_value); void add_StopIgnore(void); // Verification and initialization: void Mock_add_VerifyAll(void); void Mock_add_Init(void); void Mock_add_Destroy(void); // Typedef for instance tracking (if expect plugin enabled): typedef struct { UNITY_LINE_TYPE LineNumber; int Expected_a; int Expected_b; int ReturnVal; // ... plugin-generated fields ... } CMOCK_add_CALL_INSTANCE; #endif ``` -------------------------------- ### CMock Expect Array Example Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Demonstrates how CMock handles array arguments with `_Expect` calls, comparing it to `_ExpectWithArray`. Use this when verifying function calls with array parameters. ```c Banana b[2] = {GreenBanana, YellowBanana}; GoBananas_Expect(b, 2); ``` ```c GoBananas_ExpectWithArray(b, 2, 2); ``` -------------------------------- ### Example: Type Handling with Const Pointer Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGeneratorUtils.md Demonstrates how to use `arg_type_with_const` to format a C argument type, including handling `const` qualifiers for pointers. ```ruby # Setup config = CMockConfig.new(:plugins => [:array, :expect_any_args]) utils = CMockGeneratorUtils.new(config) # Type handling arg_with_const = { :type => 'int*', :const_ptr? => true, :volatile? => false } puts utils.arg_type_with_const(arg_with_const) # => "int* const" ``` -------------------------------- ### Example Usage of create_mock Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md Instantiate CMockGenerator and use the create_mock method with parsed header data to generate mock files in a specified subdirectory. ```ruby generator = CMockGenerator.new(config, file_writer, utils, plugins) parsed = parser.parse('calculator', header_source) generator.create_mock('calculator', parsed, '.h', 'math_subsystem') # Generates: # - mocks/math_subsystem/Mockcalculator.h # - mocks/math_subsystem/Mockcalculator.c ``` -------------------------------- ### Example Commit Message Structure Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CONTRIBUTING.md Illustrates the recommended format for commit messages, including a subject line, a blank line, and a detailed body explaining the 'why' behind the change. It also shows how to reference issues. ```text :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 ``` -------------------------------- ### CMock Configuration Options (YAML) Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Define CMock configuration options in a YAML file. This example sets attributes and pointer comparison behavior, mirroring the Ruby syntax. ```yaml :cmock: :attributes: - __funky - __intrinsic :when_ptr: :compare ``` -------------------------------- ### CMock Test Case Example in C Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md A C test case demonstrating how to use CMock generated interfaces to set expectations, call the function under test, and verify results. ```c #include "unity.h" #include "Mockcalculator.h" void test_add_positive_numbers(void) { // Expect add(2, 3) to be called, return 5 add_ExpectAndReturn(2, 3, 5); // Call function under test int result = calculator_sum(2, 3); // Verify result TEST_ASSERT_EQUAL_INT(5, result); // Verify expectations met Mock_calculator_Verify(); } void tearDown(void) { CMock_Guts_MemFreeAll(); } ``` -------------------------------- ### Integrate CMock with Makefiles Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Use Makefiles to automatically generate mocks from header files and compile tests. This example shows how to define mock targets and link test executables. ```makefile MOCKS = $(patsubst src/%.h,build/Mock%.h,$(HEADERS)) $(MOCKS): build/Mock%.h: src/%.h ruby lib/cmock.rb --mock_path=build $< test: $(MOCKS) gcc -I. -Ibuild $(TEST_SRC) -o test ./test ``` -------------------------------- ### CMock Expect Interface Examples Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md Use these interfaces to queue expectations for function calls, specifying arguments and return values. Multiple calls queue expectations in order. ```c // For void return, void args: void func_Expect(void); ``` ```c // For void return, with args: void func_Expect(param1_type param1, ...); ``` ```c // For return value, void args: void func_ExpectAndReturn(return_type return_value); ``` ```c // For return value and args: void func_ExpectAndReturn(param1_type param1, ..., return_type return_value); ``` -------------------------------- ### Example Usage of create_skeleton Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md Parse header data for a module and then use create_skeleton to generate a skeleton C file. This file can be manually completed with actual function implementations. ```ruby parsed = parser.parse('mymodule', header_source) generator.create_skeleton('mymodule', parsed) # Generates (or appends to): # - skeletons/mymodule.c ``` -------------------------------- ### setup_mocks Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMock.md Generates mock implementations for the given header files. Accepts either a single file path or multiple file paths. ```APIDOC ## setup_mocks(files, folder = nil) ### Description Parses C header file(s) and generates corresponding mock implementations. Accepts either a single file path (String) or multiple file paths (Array). Internally normalizes input to Array for consistent processing. ### Parameters #### Path Parameters - **files** (String or Array) - Required - Header file path(s) to mock - **folder** (String) - Optional - Subdirectory within mock_path where mocks will be written ### Request Example ```ruby cmock = CMock.new cmock.setup_mocks('src/calculator.h') cmock.setup_mocks(['src/drivers/sensor.h', 'src/drivers/display.h']) cmock.setup_mocks('src/networking.h', 'network_subsystem') ``` ``` -------------------------------- ### Using CMockPluginManager Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockPluginManager.md Demonstrates configuring CMock with plugins, initializing the plugin manager, and running plugins to generate mock code. Use this to integrate CMock's plugin system into your build process. ```ruby config = CMockConfig.new({ :plugins => [:array, :callback, :expect_any_args] }) utils = CMockGeneratorUtils.new(config) plugin_mgr = CMockPluginManager.new(config, utils) plugin_mgr.plugins.each do |plugin| puts "#{plugin.class.name} (priority: #{plugin.priority})" end function_data = { :name => 'add', :args => [...] } declarations = plugin_mgr.run(:mock_function_declarations, function_data) implementation = plugin_mgr.run(:mock_implementation, function_data) interfaces = plugin_mgr.run(:mock_interfaces, function_data) puts declarations puts implementation ``` -------------------------------- ### Enable Debug Output in CMock Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md When enabled, the generated mock will emit a TEST_MESSAGE for each mock setup call and each actual mock invocation. This aids in diagnosing the order of mock call setup and execution. ```yaml :debug_output: true ``` -------------------------------- ### Initialize CMockConfig and Access Options Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockConfig.md Demonstrates how to create a CMockConfig instance and access its default configuration values for mock path, prefix, and plugins. ```ruby config = CMockConfig.new config.mock_path # => 'mocks' config.mock_prefix # => 'Mock' config.plugins # => [] ``` -------------------------------- ### CMock Configuration Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/INDEX.md Details on all configuration options available for CMock, including methods and examples. ```APIDOC ## CMock Configuration ### Description Details all configuration options for CMock, including methods of configuration, option categories, examples, and default values. ### Configuration Methods 1. Hash dictionary 2. YAML file 3. Command-line arguments 4. Default options ### Option Categories - File and path (mock_path, mock_prefix, etc.) - Framework and behavior (framework, verbosity, ordering, etc.) - Plugins (which to enable) - Type handling (treat_as, treat_as_array, treat_as_void) - Parser rules (attributes, calling conventions, strippables) - Array support (array_size_name, array_size_type) - Include configuration (pre/post header includes) - Callback behavior (callback_include_count, etc.) - Other options (skeleton mode, debug output, etc.) ### Complete Examples - Minimal configuration - Full YAML example - Ruby hash example - Command-line override ### Default Values - Complete CMOCK_DEFAULT_OPTIONS listing - Override instructions ### When to use Configuring CMock for your project. ``` -------------------------------- ### Override CMOCK_MEM_INDEX_TYPE for 32-bit Systems Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockRuntime.md Example of overriding the CMOCK_MEM_INDEX_TYPE to unsigned int, typically for 32-bit systems. ```c #define CMOCK_MEM_INDEX_TYPE unsigned int ``` -------------------------------- ### setup_skeletons Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMock.md Generates skeleton function implementations for the given header files. Creates skeleton C source files based on function declarations in header files. ```APIDOC ## setup_skeletons(files) ### Description Creates skeleton C source files based on function declarations in header files. Skeleton files provide function stubs that can be manually implemented. Does not overwrite existing skeleton files; appends new functions only. ### Parameters #### Path Parameters - **files** (String or Array) - Required - Header file path(s) to create skeletons for ### Request Example ```ruby cmock = CMock.new(:skeleton_path => 'src/skeletons') cmock.setup_skeletons('src/mymodule.h') cmock.setup_skeletons(['src/module1.h', 'src/module2.h']) ``` ``` -------------------------------- ### Get CMockFileWriter Configuration Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Instantiate CMockFileWriter and access its configuration object to retrieve settings such as the mock path. ```ruby writer = CMockFileWriter.new(config) puts writer.config.mock_path # => 'mocks' ``` -------------------------------- ### Initialize CMock with Default Options Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMock.md Use this snippet to create a CMock instance with all default configuration settings. ```ruby # Using default options cmock = CMock.new ``` -------------------------------- ### Test Case with Multiple Expectations Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md This example demonstrates queuing multiple expectations for a mocked function within a test. ```c test_CallsDoesSomething_ShouldDoJustThat(void) { DoesSomething_ExpectAndReturn(1,2,3); DoesSomething_ExpectAndReturn(4,5,6); DoesSomething_ExpectAndThrow(7,8, STATUS_ERROR_OOPS); CallsDoesSomething( ); } ``` -------------------------------- ### Increase CMock Memory Size Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockRuntime.md Example of increasing the CMock memory size to 64KB to resolve out-of-memory issues. ```c #define CMOCK_MEM_SIZE (65536) // 64KB ``` -------------------------------- ### Create Mock File with Base Path Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Demonstrates creating a mock file in the base mock path configured for the writer. ```ruby # Base path config = CMockConfig.new(:mock_path => 'build/mocks') writer = CMockFileWriter.new(config) writer.create_file('Mocked.h', nil) # => build/mocks/Mocked.h ``` -------------------------------- ### Ruby Version Check Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Verify if Ruby is installed and its version. CMock requires Ruby version 3.0.0 or higher. ```bash ruby --version ``` -------------------------------- ### Create Mock File with Configured Subdirectory Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Illustrates creating a mock file within a subdirectory specified in the CMockConfig, in addition to the base mock path. ```ruby # With subdir in config config = CMockConfig.new(:mock_path => 'build/mocks', :subdir => 'generated') writer = CMockFileWriter.new(config) writer.create_file('Mocked.h', 'subsystem') # => build/mocks/generated/subsystem/Mocked.h ``` -------------------------------- ### Run CMock Self Tests Source: https://github.com/throwtheswitch/cmock/blob/master/README.md Execute all CMock self-tests after installing dependencies. This is typically done from the 'test' directory. ```bash cd test rake ``` -------------------------------- ### Basic CMock Usage in Ruby Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Demonstrates how to initialize CMock in a Ruby script and set up mocks for a C header file. ```ruby # Ruby script require 'lib/cmock' cmock = CMock.new({ :mock_path => 'mocks', :mock_prefix => 'Mock', :plugins => [:array, :callback] }) cmock.setup_mocks('src/calculator.h') ``` -------------------------------- ### Initialize CMockHeaderParser and Parse Header Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockHeaderParser.md Demonstrates initializing CMockHeaderParser with custom configuration options and then parsing a C header source string. The parsed function and argument details are then iterated and printed. ```ruby # Initialize parser config = CMockConfig.new({ :when_no_prototypes => :warn, :treat_inlines => :include, :treat_externs => :include, :array_size_name => 'size|len|count', :attributes => ['__attribute__', '__ramfunc'] }) parser = CMockHeaderParser.new(config) # Parse a header file header_source = <<~C int calculate(int a, int b); void process_array(int* data, int size); typedef struct { int x; int y; } Point; C result = parser.parse('math', header_source) result[:functions].each do |func| puts "Function: #{func[:name]}" puts " Returns: #{func[:return][:type]}" func[:args].each do |arg| type_str = arg[:ptr?] ? "#{arg[:type]} (pointer)" : arg[:type] puts " - #{arg[:name]}: #{type_str}" end end ``` -------------------------------- ### CMock Array Interface Examples Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md When the `:array` plugin is enabled, these interfaces specify the depth for pointer parameters that are expected to be arrays. ```c void func_ExpectWithArray(type* ptr, int ptr_Depth, ...); ``` ```c void func_ExpectWithArrayAndReturn(type* ptr, int ptr_Depth, ..., return_type); ``` -------------------------------- ### Stop Ignore Example 2 (Does Not Work) Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Illustrates an incorrect usage where StopIgnore is called before the function that should have been ignored, leading to unexpected behavior. ```c Blah_Ignore(); Blah_StopIgnore(); funcThatMightCallBlahButWeDoNotCare(); funcThatWeWantToMakeSureDoesNotCallBlah(); ``` -------------------------------- ### Generate Mock Implementations with CMock Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMock.md Use `setup_mocks` to generate mock implementations for C header files. It accepts single or multiple file paths and an optional subdirectory for output. ```ruby def setup_mocks(files, folder = nil) [files].flatten.each do |src| generate_mock(src, folder) end end ``` ```ruby cmock = CMock.new cmock.setup_mocks('src/calculator.h') cmock.setup_mocks(['src/drivers/sensor.h', 'src/drivers/display.h']) cmock.setup_mocks('src/networking.h', 'network_subsystem') ``` -------------------------------- ### Initialize CMock with YAML Configuration File Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMock.md Create a CMock instance by specifying the path to a YAML file containing configuration options. ```ruby # Using a YAML configuration file cmock = CMock.new('cmock_config.yml') ``` -------------------------------- ### Create Mock File with Method-Specific Subdirectory Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Shows how to create a mock file in a subdirectory provided directly to the create_file method, relative to the base mock path. ```ruby # With subdir in method config = CMockConfig.new(:mock_path => 'build/mocks') writer = CMockFileWriter.new(config) writer.create_file('Mocked.h', 'subsystem') # => build/mocks/subsystem/Mocked.h ``` -------------------------------- ### CMock Configuration with Ruby Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockConfig.md Demonstrates how to create and access CMock configuration objects programmatically using Ruby. Shows custom options and accessing values. ```ruby # Create config with custom options config = CMockConfig.new({ :mock_path => 'test/mocks', :mock_prefix => 'Mock', :mock_suffix => '_Mock', :plugins => [:array, :callback, :cexception], :verbosity => 3, :when_ptr => :smart, :enforce_strict_ordering => true, :treat_as => { 'custom_status_t' => 'INT' }, :includes => ['project_types.h'] }) # Access configuration values puts config.mock_path # 'test/mocks' puts config.plugins # [:array, :callback, :cexception] ``` -------------------------------- ### Initialize CMock with Configuration Hash Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMock.md Instantiate CMock by providing a hash of specific configuration options, such as mock path, prefix, and enabled plugins. ```ruby # Using a configuration hash cmock = CMock.new({ :mock_path => 'build/mocks', :mock_prefix => 'Mock', :plugins => [:array, :callback] }) ``` -------------------------------- ### C Function with Array Parameter Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Example of a C function that takes an array and its size. CMock generates a corresponding ExpectWithArray function for testing. ```c void process_array(int* data, int size); // Generates: void process_array_ExpectWithArray(int* data, int size); ``` -------------------------------- ### Example: Generate Argument Expectation Code Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGeneratorUtils.md Shows how to generate C code for adding an expectation for a specific function argument using `code_add_an_arg_expectation`. ```ruby # Generate argument storage code expectation_code = utils.code_add_an_arg_expectation(arg, 1) ``` -------------------------------- ### Generate Skeleton Implementations with CMock Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMock.md Use `setup_skeletons` to generate skeleton C function implementations from header files. This method can be configured with a specific path for skeleton output. ```ruby def setup_skeletons(files) [files].flatten.each do |src| generate_skeleton src end end ``` ```ruby cmock = CMock.new(:skeleton_path => 'src/skeletons') cmock.setup_skeletons('src/mymodule.h') cmock.setup_skeletons(['src/module1.h', 'src/module2.h']) ``` -------------------------------- ### Instantiate CMock with Hash Configuration Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/configuration.md Use this method to directly provide configuration options to CMock during instantiation. Ensure all required keys are present and values are of the correct type. ```ruby CMock.new({ :mock_path => 'build/mocks', :mock_prefix => 'Mock', :plugins => [:array, :callback], :enforce_strict_ordering => true, :when_ptr => :smart, :treat_as => { 'status_code_t' => 'INT', 'handle_t' => 'HEX32' }, :includes => ['project_types.h'], :array_size_name => 'size|len', :array_size_type => ['size_t'] }) ``` -------------------------------- ### CMock Callback Interface Examples Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md If the `:callback` plugin is enabled, these interfaces allow you to provide a custom C function to be called instead of the mock implementation. ```c typedef return_type (*CMOCK_func_CALLBACK)(int NumCalls); void func_AddCallback(CMOCK_func_CALLBACK callback); ``` ```c void func_Stub(CMOCK_func_CALLBACK callback); ``` -------------------------------- ### Create Mock Subdirectory Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Creates the mock output directory and an optional subdirectory. Uses FileUtils.mkdir_p for idempotent creation. Raises SystemCallError on failure. ```ruby def create_subdir(subdir) require 'fileutils' FileUtils.mkdir_p "#{@config.mock_path}/" unless Dir.exist?("#{@config.mock_path}/") FileUtils.mkdir_p "#{@config.mock_path}/#{"#{subdir}/" if subdir}" if subdir && !Dir.exist?(...) rescue SystemCallError => e raise "Unable to create mock output directory: #{e.message}. Check :mock_path ('#{@config.mock_path}') configuration." end ``` ```ruby writer = CMockFileWriter.new(config) writer.create_subdir(nil) # Creates 'mocks/' writer.create_subdir('subsystem') # Creates 'mocks/subsystem/' ``` -------------------------------- ### CMock Ignore Interface Examples Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockGenerator.md If the `:ignore` plugin is enabled, these interfaces allow a function to be called any number of times with any arguments without failing the test. ```c void func_Ignore(void); ``` ```c void func_IgnoreAndReturn(return_type return_value); ``` ```c void func_StopIgnore(void); ``` -------------------------------- ### CMockFileWriter.initialize Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Creates a new CMockFileWriter instance. It requires a configuration object that holds file path information. ```APIDOC ## CMockFileWriter.initialize(config) ### Description Creates a new CMockFileWriter instance. ### Method initialize ### Parameters #### Path Parameters - **config** (CMockConfig) - Required - Configuration object with file paths ### Response **Returns:** CMockFileWriter instance ### Example ```ruby config = CMockConfig.new writer = CMockFileWriter.new(config) ``` ``` -------------------------------- ### Configure CMock with Ceedling Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Configure CMock settings within the Ceedling build system. This setup automatically handles mock generation, inclusion, and cleanup. ```yaml :cmock: :mock_path: 'build/mocks' :plugins: - :array - :callback ``` -------------------------------- ### Get CMock Memory Capacity Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockRuntime.md Retrieves the total configured memory size available to CMock. This value is determined by the CMOCK_MEM_SIZE define and remains constant. ```c CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesCapacity(void); ``` ```c CMOCK_MEM_INDEX_TYPE capacity = CMock_Guts_MemBytesCapacity(); // capacity == 32768 (default) ``` -------------------------------- ### Configure CMock File and Path Options via YAML Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/configuration.md Set directories for mock generation, skeleton files, prefixes, suffixes, subdirectories, and weak attributes using a YAML configuration. ```yaml :cmock: :mock_path: 'test/mocks' :skeleton_path: 'test/stubs' :mock_prefix: 'Mock' :mock_suffix: '_Mock' :subdir: 'generated' :weak: '__weak' ``` -------------------------------- ### Get Skeleton File Path Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Returns the full path for a skeleton file without creating it. Useful for checking existence or preparing for append operations. ```ruby def skeleton_file_path(filename, subdir) base = effective_skeleton_path "#{base}/#{"#{subdir}/" if subdir}#{filename}" end ``` ```ruby writer = CMockFileWriter.new(config) path = writer.skeleton_file_path('mymodule.c', nil) # => 'skeletons/mymodule.c' if File.exist?(path) puts "Skeleton already exists" end ``` -------------------------------- ### CMock Generation Pipeline Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/README.md Illustrates the steps involved in generating mock files from a header file. This process includes parsing, generation, and writing mock files. ```text Header File ↓ CMockHeaderParser.parse() ↓ (function data) CMockGenerator.create_mock() ├─ CMockPluginManager.run() → plugin code ├─ CMockGeneratorUtils → utility code └─ CMockFileWriter → write files ↓ Mock header (.h) Mock source (.c) ``` -------------------------------- ### CMock Example: Size After Pointer Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Demonstrates how CMock automatically uses the size parameter when it appears after the pointer it describes. The _Expect call uses 'buf_size' as the depth. ```c void func(uint8_t* buf, int buf_size) ``` -------------------------------- ### Error Message Context Example Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/api-reference/CMockFileWriter.md Illustrates the helpful error message format provided by file operations, aiding in the diagnosis of permission and path configuration problems. ```ruby # Creates helpful error message: # "Unable to write mock file 'build/mocks/test.h': Permission denied. # Check :mock_path ('build/mocks') and :subdir ('') configuration." ``` -------------------------------- ### Using resetTest with CMock Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Call resetTest during a test to have CMock validate everything to this point and start over clean. This is useful for testing functions iteratively with different arguments. ```c resetTest(); ``` -------------------------------- ### CMock Generated Function Name Example Source: https://github.com/throwtheswitch/cmock/blob/master/docs/CMock_Summary.md Generated function names include the namespace(s) and class to address potential issues with re-using the same function name in different namespaces/classes. ```c void MyNamespace_MyClass_DoesSomething_ExpectAndReturn(int a, int b, int toReturn); ``` -------------------------------- ### Configure Include and Header Directives Source: https://github.com/throwtheswitch/cmock/blob/master/_autodocs/configuration.md Manage include directives for generated mock headers and source files, including common includes, pre/post original header includes, and paths to Unity helper files. ```yaml :cmock: :includes: - 'config.h' - 'types.h' :includes_h_pre_orig_header: - 'stdint.h' :includes_c_pre_header: - 'project_config.h' :orig_header_include_fmt: '#include "%s"' :unity_helper_path: - 'vendor/unity/helpers/custom_types.h' ```