Main Content

polyspace.project.Mock Class

Namespace: polyspace.project

(Python) Create and update mock for function

Since R2026a

Description

Create a mock function to override the definition of a C/C++ function in the source code added to a Polyspace® Platform project.

Creation

Description

mock = proj.Mocks.create(functionToMock) creates a mock for function functionToMock in a polyspace.project.Project object proj. The mock name is the name of the original function followed by _mock.

mock = proj.Mocks.create(functionToMock, PropertyName=Value) creates a mock for function functionToMock and assigns one or more of its properties during creation.

mock = proj.Mocks.createFrom(existingMock, newMockName) creates a new mock by duplicating an existing mock.

Input Arguments

expand all

Function to mock, specified as a polyspace.project.Function object.

Get the polyspace.project.Function object for a function by parsing the code associated with a polyspace.project.Project object proj and using the getFunctionBySignature method for the resulting polyspace.project.CodeInfo object.

For example, use this code to get the polyspace.project.Function object for the function with signature void init(int) in the project proj:

codeInfo = polyspace.project.parseCode(proj)
functionToMock = codeInfo.getFunctionBySignature("void init(int)")

For more information, see polyspace.project.CodeInfo.

Existing mock, specified as a polyspace.project.Mock object. The existing mock object can be from any project.

Name of new mock specified as a string. This name is assigned to the Name property of the newly created mock.

Properties

expand all

Name of mock, specified as a string. This name is assigned to the Name property of the polyspace.project.Mock object and appears as the mock name when you open the associated project in the Polyspace Platform user interface.

Names of arguments to the mock, specified as an array of strings. Each mock argument has the same type as the type of the corresponding function argument.

If you do not set this property explicitly, the mock argument names are the same as the function argument names. For unnamed function arguments, the mock argument names are automatically generated.

Example: ["arg0", "arg1", "arg2"]

Code that goes outside the mock body, such as global variable declarations or type declarations, specified as a string. This code allows the mock definition to be compiled in isolation. In most cases, you add #include-s to header files containing the required declarations.

Example: '#include "types.h"'

Code that goes inside the mock body (excluding the mock signature), specified as a string.

Example: "int aGlobal1 = num;"

Variable declarations to export from the mock, specified as a string.

Example: "extern int statusVar;"

List of variables whose declarations are exported from a mock using the ExportedDeclarations property. A mock variable can looked up in the list using its name and accessed from the inputs or assessments of a test.

For an example usage of this property, see Change Mock Implementation Using Test Inputs.

Examples

collapse all

