Component Tester - Test Case Specification

This section describes the principle of the tests produced with the Component Tester, the format of a test case and the APIs available to write a test case.

This page discusses:

Glossary

Acronym Definition
SUT System Under Test
CSE Communication & Scheduling Entity
SM State Machine
Tal Targeted Application Layer
TAM Target Abstraction Module

Referenced Documents

Document Internal Reference
Component Tester Generator - Operation Specification [1]
UML & SysML to C - Statemachine Code Generator Specification [2]
UML & SysML to C - Activity Code Generator Specification [3]
UML & SysML to C - Interface Code Generation Specifications [4]
C Code Architecture Specification [5]

General Concepts

Principle of the tests

The Component Tester turns the generated code of a component into a System Under Test (SUT) compiled as a shared library, and provides two layers of APIs to drive and observe it from a test case:

  • a model-independent API (TestCase_Api.h): logging, traceability, virtual-time scheduling and generic checks;
  • a model-specific API (TestCase_Api_Gen.h): generated from the model, it exposes the data, properties, behaviors and operations of the component under test.

A test case is a piece of C or C++ code that:

  1. brings the SUT to a known state,
  2. stimulates the model — by writing on its interface elements, by setting instance properties, by injecting events, or by calling its server operations,
  3. advances the virtual execution time so the SUT reacts,
  4. observes and checks the resulting state of the model — interface data, instance properties, and (with instrumented code) the active states of state machines and the active nodes of activities.

The execution is driven by virtual time: the SUT does not run in real time. The test case explicitly advances time with Sut_Runduring / Sut_Runto, which gives deterministic and reproducible results. State machines and activities are event-driven; advancing time lets the scheduler dispatch the events through the event pools and run the successive behavior steps.

Component Tester Architecture

The Component Tester is composed of an executable and a shared library.

The shared library is compiled with the source code generated by the operations UML to C and UML to C++. It may also be compiled with the test cases, if any. The executable loads the shared library, manages the test cases, schedules the execution and logs the results.

+-------------------------------------------------------------+
|                     Tester / executable                     |
|   http Server   Test cases Manager   Exec. scheduler   Logger|
+-------------------------------------------------------------+
                              |  loads
                              v
+-------------------------------------------------------------+
|              System Under Test / shared library             |
|                                                             |
|   Component                          (Target independent    |
|                                       & dependent)          |
|   Communication & Scheduling Component (Target independent)  |
|                                                             |
|   Tester Target Abstraction Layer:                          |
|     Shared Objects | Hooks | Test case | Scheduler |        |
|     Tracer | Memory | Timer | Api                           |
+-------------------------------------------------------------+

Development Environment

VSCode

The development environment can rely on the VSCode software. VSCode eases the development activity: code development, compilation, execution including debug.

Note that the Component Tester can be used in an alternative environment. In such a case, it may require additional user-specific configuration. The installation of VSCode is described in VS Code installation.

MSYS2

The Component Tester Generator provides an environment already compiled and ready for execution. Nevertheless, it may be required to recompile the project locally following a code change, or the user may need to debug the application. In both cases, MSYS2 may be required. The installation of MSYS2 is described in MSYS2 installation.

Observability of behaviors

The behavior monitoring part of the API (active state / transition of state machines, active node / flows of activities, and event injection) is available only when the SUT and the harness are generated with instrumented code. See the instrumented_code parameter in [1].

Naming conventions

The model-specific API uses a function suffix derived from the path of the element in the component, with a prefix identifying its kind:

Prefix Kind of element Reference
i_ Interface element (data on a port, shared variable) [4]
p_ Instance property of the cpp instance graph
b_ Behavior member: active state / transition of a state machine, active node / flows of an activity (instrumented code only) [2], [3]

Component Tester Usage

VS Code installation

Go to https://code.visualstudio.com/download and follow the instructions to install VSCode.

Install the C/C++ extension to enable application execution and debugging:

C/C++ extension for VSCode

MSYS2 installation

To take advantage of all the capabilities delivered by the Component Tester, we advise installing MSYS2.

To do so, go to https://www.msys2.org/ and install MSYS2. Note that installing MSYS2 in the default directory simplifies the configuration of your environment.

To enable compilation, install gcc and make. Launch the MSYS2 console by running <msys2_install_dir>/msys2.exe and execute the following commands:

