1.. _twister_script:
2
3Test Runner (Twister)
4#####################
5
6This script scans for the set of unit test applications in the git repository
7and attempts to execute them. By default, it tries to build each test
8case on boards marked as default in the board definition file.
9
10The default options will build the majority of the tests on a defined set of
11boards and will run in an emulated environment if available for the
12architecture or configuration being tested.
13
14In normal use, twister runs a limited set of kernel tests (inside
15an emulator).  Because of its limited test execution coverage, twister
16cannot guarantee local changes will succeed in the full build
17environment, but it does sufficient testing by building samples and
18tests for different boards and different configurations to help keep the
19complete code tree buildable.
20
21When using (at least) one ``-v`` option, twister's console output
22shows for every test how the test is run (qemu, native_sim, etc.) or
23whether the binary was just built.  There are a few reasons why twister
24only builds a test and doesn't run it:
25
26- The test is marked as ``build_only: true`` in its ``.yaml``
27  configuration file.
28- The test configuration has defined a ``harness`` but you don't have
29  it or haven't set it up.
30- The target device is not connected and not available for flashing
31- You or some higher level automation invoked twister with
32  ``--build-only``.
33
34To run the script in the local tree, follow the steps below:
35
36.. tabs::
37
38   .. group-tab:: Linux
39
40      .. code-block:: bash
41
42         $ source zephyr-env.sh
43         $ ./scripts/twister
44
45   .. group-tab:: Windows
46
47      .. code-block:: bat
48
49         zephyr-env.cmd
50         python .\scripts\twister
51
52
53If you have a system with a large number of cores and plenty of free storage space,
54you can build and run all possible tests using the following options:
55
56.. tabs::
57
58   .. group-tab:: Linux
59
60      .. code-block:: bash
61
62         $ ./scripts/twister --all --enable-slow
63
64   .. group-tab:: Windows
65
66      .. code-block:: bat
67
68         python .\scripts\twister --all --enable-slow
69
70This will build for all available boards and run all applicable tests in
71a simulated (for example QEMU) environment.
72
73If you want to run tests on one or more specific platforms, you can use
74the ``--platform`` option, it is a platform filter for testing, with this
75option, test suites will only be built/run on the platforms specified.
76This option also supports different revisions of one same board,
77you can use ``--platform board@revision`` to test on a specific revision.
78
79The list of command line options supported by twister can be viewed using:
80
81.. tabs::
82
83   .. group-tab:: Linux
84
85      .. code-block:: bash
86
87         $ ./scripts/twister --help
88
89   .. group-tab:: Windows
90
91      .. code-block:: bat
92
93         python .\scripts\twister --help
94
95
96Board Configuration
97*******************
98
99To build tests for a specific board and to execute some of the tests on real
100hardware or in an emulation environment such as QEMU a board configuration file
101is required which is generic enough to be used for other tasks that require a
102board inventory with details about the board and its configuration that is only
103available during build time otherwise.
104
105The board metadata file is located in the board directory and is structured
106using the YAML markup language. The example below shows a board with a data
107required for best test coverage for this specific board:
108
109.. code-block:: yaml
110
111  identifier: frdm_k64f
112  name: NXP FRDM-K64F
113  type: mcu
114  arch: arm
115  toolchain:
116    - zephyr
117    - gnuarmemb
118    - xtools
119  supported:
120    - arduino_gpio
121    - arduino_i2c
122    - netif:eth
123    - adc
124    - i2c
125    - nvs
126    - spi
127    - gpio
128    - usb_device
129    - watchdog
130    - can
131    - pwm
132  testing:
133    default: true
134
135
136identifier:
137  A string that matches how the board is defined in the build system. This same
138  string is used when building, for example when calling ``west build`` or
139  ``cmake``:
140
141  .. code-block:: console
142
143     # with west
144     west build -b reel_board
145     # with cmake
146     cmake -DBOARD=reel_board ..
147
148name:
149  The actual name of the board as it appears in marketing material.
150type:
151  Type of the board or configuration, currently we support 2 types: mcu, qemu
152simulation:
153  Simulator used to simulate the platform, e.g. qemu.
154arch:
155  Architecture of the board
156toolchain:
157  The list of supported toolchains that can build this board. This should match
158  one of the values used for :envvar:`ZEPHYR_TOOLCHAIN_VARIANT` when building on the command line
159ram:
160  Available RAM on the board (specified in KB). This is used to match testcase
161  requirements.  If not specified we default to 128KB.
162flash:
163  Available FLASH on the board (specified in KB). This is used to match testcase
164  requirements.  If not specified we default to 512KB.
165supported:
166  A list of features this board supports. This can be specified as a single word
167  feature or as a variant of a feature class. For example:
168
169  .. code-block:: yaml
170
171        supported:
172          - pci
173
174  This indicates the board does support PCI. You can make a testcase build or
175  run only on such boards, or:
176
177  .. code-block:: yaml
178
179        supported:
180          - netif:eth
181          - sensor:bmi16
182
183  A testcase can both depend on 'eth' to only test ethernet or on 'netif' to run
184  on any board with a networking interface.
185
186testing:
187  testing relating keywords to provide best coverage for the features of this
188  board.
189
190  default: [True|False]:
191    This is a default board, it will tested with the highest priority and is
192    covered when invoking the simplified twister without any additional
193    arguments.
194  ignore_tags:
195    Do not attempt to build (and therefore run) tests marked with this list of
196    tags.
197  only_tags:
198    Only execute tests with this list of tags on a specific platform.
199
200  .. _twister_board_timeout_multiplier:
201
202  timeout_multiplier: <float> (default 1)
203    Multiply each test case timeout by specified ratio. This option allows to tune timeouts only
204    for required platform. It can be useful in case naturally slow platform I.e.: HW board with
205    power-efficient but slow CPU or simulation platform which can perform instruction accurate
206    simulation but does it slowly.
207
208Test Cases
209**********
210
211Test cases are detected by the presence of a ``testcase.yaml`` or a ``sample.yaml``
212files in the application's project directory. This file may contain one or more
213entries in the test section each identifying a test scenario.
214
215The name of each testcase needs to be unique in the context of the overall
216testsuite and has to follow basic rules:
217
218#. The format of the test identifier shall be a string without any spaces or
219   special characters (allowed characters: alphanumeric and [\_=]) consisting
220   of multiple sections delimited with a dot (.).
221
222#. Each test identifier shall start with a section followed by a subsection
223   separated by a dot. For example, a test that covers semaphores in the kernel
224   shall start with ``kernel.semaphore``.
225
226#. All test identifiers within a testcase.yaml file need to be unique. For
227   example a testcase.yaml file covering semaphores in the kernel can have:
228
229   * ``kernel.semaphore``: For general semaphore tests
230   * ``kernel.semaphore.stress``: Stress testing semaphores in the kernel.
231
232#. Depending on the nature of the test, an identifier can consist of at least
233   two sections:
234
235   * Ztest tests: The individual testcases in the ztest testsuite will be
236     concatenated to identifier in the testcase.yaml file generating unique
237     identifiers for every testcase in the suite.
238
239   * Standalone tests and samples: This type of test should at least have 3
240     sections in the test identifier in the testcase.yaml (or sample.yaml) file.
241     The last section of the name shall signify the test itself.
242
243
244Test cases are written using the YAML syntax and share the same structure as
245samples. The following is an example test with a few options that are
246explained in this document.
247
248
249  .. code-block:: yaml
250
251        tests:
252          bluetooth.gatt:
253            build_only: true
254            platform_allow: qemu_cortex_m3 qemu_x86
255            tags: bluetooth
256          bluetooth.gatt.br:
257            build_only: true
258            extra_args: CONF_FILE="prj_br.conf"
259            filter: not CONFIG_DEBUG
260            platform_exclude: up_squared
261            platform_allow: qemu_cortex_m3 qemu_x86
262            tags: bluetooth
263
264
265A sample with tests will have the same structure with additional information
266related to the sample and what is being demonstrated:
267
268  .. code-block:: yaml
269
270        sample:
271          name: hello world
272          description: Hello World sample, the simplest Zephyr application
273        tests:
274          sample.basic.hello_world:
275            build_only: true
276            tags: tests
277            min_ram: 16
278          sample.basic.hello_world.singlethread:
279            build_only: true
280            extra_args: CONF_FILE=prj_single.conf
281            filter: not CONFIG_BT
282            tags: tests
283            min_ram: 16
284
285The full canonical name for each test case is:``<path to test case>/<test entry>``
286
287Each test block in the testcase meta data can define the following key/value
288pairs:
289
290tags: <list of tags> (required)
291    A set of string tags for the testcase. Usually pertains to
292    functional domains but can be anything. Command line invocations
293    of this script can filter the set of tests to run based on tag.
294
295skip: <True|False> (default False)
296    skip testcase unconditionally. This can be used for broken tests.
297
298slow: <True|False> (default False)
299    Don't run this test case unless ``--enable-slow`` or ``--enable-slow-only`` was
300    passed in on the command line. Intended for time-consuming test cases that
301    are only run under certain circumstances, like daily builds. These test
302    cases are still compiled.
303
304extra_args: <list of extra arguments>
305    Extra arguments to pass to Make when building or running the
306    test case.
307
308extra_configs: <list of extra configurations>
309    Extra configuration options to be merged with a master prj.conf
310    when building or running the test case. For example:
311
312    .. code-block:: yaml
313
314        common:
315          tags: drivers adc
316        tests:
317          test:
318            depends_on: adc
319          test_async:
320            extra_configs:
321              - CONFIG_ADC_ASYNC=y
322
323    Using namespacing, it is possible to apply a configuration only to some
324    hardware. Currently both architectures and platforms are supported:
325
326    .. code-block:: yaml
327
328        common:
329          tags: drivers adc
330        tests:
331          test:
332            depends_on: adc
333          test_async:
334            extra_configs:
335              - arch:x86:CONFIG_ADC_ASYNC=y
336              - platform:qemu_x86:CONFIG_DEBUG=y
337
338
339build_only: <True|False> (default False)
340    If true, twister will not try to run the test even if the test is runnable
341    on the platform.
342
343    This keyword is reserved for tests that are used to test if some code
344    actually builds. A ``build_only`` test is not designed to be run in any
345    environment and should not be testing any functionality, it only verifies
346    that the code builds.
347
348    This option is often used to test drivers and the fact that they are correctly
349    enabled in Zephyr and that the code builds, for example sensor drivers. Such
350    test shall not be used to verify the functionality of the driver.
351
352build_on_all: <True|False> (default False)
353    If true, attempt to build test on all available platforms. This is mostly
354    used in CI for increased coverage. Do not use this flag in new tests.
355
356depends_on: <list of features>
357    A board or platform can announce what features it supports, this option
358    will enable the test only those platforms that provide this feature.
359
360levels: <list of levels>
361    Test levels this test should be part of. If a level is present, this
362    test will be selectable using the command line option ``--level <level name>``
363
364min_ram: <integer>
365    minimum amount of RAM in KB needed for this test to build and run. This is
366    compared with information provided by the board metadata.
367
368min_flash: <integer>
369    minimum amount of ROM in KB needed for this test to build and run. This is
370    compared with information provided by the board metadata.
371
372.. _twister_test_case_timeout:
373
374timeout: <number of seconds>
375    Length of time to run test before automatically killing it.
376    Default to 60 seconds.
377
378arch_allow: <list of arches, such as x86, arm, arc>
379    Set of architectures that this test case should only be run for.
380
381arch_exclude: <list of arches, such as x86, arm, arc>
382    Set of architectures that this test case should not run on.
383
384platform_allow: <list of platforms>
385    Set of platforms that this test case should only be run for. Do not use
386    this option to limit testing or building in CI due to time or resource
387    constraints, this option should only be used if the test or sample can
388    only be run on the allowed platform and nothing else.
389
390integration_platforms: <YML list of platforms/boards>
391    This option limits the scope to the listed platforms when twister is
392    invoked with the ``--integration`` option. Use this instead of
393    platform_allow if the goal is to limit scope due to timing or
394    resource constraints.
395
396platform_exclude: <list of platforms>
397    Set of platforms that this test case should not run on.
398
399extra_sections: <list of extra binary sections>
400    When computing sizes, twister will report errors if it finds
401    extra, unexpected sections in the Zephyr binary unless they are named
402    here. They will not be included in the size calculation.
403
404sysbuild: <True|False> (default False)
405    Build the project using sysbuild infrastructure. Only the main project's
406    generated devicetree and Kconfig will be used for filtering tests.
407    on device testing must use the hardware map, or west flash to load
408    the images onto the target. The ``--erase`` option of west flash is
409    not supported with this option. Usage of unsupported options will result
410    in tests requiring sysbuild support being skipped.
411
412harness: <string>
413    A harness keyword in the ``testcase.yaml`` file identifies a Twister
414    harness needed to run a test successfully. A harness is a feature of
415    Twister and implemented by Twister, some harnesses are defined as
416    placeholders and have no implementation yet.
417
418    A harness can be seen as the handler that needs to be implemented in
419    Twister to be able to evaluate if a test passes criteria. For example, a
420    keyboard harness is set on tests that require keyboard interaction to reach
421    verdict on whether a test has passed or failed, however, Twister lack this
422    harness implementation at the moment.
423
424    Supported harnesses:
425
426    - ztest
427    - test
428    - console
429    - pytest
430    - gtest
431    - robot
432
433    Harnesses ``ztest``, ``gtest`` and ``console`` are based on parsing of the
434    output and matching certain phrases. ``ztest`` and ``gtest`` harnesses look
435    for pass/fail/etc. frames defined in those frameworks. Use ``gtest``
436    harness if you've already got tests written in the gTest framework and do
437    not wish to update them to zTest. The ``console`` harness tells Twister to
438    parse a test's text output for a regex defined in the test's YAML file.
439    The ``robot`` harness is used to execute Robot Framework test suites
440    in the Renode simulation framework.
441
442    Some widely used harnesses that are not supported yet:
443
444    - keyboard
445    - net
446    - bluetooth
447
448    Harness ``bsim`` is implemented in limited way - it helps only to copy the
449    final executable (``zephyr.exe``) from build directory to BabbleSim's
450    ``bin`` directory (``${BSIM_OUT_PATH}/bin``). This action is useful to allow
451    BabbleSim's tests to directly run after. By default, the executable file
452    name is (with dots and slashes replaced by underscores):
453    ``bs_<platform_name>_<test_path>_<test_scenario_name>``.
454    This name can be overridden with the ``bsim_exe_name`` option in
455    ``harness_config`` section.
456
457platform_key: <list of platform attributes>
458    Often a test needs to only be built and run once to qualify as passing.
459    Imagine a library of code that depends on the platform architecture where
460    passing the test on a single platform for each arch is enough to qualify the
461    tests and code as passing. The platform_key attribute enables doing just
462    that.
463
464    For example to key on (arch, simulation) to ensure a test is run once
465    per arch and simulation (as would be most common):
466
467    .. code-block:: yaml
468
469      platform_key:
470        - arch
471        - simulation
472
473    Adding platform (board) attributes to include things such as soc name,
474    soc family, and perhaps sets of IP blocks implementing each peripheral
475    interface would enable other interesting uses. For example, this could enable
476    building and running SPI tests once for each unique IP block.
477
478harness_config: <harness configuration options>
479    Extra harness configuration options to be used to select a board and/or
480    for handling generic Console with regex matching. Config can announce
481    what features it supports. This option will enable the test to run on
482    only those platforms that fulfill this external dependency.
483
484    The following options are currently supported:
485
486    type: <one_line|multi_line> (required)
487        Depends on the regex string to be matched
488
489    regex: <list of regular expressions> (required)
490        Strings with regular expressions to match with the test's output
491        to confirm the test runs as expected.
492
493    ordered: <True|False> (default False)
494        Check the regular expression strings in orderly or randomly fashion
495
496    repeat: <integer>
497        Number of times to validate the repeated regex expression
498
499    record: <recording options> (optional)
500      regex: <regular expression> (required)
501        The regular expression with named subgroups to match data fields
502        at the test's output lines where the test provides some custom data
503        for further analysis. These records will be written into the build
504        directory 'recording.csv' file as well as 'recording' property
505        of the test suite object in 'twister.json'.
506
507        For example, to extract three data fields 'metric', 'cycles', 'nanoseconds':
508
509        .. code-block:: yaml
510
511          record:
512            regex: "(?P<metric>.*):(?P<cycles>.*) cycles, (?P<nanoseconds>.*) ns"
513
514    fixture: <expression>
515        Specify a test case dependency on an external device(e.g., sensor),
516        and identify setups that fulfill this dependency. It depends on
517        specific test setup and board selection logic to pick the particular
518        board(s) out of multiple boards that fulfill the dependency in an
519        automation setup based on ``fixture`` keyword. Some sample fixture names
520        are i2c_hts221, i2c_bme280, i2c_FRAM, ble_fw and gpio_loop.
521
522        Only one fixture can be defined per testcase and the fixture name has to
523        be unique across all tests in the test suite.
524
525.. _pytest_root:
526
527    pytest_root: <list of pytest testpaths> (default pytest)
528        Specify a list of pytest directories, files or subtests that need to be
529        executed when a test case begins to run. The default pytest directory is
530        ``pytest``. After the pytest run is finished, Twister will check if
531        the test case passed or failed according to the pytest report.
532        As an example, a list of valid pytest roots is presented below:
533
534        .. code-block:: yaml
535
536            harness_config:
537              pytest_root:
538                - "pytest/test_shell_help.py"
539                - "../shell/pytest/test_shell.py"
540                - "/tmp/test_shell.py"
541                - "~/tmp/test_shell.py"
542                - "$ZEPHYR_BASE/samples/subsys/testsuite/pytest/shell/pytest/test_shell.py"
543                - "pytest/test_shell_help.py::test_shell2_sample"  # select pytest subtest
544                - "pytest/test_shell_help.py::test_shell2_sample[param_a]"  # select pytest parametrized subtest
545
546.. _pytest_args:
547
548    pytest_args: <list of arguments> (default empty)
549        Specify a list of additional arguments to pass to ``pytest`` e.g.:
550        ``pytest_args: [‘-k=test_method’, ‘--log-level=DEBUG’]``. Note that
551        ``--pytest-args`` can be passed multiple times to pass several arguments
552        to the pytest.
553
554.. _pytest_dut_scope:
555
556    pytest_dut_scope: <function|class|module|package|session> (default function)
557        The scope for which ``dut`` and ``shell`` pytest fixtures are shared.
558        If the scope is set to ``function``, DUT is launched for every test case
559        in python script. For ``session`` scope, DUT is launched only once.
560
561    robot_test_path: <robot file path> (default empty)
562        Specify a path to a file containing a Robot Framework test suite to be run.
563
564    bsim_exe_name: <string>
565        If provided, the executable filename when copying to BabbleSim's bin
566        directory, will be ``bs_<platform_name>_<bsim_exe_name>`` instead of the
567        default based on the test path and scenario name.
568
569    The following is an example yaml file with a few harness_config options.
570
571    .. code-block:: yaml
572
573         sample:
574           name: HTS221 Temperature and Humidity Monitor
575         common:
576           tags: sensor
577           harness: console
578           harness_config:
579             type: multi_line
580             ordered: false
581             regex:
582               - "Temperature:(.*)C"
583               - "Relative Humidity:(.*)%"
584             fixture: i2c_hts221
585         tests:
586           test:
587             tags: sensors
588             depends_on: i2c
589
590    The following is an example yaml file with pytest harness_config options,
591    default pytest_root name "pytest" will be used if pytest_root not specified.
592    please refer the examples in samples/subsys/testsuite/pytest/.
593
594    .. code-block:: yaml
595
596        common:
597          harness: pytest
598        tests:
599          pytest.example.directories:
600            harness_config:
601              pytest_root:
602                - pytest_dir1
603                - $ENV_VAR/samples/test/pytest_dir2
604          pytest.example.files_and_subtests:
605            harness_config:
606              pytest_root:
607                - pytest/test_file_1.py
608                - test_file_2.py::test_A
609                - test_file_2.py::test_B[param_a]
610
611    The following is an example yaml file with robot harness_config options.
612
613    .. code-block:: yaml
614
615        tests:
616          robot.example:
617            harness: robot
618            harness_config:
619              robot_test_path: [robot file path]
620
621filter: <expression>
622    Filter whether the testcase should be run by evaluating an expression
623    against an environment containing the following values:
624
625    .. code-block:: none
626
627            { ARCH : <architecture>,
628              PLATFORM : <platform>,
629              <all CONFIG_* key/value pairs in the test's generated defconfig>,
630              *<env>: any environment variable available
631            }
632
633    Twister will first evaluate the expression to find if a "limited" cmake call, i.e. using package_helper cmake script,
634    can be done. Existence of "dt_*" entries indicates devicetree is needed.
635    Existence of "CONFIG*" entries indicates kconfig is needed.
636    If there are no other types of entries in the expression a filtration can be done without creating a complete build system.
637    If there are entries of other types a full cmake is required.
638
639    The grammar for the expression language is as follows:
640
641    .. code-block:: antlr
642
643        expression : expression 'and' expression
644                   | expression 'or' expression
645                   | 'not' expression
646                   | '(' expression ')'
647                   | symbol '==' constant
648                   | symbol '!=' constant
649                   | symbol '<' NUMBER
650                   | symbol '>' NUMBER
651                   | symbol '>=' NUMBER
652                   | symbol '<=' NUMBER
653                   | symbol 'in' list
654                   | symbol ':' STRING
655                   | symbol
656                   ;
657
658        list : '[' list_contents ']';
659
660        list_contents : constant (',' constant)*;
661
662        constant : NUMBER | STRING;
663
664    For the case where ``expression ::= symbol``, it evaluates to ``true``
665    if the symbol is defined to a non-empty string.
666
667    Operator precedence, starting from lowest to highest:
668
669       * or (left associative)
670       * and (left associative)
671       * not (right associative)
672       * all comparison operators (non-associative)
673
674    ``arch_allow``, ``arch_exclude``, ``platform_allow``, ``platform_exclude``
675    are all syntactic sugar for these expressions. For instance:
676
677    .. code-block:: none
678
679        arch_exclude = x86 arc
680
681    Is the same as:
682
683    .. code-block:: none
684
685        filter = not ARCH in ["x86", "arc"]
686
687    The ``:`` operator compiles the string argument as a regular expression,
688    and then returns a true value only if the symbol's value in the environment
689    matches. For example, if ``CONFIG_SOC="stm32f107xc"`` then
690
691    .. code-block:: none
692
693        filter = CONFIG_SOC : "stm.*"
694
695    Would match it.
696
697required_snippets: <list of needed snippets>
698    :ref:`Snippets <snippets>` are supported in twister for test cases that
699    require them. As with normal applications, twister supports using the base
700    zephyr snippet directory and test application directory for finding
701    snippets. Listed snippets will filter supported tests for boards (snippets
702    must be compatible with a board for the test to run on them, they are not
703    optional).
704
705    The following is an example yaml file with 2 required snippets.
706
707    .. code-block:: yaml
708
709        tests:
710          snippet.example:
711            required_snippets:
712              - cdc-acm-console
713              - user-snippet-example
714
715The set of test cases that actually run depends on directives in the testcase
716filed and options passed in on the command line. If there is any confusion,
717running with ``-v`` or examining the discard report
718(:file:`twister_discard.csv`) can help show why particular test cases were
719skipped.
720
721Metrics (such as pass/fail state and binary size) for the last code
722release are stored in ``scripts/release/twister_last_release.csv``.
723To update this, pass the ``--all --release`` options.
724
725To load arguments from a file, add ``+`` before the file name, e.g.,
726``+file_name``. File content must be one or more valid arguments separated by
727line break instead of white spaces.
728
729Most everyday users will run with no arguments.
730
731Managing tests timeouts
732***********************
733
734There are several parameters which control tests timeouts on various levels:
735
736* ``timeout`` option in each test case. See :ref:`here <twister_test_case_timeout>` for more
737  details.
738* ``timeout_multiplier`` option in board configuration. See
739  :ref:`here <twister_board_timeout_multiplier>` for more details.
740* ``--timeout-multiplier`` twister option which can be used to adjust timeouts in exact twister run.
741  It can be useful in case of simulation platform as simulation time may depend on the host
742  speed & load or we may select different simulation method (i.e. cycle accurate but slower
743  one), etc...
744
745Overall test case timeout is a multiplication of these three parameters.
746
747Running in Integration Mode
748***************************
749
750This mode is used in continuous integration (CI) and other automated
751environments used to give developers fast feedback on changes. The mode can
752be activated using the ``--integration`` option of twister and narrows down
753the scope of builds and tests if applicable to platforms defined under the
754integration keyword in the testcase definition file (testcase.yaml and
755sample.yaml).
756
757
758Running tests on custom emulator
759********************************
760
761Apart from the already supported QEMU and other simulated environments, Twister
762supports running any out-of-tree custom emulator defined in the board's :file:`board.cmake`.
763To use this type of simulation, add the following properties to
764:file:`custom_board/custom_board.yaml`:
765
766.. code-block:: yaml
767
768   simulation: custom
769   simulation_exec: <name_of_emu_binary>
770
771This tells Twister that the board is using a custom emulator called ``<name_of_emu_binary>``,
772make sure this binary exists in the PATH.
773
774Then, in :file:`custom_board/board.cmake`, set the supported emulation platforms to ``custom``:
775
776.. code-block:: cmake
777
778   set(SUPPORTED_EMU_PLATFORMS custom)
779
780Finally, implement the ``run_custom`` target in :file:`custom_board/board.cmake`.
781It should look something like this:
782
783.. code-block:: cmake
784
785   add_custom_target(run_custom
786     COMMAND
787     <name_of_emu_binary to invoke during 'run'>
788     <any args to be passed to the command, i.e. ${BOARD}, ${APPLICATION_BINARY_DIR}/zephyr/zephyr.elf>
789     WORKING_DIRECTORY ${APPLICATION_BINARY_DIR}
790     DEPENDS ${logical_target_for_zephyr_elf}
791     USES_TERMINAL
792     )
793
794Running Tests on Hardware
795*************************
796
797Beside being able to run tests in QEMU and other simulated environments,
798twister supports running most of the tests on real devices and produces
799reports for each run with detailed FAIL/PASS results.
800
801
802Executing tests on a single device
803===================================
804
805To use this feature on a single connected device, run twister with
806the following new options:
807
808.. tabs::
809
810   .. group-tab:: Linux
811
812      .. code-block:: bash
813
814	      scripts/twister --device-testing --device-serial /dev/ttyACM0 \
815	      --device-serial-baud 115200 -p frdm_k64f  -T tests/kernel
816
817   .. group-tab:: Windows
818
819      .. code-block:: bat
820
821	      python .\scripts\twister --device-testing --device-serial COM1 \
822	      --device-serial-baud 115200 -p frdm_k64f  -T tests/kernel
823
824The ``--device-serial`` option denotes the serial device the board is connected to.
825This needs to be accessible by the user running twister. You can run this on
826only one board at a time, specified using the ``--platform`` option.
827
828The ``--device-serial-baud`` option is only needed if your device does not run at
829115200 baud.
830
831To support devices without a physical serial port, use the ``--device-serial-pty``
832option. In this cases, log messages are captured for example using a script.
833In this case you can run twister with the following options:
834
835.. tabs::
836
837   .. group-tab:: Linux
838
839      .. code-block:: bash
840
841         scripts/twister --device-testing --device-serial-pty "script.py" \
842         -p intel_adsp_cavs25 -T tests/kernel
843
844   .. group-tab:: Windows
845
846      .. note::
847
848         Not supported on Windows OS
849
850The script is user-defined and handles delivering the messages which can be
851used by twister to determine the test execution status.
852
853The ``--device-flash-timeout`` option allows to set explicit timeout on the
854device flash operation, for example when device flashing takes significantly
855large time.
856
857The ``--device-flash-with-test`` option indicates that on the platform
858the flash operation also executes a test case, so the flash timeout is
859increased by a test case timeout.
860
861Executing tests on multiple devices
862===================================
863
864To build and execute tests on multiple devices connected to the host PC, a
865hardware map needs to be created with all connected devices and their
866details such as the serial device, baud and their IDs if available.
867Run the following command to produce the hardware map:
868
869.. tabs::
870
871   .. group-tab:: Linux
872
873      .. code-block:: bash
874
875         ./scripts/twister --generate-hardware-map map.yml
876
877   .. group-tab:: Windows
878
879      .. code-block:: bat
880
881         python .\scripts\twister --generate-hardware-map map.yml
882
883The generated hardware map file (map.yml) will have the list of connected
884devices, for example:
885
886.. tabs::
887
888   .. group-tab:: Linux
889
890      .. code-block:: yaml
891
892         - connected: true
893           id: OSHW000032254e4500128002ab98002784d1000097969900
894           platform: unknown
895           product: DAPLink CMSIS-DAP
896           runner: pyocd
897           serial: /dev/cu.usbmodem146114202
898         - connected: true
899           id: 000683759358
900           platform: unknown
901           product: J-Link
902           runner: unknown
903           serial: /dev/cu.usbmodem0006837593581
904
905   .. group-tab:: Windows
906
907      .. code-block:: yaml
908
909         - connected: true
910           id: OSHW000032254e4500128002ab98002784d1000097969900
911           platform: unknown
912           product: unknown
913           runner: unknown
914           serial: COM1
915         - connected: true
916           id: 000683759358
917           platform: unknown
918           product: unknown
919           runner: unknown
920           serial: COM2
921
922
923Any options marked as ``unknown`` need to be changed and set with the correct
924values, in the above example the platform names, the products and the runners need
925to be replaced with the correct values corresponding to the connected hardware.
926In this example we are using a reel_board and an nrf52840dk_nrf52840:
927
928.. tabs::
929
930   .. group-tab:: Linux
931
932      .. code-block:: yaml
933
934         - connected: true
935           id: OSHW000032254e4500128002ab98002784d1000097969900
936           platform: reel_board
937           product: DAPLink CMSIS-DAP
938           runner: pyocd
939           serial: /dev/cu.usbmodem146114202
940           baud: 9600
941         - connected: true
942           id: 000683759358
943           platform: nrf52840dk_nrf52840
944           product: J-Link
945           runner: nrfjprog
946           serial: /dev/cu.usbmodem0006837593581
947           baud: 9600
948
949   .. group-tab:: Windows
950
951      .. code-block:: yaml
952
953         - connected: true
954           id: OSHW000032254e4500128002ab98002784d1000097969900
955           platform: reel_board
956           product: DAPLink CMSIS-DAP
957           runner: pyocd
958           serial: COM1
959           baud: 9600
960         - connected: true
961           id: 000683759358
962           platform: nrf52840dk_nrf52840
963           product: J-Link
964           runner: nrfjprog
965           serial: COM2
966           baud: 9600
967
968The baud entry is only needed if not running at 115200.
969
970If the map file already exists, then new entries are added and existing entries
971will be updated. This way you can use one single master hardware map and update
972it for every run to get the correct serial devices and status of the devices.
973
974With the hardware map ready, you can run any tests by pointing to the map
975
976.. tabs::
977
978   .. group-tab:: Linux
979
980      .. code-block:: bash
981
982         ./scripts/twister --device-testing --hardware-map map.yml -T samples/hello_world/
983
984   .. group-tab:: Windows
985
986      .. code-block:: bat
987
988         python .\scripts\twister --device-testing --hardware-map map.yml -T samples\hello_world
989
990The above command will result in twister building tests for the platforms
991defined in the hardware map and subsequently flashing and running the tests
992on those platforms.
993
994.. note::
995
996  Currently only boards with support for pyocd, nrfjprog, jlink, openocd, or dediprog
997  are supported with the hardware map features. Boards that require other runners to flash the
998  Zephyr binary are still work in progress.
999
1000Hardware map allows to set ``--device-flash-timeout`` and ``--device-flash-with-test``
1001command line options as ``flash-timeout`` and ``flash-with-test`` fields respectively.
1002These hardware map values override command line options for the particular platform.
1003
1004Serial PTY support using ``--device-serial-pty``  can also be used in the
1005hardware map:
1006
1007.. code-block:: yaml
1008
1009   - connected: true
1010     id: None
1011     platform: intel_adsp_cavs25
1012     product: None
1013     runner: intel_adsp
1014     serial_pty: path/to/script.py
1015     runner_params:
1016       - --remote-host=remote_host_ip_addr
1017       - --key=/path/to/key.pem
1018
1019
1020The runner_params field indicates the parameters you want to pass to the
1021west runner. For some boards the west runner needs some extra parameters to
1022work. It is equivalent to following west and twister commands.
1023
1024.. tabs::
1025
1026   .. group-tab:: Linux
1027
1028      .. code-block:: bash
1029
1030         west flash --remote-host remote_host_ip_addr --key /path/to/key.pem
1031
1032         twister -p intel_adsp_cavs25 --device-testing --device-serial-pty script.py
1033         --west-flash="--remote-host=remote_host_ip_addr,--key=/path/to/key.pem"
1034
1035   .. group-tab:: Windows
1036
1037      .. note::
1038
1039         Not supported on Windows OS
1040
1041.. note::
1042
1043  For serial PTY, the "--generate-hardware-map" option cannot scan it out
1044  and generate a correct hardware map automatically. You have to edit it
1045  manually according to above example. This is because the serial port
1046  of the PTY is not fixed and being allocated in the system at runtime.
1047
1048Fixtures
1049+++++++++
1050
1051Some tests require additional setup or special wiring specific to the test.
1052Running the tests without this setup or test fixture may fail. A testcase can
1053specify the fixture it needs which can then be matched with hardware capability
1054of a board and the fixtures it supports via the command line or using the hardware
1055map file.
1056
1057Fixtures are defined in the hardware map file as a list:
1058
1059.. code-block:: yaml
1060
1061      - connected: true
1062        fixtures:
1063          - gpio_loopback
1064        id: 0240000026334e450015400f5e0e000b4eb1000097969900
1065        platform: frdm_k64f
1066        product: DAPLink CMSIS-DAP
1067        runner: pyocd
1068        serial: /dev/ttyACM9
1069
1070When running ``twister`` with ``--device-testing``, the configured fixture
1071in the hardware map file will be matched to testcases requesting the same fixtures
1072and these tests will be executed on the boards that provide this fixture.
1073
1074.. figure:: fixtures.svg
1075   :figclass: align-center
1076
1077Fixtures can also be provided via twister command option ``--fixture``, this option
1078can be used multiple times and all given fixtures will be appended as a list. And the
1079given fixtures will be assigned to all boards, this means that all boards set by
1080current twister command can run those testcases which request the same fixtures.
1081
1082Notes
1083+++++
1084
1085It may be useful to annotate board descriptions in the hardware map file
1086with additional information.  Use the ``notes`` keyword to do this.  For
1087example:
1088
1089.. code-block:: yaml
1090
1091    - connected: false
1092      fixtures:
1093        - gpio_loopback
1094      id: 000683290670
1095      notes: An nrf5340dk_nrf5340 is detected as an nrf52840dk_nrf52840 with no serial
1096        port, and three serial ports with an unknown platform.  The board id of the serial
1097        ports is not the same as the board id of the development kit.  If you regenerate
1098        this file you will need to update serial to reference the third port, and platform
1099        to nrf5340dk_nrf5340_cpuapp or another supported board target.
1100      platform: nrf52840dk_nrf52840
1101      product: J-Link
1102      runner: jlink
1103      serial: null
1104
1105Overriding Board Identifier
1106+++++++++++++++++++++++++++
1107
1108When (re-)generated the hardware map file will contain an ``id`` keyword
1109that serves as the argument to ``--board-id`` when flashing.  In some
1110cases the detected ID is not the correct one to use, for example when
1111using an external J-Link probe.  The ``probe_id`` keyword overrides the
1112``id`` keyword for this purpose.   For example:
1113
1114.. code-block:: yaml
1115
1116    - connected: false
1117      id: 0229000005d9ebc600000000000000000000000097969905
1118      platform: mimxrt1060_evk
1119      probe_id: 000609301751
1120      product: DAPLink CMSIS-DAP
1121      runner: jlink
1122      serial: null
1123
1124Quarantine
1125++++++++++
1126
1127Twister allows user to provide configuration files defining a list of tests or
1128platforms to be put under quarantine. Such tests will be skipped and marked
1129accordingly in the output reports. This feature is especially useful when
1130running larger test suits, where a failure of one test can affect the execution
1131of other tests (e.g. putting the physical board in a corrupted state).
1132
1133To use the quarantine feature one has to add the argument
1134``--quarantine-list <PATH_TO_QUARANTINE_YAML>`` to a twister call.
1135Multiple quarantine files can be used.
1136The current status of tests on the quarantine list can also be verified by adding
1137``--quarantine-verify`` to the above argument. This will make twister skip all tests
1138which are not on the given list.
1139
1140A quarantine yaml has to be a sequence of dictionaries. Each dictionary has to have
1141``scenarios`` and ``platforms`` entries listing combinations of scenarios and platforms
1142to put under quarantine. In addition, an optional entry ``comment`` can be used, where
1143some more details can be given (e.g. link to a reported issue). These comments will also
1144be added to the output reports.
1145
1146When quarantining a class of tests or many scenarios in a single testsuite or
1147when dealing with multiple issues within a subsystem, it is possible to use
1148regular expressions, for example, **kernel.*** would quarantine
1149all kernel tests.
1150
1151An example of entries in a quarantine yaml:
1152
1153.. code-block:: yaml
1154
1155    - scenarios:
1156        - sample.basic.helloworld
1157      comment: "Link to the issue: https://github.com/zephyrproject-rtos/zephyr/pull/33287"
1158
1159    - scenarios:
1160        - kernel.common
1161        - kernel.common.(misra|tls)
1162        - kernel.common.nano64
1163      platforms:
1164        - .*_cortex_.*
1165        - native_sim
1166
1167To exclude a platform, use the following syntax:
1168
1169.. code-block:: yaml
1170
1171    - platforms:
1172      - qemu_x86
1173      comment: "broken qemu"
1174
1175Additionally you can quarantine entire architectures or a specific simulator for executing tests.
1176
1177Test Configuration
1178******************
1179
1180A test configuration can be used to customize various aspects of twister
1181and the default enabled options and features. This allows tweaking the filtering
1182capabilities depending on the environment and makes it possible to adapt and
1183improve coverage when targeting different sets of platforms.
1184
1185The test configuration also adds support for test levels and the ability to
1186assign a specific test to one or more levels. Using command line options of
1187twister it is then possible to select a level and just execute the tests
1188included in this level.
1189
1190Additionally, the test configuration allows defining level
1191dependencies and additional inclusion of tests into a specific level if
1192the test itself does not have this information already.
1193
1194In the configuration file you can include complete components using
1195regular expressions and you can specify which test level to import from
1196the same file, making management of levels easier.
1197
1198To help with testing outside of upstream CI infrastructure, additional
1199options are available in the configuration file, which can be hosted
1200locally. As of now, those options are available:
1201
1202- Ability to ignore default platforms as defined in board definitions
1203  (Those are mostly emulation platforms used to run tests in upstream
1204  CI)
1205- Option to specify your own list of default platforms overriding what
1206  upstream defines.
1207- Ability to override `build_on_all` options used in some testcases.
1208  This will treat tests or sample as any other just build for default
1209  platforms you specify in the configuration file or on the command line.
1210- Ignore some logic in twister to expand platform coverage in cases where
1211  default platforms are not in scope.
1212
1213
1214Platform Configuration
1215======================
1216
1217The following options control platform filtering in twister:
1218
1219- `override_default_platforms`: override default key a platform sets in board
1220  configuration and instead use the list of platforms provided in the
1221  configuration file as the list of default platforms. This option is set to
1222  False by default.
1223- `increased_platform_scope`: This option is set to True by default, when
1224  disabled, twister will not increase platform coverage automatically and will
1225  only build and run tests on the specified platforms.
1226- `default_platforms`: A list of additional default platforms to add. This list
1227  can either be used to replace the existing default platforms or can extend it
1228  depending on the value of `override_default_platforms`.
1229
1230And example platforms configuration:
1231
1232.. code-block:: yaml
1233
1234	platforms:
1235	  override_default_platforms: true
1236	  increased_platform_scope: false
1237	  default_platforms:
1238	    - qemu_x86
1239
1240
1241Test Level Configuration
1242========================
1243
1244The test configuration allows defining test levels, level dependencies and
1245additional inclusion of tests into a specific test level if the test itself
1246does not have this information already.
1247
1248In the configuration file you can include complete components using
1249regular expressions and you can specify which test level to import from
1250the same file, making management of levels simple.
1251
1252And example test level configuration:
1253
1254.. code-block:: yaml
1255
1256	levels:
1257	  - name: my-test-level
1258	    description: >
1259	      my custom test level
1260	    adds:
1261	      - kernel.threads.*
1262	      - kernel.timer.behavior
1263	      - arch.interrupt
1264	      - boards.*
1265
1266
1267Combined configuration
1268======================
1269
1270To mix the Platform and level configuration, you can take an example as below:
1271
1272An example platforms plus level configuration:
1273
1274.. code-block:: yaml
1275
1276	platforms:
1277	  override_default_platforms: true
1278	  default_platforms:
1279	    - frdm_k64f
1280	levels:
1281	  - name: smoke
1282	    description: >
1283	        A plan to be used verifying basic zephyr features.
1284	  - name: unit
1285	    description: >
1286	        A plan to be used verifying unit test.
1287	  - name: integration
1288	    description: >
1289	        A plan to be used verifying integration.
1290	  - name: acceptance
1291	    description: >
1292	        A plan to be used verifying acceptance.
1293	  - name: system
1294	    description: >
1295	        A plan to be used verifying system.
1296	  - name: regression
1297	    description: >
1298	        A plan to be used verifying regression.
1299
1300
1301To run with above test_config.yaml file, only default_platforms with given test level
1302test cases will run.
1303
1304.. tabs::
1305
1306   .. group-tab:: Linux
1307
1308      .. code-block:: bash
1309
1310         scripts/twister --test-config=<path to>/test_config.yaml
1311          -T tests --level="smoke"
1312
1313
1314
1315Running in Tests in Random Order
1316********************************
1317Enable ZTEST framework's :kconfig:option:`CONFIG_ZTEST_SHUFFLE` config option to
1318run your tests in random order.  This can be beneficial for identifying
1319dependencies between test cases. For native_sim platforms, you can provide
1320the seed to the random number generator by providing ``-seed=value`` as an
1321argument to twister. See :ref:`Shuffling Test Sequence <ztest_shuffle>` for more
1322details.
1323
1324Robot Framework Tests
1325*********************
1326Zephyr supports `Robot Framework <https://robotframework.org/>`_ as one of solutions for automated testing.
1327
1328Robot files allow you to express interactive test scenarios in human-readable text format and execute them in simulation or against hardware.
1329At this moment Zephyr integration supports running Robot tests in the `Renode <https://renode.io/>`_ simulation framework.
1330
1331To execute a Robot test suite with twister, run the following command:
1332
1333.. tabs::
1334
1335   .. group-tab:: Linux
1336
1337      .. code-block:: bash
1338
1339         $ ./scripts/twister --platform hifive1 --test samples/subsys/shell/shell_module/sample.shell.shell_module.robot
1340
1341   .. group-tab:: Windows
1342
1343      .. code-block:: bat
1344
1345         python .\scripts\twister --platform hifive1 --test samples/subsys/shell/shell_module/sample.shell.shell_module.robot
1346
1347It's also possible to run it by `west` directly, with:
1348
1349.. code-block:: bash
1350
1351   $ ROBOT_FILES=shell_module.robot west build -p -b hifive1 -s samples/subsys/shell/shell_module -t run_renode_test
1352
1353Writing Robot tests
1354===================
1355
1356For the list of keywords provided by the Robot Framework itself, refer to `the official Robot documentation <https://robotframework.org/robotframework/>`_.
1357
1358Information on writing and running Robot Framework tests in Renode can be found in `the testing section <https://renode.readthedocs.io/en/latest/introduction/testing.html>`_ of Renode documentation.
1359It provides a list of the most commonly used keywords together with links to the source code where those are defined.
1360
1361It's possible to extend the framework by adding new keywords expressed directly in Robot test suite files, as an external Python library or, like Renode does it, dynamically via XML-RPC.
1362For details see the `extending Robot Framework <https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#extending-robot-framework>`_ section in the official Robot documentation.
1363
1364Running a single testsuite
1365==========================
1366
1367To run a single testsuite instead of a whole group of test you can run:
1368
1369.. code-block:: bash
1370
1371   $ twister -p qemu_riscv32 -s tests/kernel/interrupt/arch.shared_interrupt
1372