Create a mock for a function and apply the mock in a test. For equivalent steps in the Polyspace Platform user interface, see Override Callee Definitions When Testing Functions in Polyspace Platform User Interface.

  1. Inspect the file inits.c in the folder polyspaceroot\polyspace\examples\doc_pstest\test_with_mocked_callee\src. Here, polyspaceroot is the Polyspace installation folder, for instance, C:\Program Files\Polyspace\R2026a.

    The file contains a function set() that calls another function init() to write to global variables.

    #include "decls.h"
    
    extern int32_t aGlobal1;
    extern int32_t aGlobal2;
    
    void init(int32_t num) {
        aGlobal1 = num;
        aGlobal2 = num;
    }
    
    void set(int32_t num) {
        init(num);
    }
    In the following two scripts, you write a test for the function set() by mocking the function init() and see the effect of applying the mock.

  2. Create a test for the function set() leaving the default implementation of the function init():

    import polyspace.project, polyspace.test
    import os
    
    # Add source file "inits.c" to a project and parse source code
    proj = polyspace.project.Project("myProject")
    proj.Code.Files.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "test_with_mocked_callee",
            "src",
            "inits.c"
        )
    )
    proj.IncludePaths.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "test_with_mocked_callee",
            "src"
        )
    )
    codeInfo = polyspace.project.parseCode(proj)
    
    # Create test for "set()" function
    suite = proj.TestSuites.create("globalUpdateSuite")
    test = suite.TestCases.create("globalUpdateTest")
    funcToTest = codeInfo.getFunctionBySignature("void set(int32_t)")
    testStep = test.TestSteps.createTabular("setGlobal", funcToTest)
    testStep.Inputs["num"].Value = "1"
    testStep.Assessments["aGlobal1"].Value = "0"
    testStep.Assessments["aGlobal2"].Value = "0"
    
    # Run test
    res = polyspace.test.run(proj)
    print(res.SuitesPassed)
    
    When you run the script, you see failing test results because the function init() initializes the global variables to 1, but the assessments compare the value against 0.

  3. Modify the previous test to apply a mock for the init() function:

    # Import required modules
    import polyspace.project
    import polyspace.test
    import os
    
    # Add source file "inits.c" to a project and parse source code
    projWithMocks = polyspace.project.Project("myProjectWithMocks")
    projWithMocks.Code.Files.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "test_with_mocked_callee",
            "src",
            "inits.c"
        )
    )
    projWithMocks.IncludePaths.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "test_with_mocked_callee",
            "src"
        )
    )
    codeInfo = polyspace.project.parseCode(projWithMocks)
    
    # Create mock for "init()" function
    projectMocks = projWithMocks.Mocks
    funcToMock = codeInfo.getFunctionBySignature("void init(int32_t)")
    mockInit = projectMocks.create(funcToMock, Name="init_mock")
    mockInit.Header = """#include <stdint.h>
                         extern int32_t aGlobal1;
                         extern int32_t aGlobal2;"""
    mockInit.Body = """ aGlobal1 = 0;
                        aGlobal2 = 0;"""
    
    # Create test for "set()" function
    suite = projWithMocks.TestSuites.create("globalUpdateSuite")
    test = suite.TestCases.create("globalUpdateTest")
    funcToTest = codeInfo.getFunctionBySignature("void set(int32_t)")
    testStep = test.TestSteps.createTabular("setGlobal", funcToTest)
    testStep.Inputs["num"].Value = "1"
    testStep.Assessments["aGlobal1"].Value = "0"
    testStep.Assessments["aGlobal2"].Value = "0"
    
    # Apply mock on test
    testStep.ActiveMocks.add(mockInit)
    
    # Run test
    res = polyspace.test.run(projWithMocks)
    print(res.SuitesPassed)
    When you run the script, the test passes now because the mock body overrides the implementation of the init() function.