pacman -S make
pacman -S mingw-w64-x86_64-gcc

To enable debugging, install gdb. Launch the MSYS2 console by running <msys2_install_dir>/msys2.exe and execute the following command:

pacman -S mingw-w64-x86_64-gdb

Tester Command Line Parameters

The Component Tester is composed of an executable compatible with Windows 64-bit (named tester.exe) and Linux 64-bit (named tester).

The tester supports command line parameters. Each parameter is identified with a - prefix character. The tester can be invoked as follows in a terminal:

<path to tester>\Tester.exe [PARAMETER] ... -dll [FILE] ...

Running Tester.exe -help displays the usage:

Usage: Tester [OPTION] ... -dll [FILE] ...
Execute a test sequence on a system under test contained in the DLL.
 -dll <dll path>               [Mandatory]                    absolute/relative path to the
                                   dll containing the model.
 -report <name>                [Optional|Default:TestReport]  name of the report file
                                   referencing the general informations of the test execution.
 -logName <name>               [Optional|Default:TestLog]     default log name given when log
                                   files are created.
 -timestamp <true/false>       [Optional|Default:true]        indicate if timestamp must be
                                   added at the end of the generated report and logs.
 -logDirectory <directory>     [Optional|Default:current dir] directory where report and logs
                                   are stored.
 -enableLogging <true/false>   [Optional|Default:true]        enable or disable logging
                                   mechanism. If set to false, neither the report nor logs are
                                   generated.
 -logLevel <N0/N1/N2/N3/N4/N5> [Optional|Default:N5]          level of details printed in log.
                                   N0 means nothing, N5 means everything.
 -httpServer <true/false>      [Optional|Default:false]       start or not http server to
                                   communicate with tester.
 -port <number>                [Optional]                     port number on which server is
                                   listening. Mandatory if startServer is set to "true"
 -listTestCases                [Optional]                     list the test cases availables
                                   in the dll provided via -dll option and exit.
 -executeTestCases <true/false>[Optional|Default:true]        execute test cases if set to
                                   true. If set to false, no test case is executed. False is
                                   only permitted if -httpServer is set to true.
 -testCases <tc1 tc2 ...>      [Optional]                     execute the listed test cases.
                                   If no testcase is provided, all the available tests are
                                   executed.
 -verbose                      [Optional]                     activate verbose mode to get
                                   more details during execution.
 -help                         [Optional]                     display this help and exit.

The parameters are detailed below.

dll parameter

Attributes Values
Name dll
Description Mandatory parameter to specify the absolute / relative path to the DLL containing the model.
Type String
Values [Default] N/A
Multiplicity 1

report parameter

Attributes Values
Name report
Description Optional parameter to specify the name of the report file referencing the general information of the test execution.
Type String
Values [Default] [TestReport]
Multiplicity 0..1

logName parameter

Attributes Values
Name logName
Description Optional parameter to specify the default log name given when log files are created.
Type String
Values [Default] [TestLog]
Multiplicity 0..1

timestamp parameter

Attributes Values
Name timestamp
Description Optional parameter to indicate if a timestamp must be added at the end of the generated report and logs.
Type Boolean
Values [Default] [true] / false
Multiplicity 0..1

logDirectory parameter

Attributes Values
Name logDirectory
Description Optional parameter to specify the directory where the report and logs are stored.
Type String
Values [Default] current directory
Multiplicity 0..1

enableLogging parameter

Attributes Values
Name enableLogging
Description Optional parameter to enable or disable the logging mechanism. If set to false, neither the report nor the logs are generated.
Type Boolean
Values [Default] [true] / false
Multiplicity 0..1

logLevel parameter

Attributes Values
Name logLevel
Description Optional parameter to specify the level of detail printed in the log. N0 means nothing, N5 means everything.
Type Enumeration
Values [Default] N0 / N1 / N2 / N3 / N4 / [N5]
Multiplicity 0..1

httpServer parameter

Attributes Values
Name httpServer
Description Optional parameter to start or not the HTTP server used to communicate with the tester.
Type Boolean
Values [Default] true / [false]
Multiplicity 0..1

port parameter

Attributes Values
Name port
Description Optional parameter to specify the port number on which the server is listening. Mandatory if httpServer is set to true.
Type Integer
Values [Default] N/A
Multiplicity 0..1

listTestCases parameter

