#!/usr/bin/env python3 # vim: set syntax=python ts=4 : # Copyright (c) 2020 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Zephyr Test Runner (twister) Also check the "User and Developer Guides" at https://docs.zephyrproject.org/ This script scans for the set of unit test applications in the git repository and attempts to execute them. By default, it tries to build each test case on one platform per architecture, using a precedence list defined in an architecture configuration file, and if possible run the tests in any available emulators or simulators on the system. Test cases are detected by the presence of a 'testcase.yaml' or a sample.yaml files in the application's project directory. This file may contain one or more blocks, each identifying a test scenario. The title of the block is a name for the test case, which only needs to be unique for the test cases specified in that testcase meta-data. The full canonical name for each test case is /. Each test block in the testcase meta data can define the following key/value pairs: tags: (required) A set of string tags for the testcase. Usually pertains to functional domains but can be anything. Command line invocations of this script can filter the set of tests to run based on tag. skip: (default False) skip testcase unconditionally. This can be used for broken tests. slow: (default False) Don't build or run this test case unless --enable-slow was passed in on the command line. Intended for time-consuming test cases that are only run under certain circumstances, like daily builds. extra_args: Extra cache entries to pass to CMake when building or running the test case. extra_configs: Extra configuration options to be merged with a master prj.conf when building or running the test case. build_only: (default False) If true, don't try to run the test even if the selected platform supports it. build_on_all: (default False) If true, attempt to build test on all available platforms. depends_on: A board or platform can announce what features it supports, this option will enable the test only those platforms that provide this feature. min_ram: minimum amount of RAM needed for this test to build and run. This is compared with information provided by the board metadata. min_flash: minimum amount of ROM needed for this test to build and run. This is compared with information provided by the board metadata. modules: Add list of modules needed for this sample to build and run. timeout: Length of time to run test in emulator before automatically killing it. Default to 60 seconds. arch_allow: Set of architectures that this test case should only be run for. arch_exclude: Set of architectures that this test case should not run on. platform_allow: Set of platforms that this test case should only be run for. platform_exclude: Set of platforms that this test case should not run on. extra_sections: When computing sizes, twister will report errors if it finds extra, unexpected sections in the Zephyr binary unless they are named here. They will not be included in the size calculation. filter: Filter whether the testcase should be run by evaluating an expression against an environment containing the following values: { ARCH : , PLATFORM : , , , , *: any environment variable available } The grammar for the expression language is as follows: expression ::= expression "and" expression | expression "or" expression | "not" expression | "(" expression ")" | symbol "==" constant | symbol "!=" constant | symbol "<" number | symbol ">" number | symbol ">=" number | symbol "<=" number | symbol "in" list | symbol ":" string | symbol list ::= "[" list_contents "]" list_contents ::= constant | list_contents "," constant constant ::= number | string For the case where expression ::= symbol, it evaluates to true if the symbol is defined to a non-empty string. Operator precedence, starting from lowest to highest: or (left associative) and (left associative) not (right associative) all comparison operators (non-associative) arch_allow, arch_exclude, platform_allow, platform_exclude are all syntactic sugar for these expressions. For instance arch_exclude = x86 arc Is the same as: filter = not ARCH in ["x86", "arc"] The ':' operator compiles the string argument as a regular expression, and then returns a true value only if the symbol's value in the environment matches. For example, if CONFIG_SOC="stm32f107xc" then filter = CONFIG_SOC : "stm.*" Would match it. The set of test cases that actually run depends on directives in the testcase filed and options passed in on the command line. If there is any confusion, running with -v or examining the discard report (twister_discard.csv) can help show why particular test cases were skipped. Metrics (such as pass/fail state and binary size) for the last code release are stored in scripts/release/twister_last_release.csv. To update this, pass the --all --release options. To load arguments from a file, write '+' before the file name, e.g., +file_name. File content must be one or more valid arguments separated by line break instead of white spaces. Most everyday users will run with no arguments. """ import os import argparse import sys import logging import time import itertools import shutil from collections import OrderedDict import multiprocessing from itertools import islice import csv from colorama import Fore from pathlib import Path from multiprocessing.managers import BaseManager import queue from zephyr_module import west_projects, parse_modules ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: # This file has been zephyr/scripts/twister for years, # and that is not going to change anytime soon. Let the user # run this script as ./scripts/twister without making them # set ZEPHYR_BASE. ZEPHYR_BASE = str(Path(__file__).resolve().parents[1]) # Propagate this decision to child processes. os.environ['ZEPHYR_BASE'] = ZEPHYR_BASE print(f'ZEPHYR_BASE unset, using "{ZEPHYR_BASE}"') try: from anytree import RenderTree, Node, find except ImportError: print("Install the anytree module to use the --test-tree option") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) from twisterlib import HardwareMap, TestSuite, SizeCalculator, CoverageTool, ExecutionCounter logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) def size_report(sc): logger.info(sc.filename) logger.info("SECTION NAME VMA LMA SIZE HEX SZ TYPE") for v in sc.sections: logger.info("%-17s 0x%08x 0x%08x %8d 0x%05x %-7s" % (v["name"], v["virt_addr"], v["load_addr"], v["size"], v["size"], v["type"])) logger.info("Totals: %d bytes (ROM), %d bytes (RAM)" % (sc.rom_size, sc.ram_size)) logger.info("") def export_tests(filename, tests): with open(filename, "wt") as csvfile: fieldnames = ['section', 'subsection', 'title', 'reference'] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) for test in tests: data = test.split(".") if len(data) > 1: subsec = " ".join(data[1].split("_")).title() rowdict = { "section": data[0].capitalize(), "subsection": subsec, "title": test, "reference": test } cw.writerow(rowdict) else: logger.error("{} can't be exported: ".format(test)) def parse_arguments(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.fromfile_prefix_chars = "+" case_select = parser.add_argument_group("Test case selection", """ Artificially long but functional example: $ ./scripts/twister -v \\ --testcase-root tests/ztest/base \\ --testcase-root tests/kernel \\ --test tests/ztest/base/testing.ztest.verbose_0 \\ --test tests/kernel/fifo/fifo_api/kernel.fifo "kernel.fifo.poll" is one of the test section names in __/fifo_api/testcase.yaml """) compare_group_option = parser.add_mutually_exclusive_group() platform_group_option = parser.add_mutually_exclusive_group() run_group_option = parser.add_mutually_exclusive_group() serial = parser.add_mutually_exclusive_group(required="--device-testing" in sys.argv) test_or_build = parser.add_mutually_exclusive_group() test_xor_subtest = case_select.add_mutually_exclusive_group() valgrind_asan_group = parser.add_mutually_exclusive_group() case_select.add_argument( "-E", "--save-tests", metavar="FILENAME", action="store", help="Append list of tests and platforms to be run to file.") case_select.add_argument( "-F", "--load-tests", metavar="FILENAME", action="store", help="Load list of tests and platforms to be run from file.") case_select.add_argument( "-T", "--testcase-root", action="append", default=[], help="Base directory to recursively search for test cases. All " "testcase.yaml files under here will be processed. May be " "called multiple times. Defaults to the 'samples/' and " "'tests/' directories at the base of the Zephyr tree.") case_select.add_argument( "-f", "--only-failed", action="store_true", help="Run only those tests that failed the previous twister run " "invocation.") case_select.add_argument("--list-tests", action="store_true", help="""List of all sub-test functions recursively found in all --testcase-root arguments. Note different sub-tests can share the same section name and come from different directories. The output is flattened and reports --sub-test names only, not their directories. For instance net.socket.getaddrinfo_ok and net.socket.fd_set belong to different directories. """) case_select.add_argument("--list-test-duplicates", action="store_true", help="""List tests with duplicate identifiers. """) case_select.add_argument("--test-tree", action="store_true", help="""Output the testsuite in a tree form""") compare_group_option.add_argument("--compare-report", help="Use this report file for size comparison") compare_group_option.add_argument( "-m", "--last-metrics", action="store_true", help="Instead of comparing metrics from the last --release, " "compare with the results of the previous twister " "invocation") platform_group_option.add_argument( "-G", "--integration", action="store_true", help="Run integration tests") platform_group_option.add_argument( "--emulation-only", action="store_true", help="Only build and run emulation platforms") run_group_option.add_argument( "--device-testing", action="store_true", help="Test on device directly. Specify the serial device to " "use with the --device-serial option.") run_group_option.add_argument("--generate-hardware-map", help="""Probe serial devices connected to this platform and create a hardware map file to be used with --device-testing """) serial.add_argument("--device-serial", help="""Serial device for accessing the board (e.g., /dev/ttyACM0) """) serial.add_argument("--device-serial-pty", help="""Script for controlling pseudoterminal. Twister believes that it interacts with a terminal when it actually interacts with the script. E.g "twister --device-testing --device-serial-pty