Create a single mock that can have different implementations in different tests and choose the mock implementation using test inputs. For equivalent steps in the Polyspace Platform user interface, see Change Mock or Stub Implementation Based on Test.

  1. Inspect the following files in the folder polyspaceroot\polyspace\examples\doc_pstest\mock_variables\src.

    • decls.h contains the definitions of types readStatus and State:

      #ifndef DECLS_H
      #define DECLS_H
      
      enum readStatus {
          R_SUCCESS,
          R_FAILURE
      };
      
      struct State {
          int indicator;
          int updateCount; 
      };
      
      enum readStatus readData(void);
      void updateState(struct State* stateVariable);
      #endif
    • example.c contains the definitions of functions readData() and updateStatus():

      #include "decls.h"
      
      enum readStatus readData(void) {
          //readData() implementation
      }
      
      void updateState(struct State* stateVariable) {
          enum readStatus status = readData();
          if (status == R_SUCCESS) {
              stateVariable->indicator = 1;
              stateVariable->updateCount++;
          }
      }
      In the following two scripts, you write a test for the function updateState() by mocking the function readData() and see the effect of applying the mock.

  2. Create a test for the function updateState() as follows:

    # Import the required modules
    import polyspace.project
    import polyspace.test
    import os
    
    # Add source file "example.c" and include paths
    # To a project and parse the source code
    proj = polyspace.project.Project("myProjectWithMocks")
    proj.Code.Files.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "mock_variables",
            "src",
            "example.c"
        )
    )
    proj.IncludePaths.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "test_with_mocked_callee",
            "src"
        )
    )
    codeInfo = polyspace.project.parseCode(proj)
    
    # Create test
    suite = proj.TestSuites.create("updateSuite")
    test = suite.TestCases.create("updateTest")
    
    # Create test step to invoke function "updateState()"
    funcToTest = codeInfo.getFunctionBySignature("void updateState(struct State*)")
    testStep = test.TestSteps.createTabular("updateTest", funcToTest)
    
    # Create pointer targets to variables of type "struct State"
    structType = codeInfo.getType("struct State[1]")
    inputTarget = test.TestData.create("inputState", structType) # All fields implicitly set to 0
    outputTarget = test.TestData.create("outputState", structType)
    test.TestData["outputState"][0]["indicator"].Value = "1"
    test.TestData["outputState"][0]["updateCount"].Value = "1"
    
    # Set test inputs and assessments
    testStep.Inputs["stateVariable"].Value = inputTarget
    testStep.Assessments["stateVariable"].Value = outputTarget
    
    # Run test
    res = polyspace.test.run(proj)
    print(res.SuitesPassed)
    When you run the script, you see failing test results because the function updateState() bypasses the if statement and does not modify its input.

  3. Modify the previous test to apply a mock on the readData() function:

    # Import the required modules
    import polyspace.project
    import polyspace.test
    import os
    
    # Add source file "example.c" and include paths
    # To a project and parse the source code
    projWithMocks = polyspace.project.Project("myProject")
    projWithMocks.Code.Files.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "mock_variables",
            "src",
            "example.c"
        )
    )
    projWithMocks.IncludePaths.add(
        os.path.join(
            polyspace.__install_path__,
            "polyspace",
            "examples",
            "doc_pstest",
            "mock_variables",
            "src"
        )
    )
    codeInfo = polyspace.project.parseCode(projWithMocks)
    
    # Create mock for "readData()" function
    projectMocks = projWithMocks.Mocks
    funcToMock = codeInfo.getFunctionBySignature("enum readStatus readData(void)")
    mockReadData = projectMocks.create(funcToMock, Name="readData_mock")
    mockReadData.Header = '''#include "decls.h"
                         enum readStatus statusMockVar;'''
    mockReadData.ExportedDeclarations = '''#include "decls.h"
                         extern enum readStatus statusMockVar;'''
    mockReadData.Body = "return statusMockVar;"
    
    # Create test
    suite = projWithMocks.TestSuites.create("updateSuite")
    test = suite.TestCases.create("updateTest")
    
    # Create test step to invoke function "updateState()"
    funcToTest = codeInfo.getFunctionBySignature("void updateState(struct State*)")
    testStep = test.TestSteps.createTabular("updateTest", funcToTest)
    
    # Create pointer targets to variables of type "struct State"
    structType = codeInfo.getType("struct State[1]")
    inputTarget = test.TestData.create("inputState", structType) # All fields implicitly set to 0
    outputTarget = test.TestData.create("outputState", structType)
    test.TestData["outputState"][0]["indicator"].Value = "1"
    test.TestData["outputState"][0]["updateCount"].Value = "1"
    
    # Set test inputs and assessments
    testStep.Inputs["stateVariable"].Value = inputTarget
    testStep.Assessments["stateVariable"].Value = outputTarget
    
    # Run test
    res = polyspace.test.run(projWithMocks)
    print(res.SuitesPassed)
    
    # Apply mock on test
    testStep.ActiveMocks.add(mockReadData)
    
    # Create test input from the exported mock variable "statusMockVar"
    # Set input value
    testStep.Inputs.create(mockReadData.ExportedVariables["statusMockVar"])
    testStep.Inputs["statusMockVar"].Value = "R_SUCCESS"
    
    # Run the test
    res = polyspace.test.run(projWithMocks)
    print(res.SuitesPassed)
    When you run the script, the test now passes because the mock body overrides the implementation of the readData() function. The exported mock variable value R_SUCCESS causes the mock to have this implementation:
    enum readStatus readData(void) {
        return R_SUCCESS;
    }
    This implementation causes the caller updateState() to enter the body of the if statement and modify its input.

Limitations

Polyspace Test™ does not support the creation of mocks for:

  • Variadic functions

  • Template functions or methods

  • Operators, constructors, or destructors

  • Functions defined in header files

  • Methods for classes defined in source files

  • Inline methods

  • Functions with a parameter type that is defined in a source file

Version History

Introduced in R2026a