Attributes Values
Name listTestCases
Description Optional parameter to list the test cases available in the DLL provided via the -dll option and exit.
Type No value required
Values [Default] N/A
Multiplicity 0..1

executeTestCases parameter

Attributes Values
Name executeTestCases
Description Optional parameter to execute the test cases if set to true. If set to false, no test case is executed. False is only permitted if -httpServer is set to true.
Type Boolean
Values [Default] [true] / false
Multiplicity 0..1

testCases parameter

Attributes Values
Name testCases
Description Optional parameter to execute the listed test cases. If no test case is provided, all the available tests are executed.
Type String
Values [Default] testcase1 testcase2 …
Multiplicity 0..*

verbose parameter

Attributes Values
Name verbose
Description Optional parameter to activate the verbose mode to get more details during execution.
Type No value required
Values [Default] N/A
Multiplicity 0..1

help parameter

Attributes Values
Name help
Description Optional parameter to display the help and exit.
Type No value required
Values [Default] N/A
Multiplicity 0..1

Test Case Format

A test case includes the data types of the SUT and the two API headers:

#include "Cse_cfg.h"          // data types (Integer, Boolean, String, ...)
#include "TestCase_Api.h"     // model-independent API
#include "TestCase_Api_Gen.h" // model-specific API generated for the component

The test data types are: Integer (int), Boolean (bool, with values TRUE / FALSE), String (char*).

C test case

A C test case is a collection of tests, each declared with the macro TEST(<test name>), where <test name> matches the pattern a-zA-Z0-9_:

#include "Cse_cfg.h"
#include "TestCase_Api.h"
#include "TestCase_Api_Gen.h"

TEST(C_test){
    Log_Info("C_test startup");
    Sut_Runduring(10); // run the SUT during 10 virtual seconds
}

C++ test case

A C++ test case is a class declaring a collection of tests with the macro TEST_DECL(<test name>), each implemented with TEST(<class name>, <test name>). The class name and the test name match the pattern a-zA-Z0-9_:

#include "Cse_cfg.h"
#include "TestCase_Api.h"
#include "TestCase_Api_Gen.h"

class Cpp_TestCase {
  public:
    TEST_DECL(Cpp_test);
};

TEST(Cpp_TestCase, Cpp_test){
    Log_Info("Cpp_test startup");
    Sut_Runduring(10);
}

Test cases are placed in the tester/testcases folder of the generated harness. Example test cases can be generated automatically (see generate_testcase_examples in [1]).

Model-Independent APIs

These APIs are declared in TestCase_Api.h and are identical for every component.

Logging

API Description
Log_Info(...) Log a message in the log file with the INFO label.
Log_Warning(...) Log a message in the log file with the WARN label.
Log_Error(...) Log a message in the log file with the ERROR label.
Log_Failure(...) Log a message in the log file with the FATAL label.
Console_Print(...) Print a message in the console (thread-safe, similar to printf).

The logging macros accept a printf-style format string and arguments.

Traceability

API Description
Traca_TestCase_Title(...) Declare the title of the test case (TCTITLE).
Traca_TestCase_Description(...) Declare the description of the test case (TCDESC).
Traca_Check_Description(...) Describe the next check (CHKDESC). Used to document each check.
Traca_Covers(...) Declare the requirements covered by the test case (COVERS).

Time and scheduling

API Description
System_GetTime() Return the current virtual time of the execution (seconds).
System_GetTick() Return the current tick of the execution.
Sut_Runduring(time) Execute the application during time virtual seconds (relative).
Sut_Runto(time) Execute the application up to the exact virtual time time seconds (absolute).

Advancing the virtual time is required for the SUT to react: events injected or data written by the test case are processed by the scheduler while time advances.

Generic checks

API Description
Check(condition, info, ...) Evaluate condition; log a check OK / check ERROR. The test continues even on error.
Assert(condition, info, ...) Evaluate condition; log a check OK / check ERROR. The test case is stopped on error.

Check kinds

The model-specific Check_* functions take a comparison kind as first argument:

Kind Comparison
EQ equal
NE not equal
LE less or equal
LT less than
GE greater or equal
GT greater than

Access counter flags

For interface elements, an access counter can be configured to monitor how often a data is accessed. The configuration flags are:

Flag Description
AC_NONE No counter.
AC_DECREMENT Decrement the counter on each access.
AC_AUTO_RESET Reset the counter at each step.
AC_ERROR_IF_NEG Raise an error if the counter goes negative.

Model-Specific APIs

These APIs are declared in TestCase_Api_Gen.h and are generated from the model. The <suffix> part of each function name is the path of the element in the component, prefixed by its kind (i_, p_, b_). Each interface element / instance property exposes a write, a read and a check function:

API Description
Write_<suffix>(data) Write a value to the element (pointer to the typed value).
Read_<suffix>(data) Read the current value of the element into data.
Check_<suffix>(kind, value, ...) Check the current value of the element against value using the comparison kind.

Server operations exposed on ports are callable:

API Description
Call_<suffix>(args...) Call the server operation on the corresponding port.

For interface shared variables, the access counter APIs are also generated: ACbk_Cfg_<suffix>, ACntr_Get_<suffix>, ACntr_Cfg_<suffix>.

Behavior members (instrumented code)

When the harness is generated with instrumented code, each state machine and activity exposes, through Check_<suffix> / Read_<suffix> with a b_ prefix:

  • for a state machine: the active state and the active transition;
  • for an activity: the active node and the active flows.

The instrumented value of a state / node is a String formatted as "<Name> (<uuid>)".

Event injection (instrumented code)

When the harness is generated with instrumented code, each behavior exposes an event injection function that sends an event directly to the input event pool of that behavior:

Send_<suffix>(eventId);

eventId must be one of the <CLASS>_EVENT_T_* values of the receiving class. This allows a test case to stimulate a state machine or activity deterministically — one call injects exactly one event — without going through the upstream chain of components.

Example

The following C++ test case (extract) drives the Controller state machine of a stopwatch model by injecting events directly into its event pool, and verifies the evolution of the Controller and Timer state machines. It illustrates the typical pattern: declare expected values, bring the SUT to a stable state, inject an event, advance virtual time, then check.

#include "Cse_cfg.h"
#include "TestCase_Api.h"
#include "TestCase_Api_Gen.h"

class StopwatchUML {
  public:
    TEST_DECL(Cpp_test);
};

#define SETTLE 0.5  // virtual seconds left to the scheduler to propagate an event

TEST(StopwatchUML, Cpp_test){

    Traca_TestCase_Title("StopwatchUML - event-driven state machines");
    Traca_TestCase_Description(
        "Inject StartStop / LapReset into the Controller and verify the "
        "Controller (IDLE/Running/Paused) and Timer (Stopped/Running) state machines.");

    // Expected instrumented states: "<State> (<uuid>)"
    char ctrlIdleStr[]    = "IDLE (...)";
    char ctrlRunningStr[] = "Running (...)";
    String pCtrlIdle      = ctrlIdleStr;
    String pCtrlRunning   = ctrlRunningStr;
    Boolean bTrue = TRUE;

    // 1. Initialisation: each SM reaches its stable initial state
    Log_Info("SUT initialisation");
    Sut_Runduring(SETTLE);
    Traca_Check_Description("Initial state: Controller = IDLE");
    Check_Stopwatch_controller_..._state_...(EQ, &pCtrlIdle);

    // 2. StartStop -> IDLE -> Running (the Timer starts)
    Log_Info("StartStop #1 -> start");
    Send_Stopwatch_controller(CONTROLLER_EVENT_T_StartStop);
    Sut_Runduring(SETTLE);
    Traca_Check_Description("Controller = Running");
    Check_Stopwatch_controller_..._state_...(EQ, &pCtrlRunning);
    Traca_Check_Description("Timer.isRunning = true");
    Check_Stopwatch_timer_isRunning(EQ, &bTrue);

    Log_Info("Cpp_test done");
}

Test Execution and Results

When run, a test case produces a log file. Each Traca_* call adds a labelled line (TCTITLE, TCDESC, CHKDESC, COVERS); each check adds an [OK] or [ERROR] line with the current and expected values, the source location, and the virtual time. A summary at the end of the log reports the total number of checks, the number passed and the number failed, as well as the event pool statistics. An extract:

[INFO]  0.500 - CHKDESC: Initial state: Controller = IDLE
[OK]    0.500 - CHECK: state_... - Current: IDLE (...) == Expected: IDLE (...)
...
============================================================================
Total checks: 17 - Passed: 16 - Failed: 1
============================================================================