blob: 25e1a86a68f5618e123b31a7d8cbfc6b354f6190 [file] [log] [blame]
David Brazdilee5e25d2020-01-24 14:17:45 +00001#!/usr/bin/env python3
Andrew Scull18834872018-10-12 11:48:09 +01002#
Andrew Walbran692b3252019-03-07 15:51:31 +00003# Copyright 2018 The Hafnium Authors.
Andrew Scull18834872018-10-12 11:48:09 +01004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# https://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
David Brazdil2df24082019-09-05 11:55:08 +010017"""Script which drives invocation of tests and parsing their output to produce
18a results report.
Andrew Scullbc7189d2018-08-14 09:35:13 +010019"""
20
21from __future__ import print_function
22
Andrew Scull3b62f2b2018-08-21 14:26:12 +010023import xml.etree.ElementTree as ET
24
Andrew Scullbc7189d2018-08-14 09:35:13 +010025import argparse
David Brazdil2df24082019-09-05 11:55:08 +010026import collections
Andrew Scull04502e42018-09-03 14:54:52 +010027import datetime
David Brazdil4f9cf9a2020-02-06 17:34:44 +000028import importlib
Andrew Scullbc7189d2018-08-14 09:35:13 +010029import json
30import os
31import re
32import subprocess
33import sys
Andrew Walbran42bf2842020-06-05 18:50:19 +010034import time
Andrew Scullbc7189d2018-08-14 09:35:13 +010035
Andrew Scull845fc9b2019-04-03 12:44:26 +010036HFTEST_LOG_PREFIX = "[hftest] "
37HFTEST_LOG_FAILURE_PREFIX = "Failure:"
38HFTEST_LOG_FINISHED = "FINISHED"
39
David Brazdil17e76652020-01-29 14:44:19 +000040HFTEST_CTRL_GET_COMMAND_LINE = "[hftest_ctrl:get_command_line]"
41HFTEST_CTRL_FINISHED = "[hftest_ctrl:finished]"
42
David Brazdil2df24082019-09-05 11:55:08 +010043HF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
44 os.path.abspath(__file__))))
David Brazdil5715f042019-08-27 11:11:51 +010045DTC_SCRIPT = os.path.join(HF_ROOT, "build", "image", "dtc.py")
David Brazdil2df24082019-09-05 11:55:08 +010046FVP_BINARY = os.path.join(
47 os.path.dirname(HF_ROOT), "fvp", "Base_RevC_AEMv8A_pkg", "models",
48 "Linux64_GCC-4.9", "FVP_Base_RevC-2xAEMv8A")
David Brazdil21204ae2019-10-30 19:22:38 +000049FVP_PREBUILTS_ROOT = os.path.join(
50 HF_ROOT, "prebuilts", "linux-aarch64", "arm-trusted-firmware", "fvp")
David Brazdil2df24082019-09-05 11:55:08 +010051FVP_PREBUILT_DTS = os.path.join(
David Brazdil21204ae2019-10-30 19:22:38 +000052 FVP_PREBUILTS_ROOT, "fvp-base-gicv3-psci-1t.dts")
53FVP_PREBUILT_BL31 = os.path.join(FVP_PREBUILTS_ROOT, "bl31.bin")
Andrew Scull845fc9b2019-04-03 12:44:26 +010054
David Brazdil2df24082019-09-05 11:55:08 +010055def read_file(path):
56 with open(path, "r") as f:
57 return f.read()
Andrew Scull845fc9b2019-04-03 12:44:26 +010058
David Brazdil2df24082019-09-05 11:55:08 +010059def write_file(path, to_write, append=False):
60 with open(path, "a" if append else "w") as f:
61 f.write(to_write)
62
63def append_file(path, to_write):
64 write_file(path, to_write, append=True)
65
66def join_if_not_None(*args):
67 return " ".join(filter(lambda x: x, args))
68
69class ArtifactsManager:
70 """Class which manages folder with test artifacts."""
71
72 def __init__(self, log_dir):
73 self.created_files = []
74 self.log_dir = log_dir
75
76 # Create directory.
Andrew Scull845fc9b2019-04-03 12:44:26 +010077 try:
David Brazdil2df24082019-09-05 11:55:08 +010078 os.makedirs(self.log_dir)
79 except OSError:
80 if not os.path.isdir(self.log_dir):
81 raise
82 print("Logs saved under", log_dir)
83
84 # Create files expected by the Sponge test result parser.
85 self.sponge_log_path = self.create_file("sponge_log", ".log")
86 self.sponge_xml_path = self.create_file("sponge_log", ".xml")
87
David Brazdil623b6812019-09-09 11:41:08 +010088 def gen_file_path(self, basename, extension):
89 """Generate path to a file in the log directory."""
90 return os.path.join(self.log_dir, basename + extension)
91
David Brazdil2df24082019-09-05 11:55:08 +010092 def create_file(self, basename, extension):
93 """Create and touch a new file in the log folder. Ensure that no other
94 file of the same name was created by this instance of ArtifactsManager.
95 """
96 # Determine the path of the file.
David Brazdil623b6812019-09-09 11:41:08 +010097 path = self.gen_file_path(basename, extension)
David Brazdil2df24082019-09-05 11:55:08 +010098
99 # Check that the path is unique.
100 assert(path not in self.created_files)
101 self.created_files += [ path ]
102
103 # Touch file.
104 with open(path, "w") as f:
105 pass
106
107 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +0100108
David Brazdil623b6812019-09-09 11:41:08 +0100109 def get_file(self, basename, extension):
110 """Return path to a file in the log folder. Assert that it was created
111 by this instance of ArtifactsManager."""
112 path = self.gen_file_path(basename, extension)
113 assert(path in self.created_files)
114 return path
115
Andrew Scullbc7189d2018-08-14 09:35:13 +0100116
David Brazdil2df24082019-09-05 11:55:08 +0100117# Tuple holding the arguments common to all driver constructors.
118# This is to avoid having to pass arguments from subclasses to superclasses.
119DriverArgs = collections.namedtuple("DriverArgs", [
120 "artifacts",
121 "kernel",
122 "initrd",
123 "vm_args",
David Brazdil17e76652020-01-29 14:44:19 +0000124 "cpu",
David Brazdil2df24082019-09-05 11:55:08 +0100125 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100126
Andrew Walbran98656252019-03-14 14:52:29 +0000127
David Brazdil2df24082019-09-05 11:55:08 +0100128# State shared between the common Driver class and its subclasses during
129# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100130class DriverRunState:
131 def __init__(self, log_path):
132 self.log_path = log_path
133 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000134
David Brazdil7325eaf2019-09-27 13:04:51 +0100135 def set_ret_code(self, ret_code):
136 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000137
David Brazdil0dbb41f2019-09-09 18:03:35 +0100138class DriverRunException(Exception):
139 """Exception thrown if subprocess invoked by a driver returned non-zero
140 status code. Used to fast-exit from a driver command sequence."""
141 pass
142
143
David Brazdil2df24082019-09-05 11:55:08 +0100144class Driver:
145 """Parent class of drivers for all testable platforms."""
146
147 def __init__(self, args):
148 self.args = args
149
David Brazdil623b6812019-09-09 11:41:08 +0100150 def get_run_log(self, run_name):
151 """Return path to the main log of a given test run."""
152 return self.args.artifacts.get_file(run_name, ".log")
153
David Brazdil2df24082019-09-05 11:55:08 +0100154 def start_run(self, run_name):
155 """Hook called by Driver subclasses before they invoke the target
156 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100157 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100158
Andrew Walbranf636b842020-01-10 11:46:12 +0000159 def exec_logged(self, run_state, exec_args, cwd=None):
David Brazdil2df24082019-09-05 11:55:08 +0100160 """Run a subprocess on behalf of a Driver subclass and append its
161 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100162 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100163 with open(run_state.log_path, "a") as f:
164 f.write("$ {}\r\n".format(" ".join(exec_args)))
165 f.flush()
Andrew Walbranf636b842020-01-10 11:46:12 +0000166 ret_code = subprocess.call(exec_args, stdout=f, stderr=f, cwd=cwd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100167 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100168 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100169 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100170
David Brazdil0dbb41f2019-09-09 18:03:35 +0100171 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100172 """Hook called by Driver subclasses after they finished running the
173 target platform. `ret_code` argument is the return code of the main
174 command run by the driver. A corresponding log message is printed."""
175 # Decode return code and add a message to the log.
176 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100177 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100178 f.write("\r\n{}{} timed out\r\n".format(
179 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100180 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100181 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100182 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
183 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100184
185 # Append log of this run to full test log.
186 log_content = read_file(run_state.log_path)
187 append_file(
188 self.args.artifacts.sponge_log_path,
189 log_content + "\r\n\r\n")
190 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000191
192
David Brazdil2df24082019-09-05 11:55:08 +0100193class QemuDriver(Driver):
194 """Driver which runs tests in QEMU."""
195
Andrew Walbranf636b842020-01-10 11:46:12 +0000196 def __init__(self, args, qemu_wd, tfa):
David Brazdil2df24082019-09-05 11:55:08 +0100197 Driver.__init__(self, args)
Andrew Walbranf636b842020-01-10 11:46:12 +0000198 self.qemu_wd = qemu_wd
199 self.tfa = tfa
David Brazdil2df24082019-09-05 11:55:08 +0100200
David Brazdila2358d42020-01-27 18:51:38 +0000201 def gen_exec_args(self, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100202 """Generate command line arguments for QEMU."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100203 time_limit = "120s" if is_long_running else "10s"
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000204 # If no CPU configuration is selected, then test against the maximum
205 # configuration, "max", supported by QEMU.
206 cpu = self.args.cpu or "max"
David Brazdil2df24082019-09-05 11:55:08 +0100207 exec_args = [
David Brazdil3cc24aa2019-09-27 10:24:41 +0100208 "timeout", "--foreground", time_limit,
Andrew Walbranf636b842020-01-10 11:46:12 +0000209 os.path.abspath("prebuilts/linux-x64/qemu/qemu-system-aarch64"),
Andrew Scull2925e422019-10-04 13:29:53 +0100210 "-machine", "virt,virtualization=on,gic_version=3",
Andrew Walbranf636b842020-01-10 11:46:12 +0000211 "-cpu", cpu, "-smp", "4", "-m", "1G",
David Brazdil2df24082019-09-05 11:55:08 +0100212 "-nographic", "-nodefaults", "-serial", "stdio",
Andrew Walbranf636b842020-01-10 11:46:12 +0000213 "-d", "unimp", "-kernel", os.path.abspath(self.args.kernel),
David Brazdil2df24082019-09-05 11:55:08 +0100214 ]
215
Andrew Walbranf636b842020-01-10 11:46:12 +0000216 if self.tfa:
217 exec_args += ["-bios",
218 os.path.abspath(
219 "prebuilts/linux-aarch64/arm-trusted-firmware/qemu/bl1.bin"
220 ), "-machine", "secure=on", "-semihosting-config",
221 "enable,target=native"]
222
David Brazdil2df24082019-09-05 11:55:08 +0100223 if self.args.initrd:
Andrew Walbranf636b842020-01-10 11:46:12 +0000224 exec_args += ["-initrd", os.path.abspath(self.args.initrd)]
David Brazdil2df24082019-09-05 11:55:08 +0100225
226 vm_args = join_if_not_None(self.args.vm_args, test_args)
227 if vm_args:
228 exec_args += ["-append", vm_args]
229
230 return exec_args
231
David Brazdil3cc24aa2019-09-27 10:24:41 +0100232 def run(self, run_name, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100233 """Run test given by `test_args` in QEMU."""
234 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100235
236 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100237 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000238 exec_args = self.gen_exec_args(test_args, is_long_running)
Andrew Walbranf636b842020-01-10 11:46:12 +0000239 self.exec_logged(run_state, exec_args,
240 cwd=self.qemu_wd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100241 except DriverRunException:
242 pass
243
244 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100245
David Brazdil94fd1e92020-02-03 16:45:20 +0000246 def finish(self):
247 """Clean up after running tests."""
248 pass
249
Andrew Scullbc7189d2018-08-14 09:35:13 +0100250
David Brazdil2df24082019-09-05 11:55:08 +0100251class FvpDriver(Driver):
Andrew Walbran20215742019-11-18 11:35:05 +0000252 """Driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100253
254 def __init__(self, args):
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000255 if args.cpu:
256 raise ValueError("FVP emulator does not support the --cpu option.")
David Brazdil2df24082019-09-05 11:55:08 +0100257 Driver.__init__(self, args)
258
259 def gen_dts(self, dts_path, test_args, initrd_start, initrd_end):
260 """Create a DeviceTree source which will be compiled into a DTB and
261 passed to FVP for a test run."""
262 vm_args = join_if_not_None(self.args.vm_args, test_args)
263 write_file(dts_path, read_file(FVP_PREBUILT_DTS))
264 append_file(dts_path, """
265 / {{
266 chosen {{
267 bootargs = "{}";
268 stdout-path = "serial0:115200n8";
269 linux,initrd-start = <{}>;
270 linux,initrd-end = <{}>;
271 }};
272 }};
273 """.format(vm_args, initrd_start, initrd_end))
274
275 def gen_fvp_args(
Andrew Walbranee5418e2019-11-27 17:43:05 +0000276 self, is_long_running, initrd_start, uart0_log_path, uart1_log_path,
277 dtb_path):
David Brazdil2df24082019-09-05 11:55:08 +0100278 """Generate command line arguments for FVP."""
Andrew Walbranee5418e2019-11-27 17:43:05 +0000279 time_limit = "80s" if is_long_running else "40s"
David Brazdil2df24082019-09-05 11:55:08 +0100280 fvp_args = [
Andrew Walbranee5418e2019-11-27 17:43:05 +0000281 "timeout", "--foreground", time_limit,
David Brazdil2df24082019-09-05 11:55:08 +0100282 FVP_BINARY,
283 "-C", "pctl.startup=0.0.0.0",
284 "-C", "bp.secure_memory=0",
285 "-C", "cluster0.NUM_CORES=4",
286 "-C", "cluster1.NUM_CORES=4",
287 "-C", "cache_state_modelled=0",
288 "-C", "bp.vis.disable_visualisation=true",
289 "-C", "bp.vis.rate_limit-enable=false",
290 "-C", "bp.terminal_0.start_telnet=false",
291 "-C", "bp.terminal_1.start_telnet=false",
292 "-C", "bp.terminal_2.start_telnet=false",
293 "-C", "bp.terminal_3.start_telnet=false",
294 "-C", "bp.pl011_uart0.untimed_fifos=1",
295 "-C", "bp.pl011_uart0.unbuffered_output=1",
296 "-C", "bp.pl011_uart0.out_file=" + uart0_log_path,
297 "-C", "bp.pl011_uart1.out_file=" + uart1_log_path,
298 "-C", "cluster0.cpu0.RVBAR=0x04020000",
299 "-C", "cluster0.cpu1.RVBAR=0x04020000",
300 "-C", "cluster0.cpu2.RVBAR=0x04020000",
301 "-C", "cluster0.cpu3.RVBAR=0x04020000",
302 "-C", "cluster1.cpu0.RVBAR=0x04020000",
303 "-C", "cluster1.cpu1.RVBAR=0x04020000",
304 "-C", "cluster1.cpu2.RVBAR=0x04020000",
305 "-C", "cluster1.cpu3.RVBAR=0x04020000",
David Brazdil21204ae2019-10-30 19:22:38 +0000306 "--data", "cluster0.cpu0=" + FVP_PREBUILT_BL31 + "@0x04020000",
David Brazdil2df24082019-09-05 11:55:08 +0100307 "--data", "cluster0.cpu0=" + dtb_path + "@0x82000000",
308 "--data", "cluster0.cpu0=" + self.args.kernel + "@0x80000000",
309 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
310 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
311 ]
312
313 if self.args.initrd:
314 fvp_args += [
315 "--data",
316 "cluster0.cpu0={}@{}".format(
317 self.args.initrd, hex(initrd_start))
318 ]
319
320 return fvp_args
321
David Brazdil3cc24aa2019-09-27 10:24:41 +0100322 def run(self, run_name, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100323 run_state = self.start_run(run_name)
324
David Brazdila2358d42020-01-27 18:51:38 +0000325 dts_path = self.args.artifacts.create_file(run_name, ".dts")
David Brazdil2df24082019-09-05 11:55:08 +0100326 dtb_path = self.args.artifacts.create_file(run_name, ".dtb")
327 uart0_log_path = self.args.artifacts.create_file(run_name, ".uart0.log")
328 uart1_log_path = self.args.artifacts.create_file(run_name, ".uart1.log")
329
330 initrd_start = 0x84000000
331 if self.args.initrd:
332 initrd_end = initrd_start + os.path.getsize(self.args.initrd)
333 else:
334 initrd_end = 0x85000000 # Default value
335
David Brazdil0dbb41f2019-09-09 18:03:35 +0100336 try:
337 # Create a DT to pass to FVP.
David Brazdila2358d42020-01-27 18:51:38 +0000338 self.gen_dts(dts_path, test_args, initrd_start, initrd_end)
David Brazdil2df24082019-09-05 11:55:08 +0100339
David Brazdil0dbb41f2019-09-09 18:03:35 +0100340 # Compile DTS to DTB.
341 dtc_args = [
David Brazdila2358d42020-01-27 18:51:38 +0000342 DTC_SCRIPT, "compile", "-i", dts_path, "-o", dtb_path,
David Brazdil0dbb41f2019-09-09 18:03:35 +0100343 ]
344 self.exec_logged(run_state, dtc_args)
345
David Brazdil0dbb41f2019-09-09 18:03:35 +0100346 # Run FVP.
347 fvp_args = self.gen_fvp_args(
Andrew Walbranee5418e2019-11-27 17:43:05 +0000348 is_long_running, initrd_start, uart0_log_path, uart1_log_path,
349 dtb_path)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100350 self.exec_logged(run_state, fvp_args)
351 except DriverRunException:
352 pass
David Brazdil2df24082019-09-05 11:55:08 +0100353
354 # Append UART0 output to main log.
355 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100356 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100357
David Brazdil94fd1e92020-02-03 16:45:20 +0000358 def finish(self):
359 """Clean up after running tests."""
360 pass
361
David Brazdil2df24082019-09-05 11:55:08 +0100362
David Brazdil17e76652020-01-29 14:44:19 +0000363class SerialDriver(Driver):
364 """Driver which communicates with a device over the serial port."""
365
David Brazdil9d4ed962020-02-06 17:23:48 +0000366 def __init__(self, args, tty_file, baudrate, init_wait):
David Brazdil17e76652020-01-29 14:44:19 +0000367 Driver.__init__(self, args)
David Brazdil9d4ed962020-02-06 17:23:48 +0000368 self.tty_file = tty_file
369 self.baudrate = baudrate
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000370 self.pyserial = importlib.import_module("serial")
David Brazdild8013f92020-02-03 16:40:25 +0000371
David Brazdil9d4ed962020-02-06 17:23:48 +0000372 if init_wait:
David Brazdild8013f92020-02-03 16:40:25 +0000373 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000374
David Brazdil9d4ed962020-02-06 17:23:48 +0000375 def connect(self):
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000376 return self.pyserial.Serial(self.tty_file, self.baudrate, timeout=10)
David Brazdil9d4ed962020-02-06 17:23:48 +0000377
David Brazdil17e76652020-01-29 14:44:19 +0000378 def run(self, run_name, test_args, is_long_running):
379 """Communicate `test_args` to the device over the serial port."""
380 run_state = self.start_run(run_name)
381
David Brazdil9d4ed962020-02-06 17:23:48 +0000382 with self.connect() as ser:
David Brazdil17e76652020-01-29 14:44:19 +0000383 with open(run_state.log_path, "a") as f:
384 while True:
385 # Read one line from the serial port.
386 line = ser.readline().decode('utf-8')
387 if len(line) == 0:
388 # Timeout
389 run_state.set_ret_code(124)
390 input("Timeout. " +
391 "Press ENTER and then reset the device...")
392 break
393 # Write the line to the log file.
394 f.write(line)
395 if HFTEST_CTRL_GET_COMMAND_LINE in line:
396 # Device is waiting for `test_args`.
397 ser.write(test_args.encode('ascii'))
398 ser.write(b'\r')
399 elif HFTEST_CTRL_FINISHED in line:
400 # Device has finished running this test and will reboot.
401 break
402 return self.finish_run(run_state)
403
David Brazdil94fd1e92020-02-03 16:45:20 +0000404 def finish(self):
405 """Clean up after running tests."""
David Brazdil9d4ed962020-02-06 17:23:48 +0000406 with self.connect() as ser:
David Brazdil94fd1e92020-02-03 16:45:20 +0000407 while True:
408 line = ser.readline().decode('utf-8')
409 if len(line) == 0:
410 input("Timeout. Press ENTER and then reset the device...")
411 elif HFTEST_CTRL_GET_COMMAND_LINE in line:
412 # Device is waiting for a command. Instruct it to exit
413 # the test environment.
414 ser.write("exit".encode('ascii'))
415 ser.write(b'\r')
416 break
417
David Brazdil17e76652020-01-29 14:44:19 +0000418
David Brazdil2df24082019-09-05 11:55:08 +0100419# Tuple used to return information about the results of running a set of tests.
420TestRunnerResult = collections.namedtuple("TestRunnerResult", [
421 "tests_run",
422 "tests_failed",
Andrew Walbranf9463922020-06-05 16:44:42 +0100423 "tests_skipped",
David Brazdil2df24082019-09-05 11:55:08 +0100424 ])
425
426
427class TestRunner:
428 """Class which communicates with a test platform to obtain a list of
429 available tests and driving their execution."""
430
David Brazdil3cc24aa2019-09-27 10:24:41 +0100431 def __init__(self, artifacts, driver, image_name, suite_regex, test_regex,
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100432 skip_long_running_tests, force_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100433 self.artifacts = artifacts
434 self.driver = driver
435 self.image_name = image_name
David Brazdil3cc24aa2019-09-27 10:24:41 +0100436 self.skip_long_running_tests = skip_long_running_tests
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100437 self.force_long_running = force_long_running
David Brazdil2df24082019-09-05 11:55:08 +0100438
439 self.suite_re = re.compile(suite_regex or ".*")
440 self.test_re = re.compile(test_regex or ".*")
441
442 def extract_hftest_lines(self, raw):
443 """Extract hftest-specific lines from a raw output from an invocation
444 of the test platform."""
445 lines = []
446 for line in raw.splitlines():
447 if line.startswith("VM "):
448 line = line[len("VM 0: "):]
449 if line.startswith(HFTEST_LOG_PREFIX):
450 lines.append(line[len(HFTEST_LOG_PREFIX):])
451 return lines
452
453 def get_test_json(self):
454 """Invoke the test platform and request a JSON of available test and
455 test suites."""
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100456 out = self.driver.run("json", "json", self.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100457 hf_out = "\n".join(self.extract_hftest_lines(out))
458 try:
459 return json.loads(hf_out)
460 except ValueError as e:
461 print(out)
462 raise e
463
464 def collect_results(self, fn, it, xml_node):
465 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
466 Insert "tests" and "failures" nodes to `xml_node`."""
467 tests_run = 0
468 tests_failed = 0
Andrew Walbranf9463922020-06-05 16:44:42 +0100469 tests_skipped = 0
Andrew Walbran42bf2842020-06-05 18:50:19 +0100470 start_time = time.perf_counter()
David Brazdil2df24082019-09-05 11:55:08 +0100471 for i in it:
472 sub_result = fn(i)
473 assert(sub_result.tests_run >= sub_result.tests_failed)
474 tests_run += sub_result.tests_run
475 tests_failed += sub_result.tests_failed
Andrew Walbranf9463922020-06-05 16:44:42 +0100476 tests_skipped += sub_result.tests_skipped
Andrew Walbran42bf2842020-06-05 18:50:19 +0100477 elapsed_time = time.perf_counter() - start_time
David Brazdil2df24082019-09-05 11:55:08 +0100478
Andrew Walbranf9463922020-06-05 16:44:42 +0100479 xml_node.set("tests", str(tests_run + tests_skipped))
David Brazdil2df24082019-09-05 11:55:08 +0100480 xml_node.set("failures", str(tests_failed))
Andrew Walbranf9463922020-06-05 16:44:42 +0100481 xml_node.set("skipped", str(tests_skipped))
Andrew Walbran42bf2842020-06-05 18:50:19 +0100482 xml_node.set("time", str(elapsed_time))
Andrew Walbranf9463922020-06-05 16:44:42 +0100483 return TestRunnerResult(tests_run, tests_failed, tests_skipped)
David Brazdil2df24082019-09-05 11:55:08 +0100484
485 def is_passed_test(self, test_out):
486 """Parse the output of a test and return True if it passed."""
487 return \
488 len(test_out) > 0 and \
489 test_out[-1] == HFTEST_LOG_FINISHED and \
490 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
491
Andrew Walbranf9463922020-06-05 16:44:42 +0100492 def get_failure_message(self, test_out):
493 """Parse the output of a test and return the message of the first
494 assertion failure."""
495 for i, line in enumerate(test_out):
496 if line.startswith(HFTEST_LOG_FAILURE_PREFIX) and i + 1 < len(test_out):
497 # The assertion message is on the line after the 'Failure:'
498 return test_out[i + 1].strip()
499
500 return None
501
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000502 def get_log_name(self, suite, test):
503 """Returns a string with a generated log name for the test."""
504 log_name = ""
505
506 cpu = self.driver.args.cpu
507 if cpu:
508 log_name += cpu + "."
509
510 log_name += suite["name"] + "." + test["name"]
511
512 return log_name
513
David Brazdil2df24082019-09-05 11:55:08 +0100514 def run_test(self, suite, test, suite_xml):
515 """Invoke the test platform and request to run a given `test` in given
516 `suite`. Create a new XML node with results under `suite_xml`.
517 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100518 if not self.test_re.match(test["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100519 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100520
521 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100522 test_xml.set("name", test["name"])
523 test_xml.set("classname", suite["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100524
525 if self.skip_long_running_tests and test["is_long_running"]:
526 print(" SKIP", test["name"])
527 test_xml.set("status", "notrun")
528 skipped_xml = ET.SubElement(test_xml, "skipped")
529 skipped_xml.set("message", "Long running")
530 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=1)
531
532 print(" RUN", test["name"])
533 log_name = self.get_log_name(suite, test)
534
David Brazdil2df24082019-09-05 11:55:08 +0100535 test_xml.set("status", "run")
536
Andrew Walbran42bf2842020-06-05 18:50:19 +0100537 start_time = time.perf_counter()
Andrew Walbranf9463922020-06-05 16:44:42 +0100538 out = self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100539 log_name, "run {} {}".format(suite["name"], test["name"]),
Andrew Walbranf9463922020-06-05 16:44:42 +0100540 test["is_long_running"] or self.force_long_running)
541 hftest_out = self.extract_hftest_lines(out)
Andrew Walbran42bf2842020-06-05 18:50:19 +0100542 elapsed_time = time.perf_counter() - start_time
543
544 test_xml.set("time", str(elapsed_time))
David Brazdil2df24082019-09-05 11:55:08 +0100545
Andrew Walbranf9463922020-06-05 16:44:42 +0100546 system_out_xml = ET.SubElement(test_xml, "system-out")
547 system_out_xml.text = out
548
549 if self.is_passed_test(hftest_out):
David Brazdil2df24082019-09-05 11:55:08 +0100550 print(" PASS")
Andrew Walbranf9463922020-06-05 16:44:42 +0100551 return TestRunnerResult(tests_run=1, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100552 else:
David Brazdil623b6812019-09-09 11:41:08 +0100553 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100554 failure_xml = ET.SubElement(test_xml, "failure")
Andrew Walbranf9463922020-06-05 16:44:42 +0100555 failure_message = self.get_failure_message(hftest_out) or "Test failed"
556 failure_xml.set("message", failure_message)
557 failure_xml.text = '\n'.join(hftest_out)
558 return TestRunnerResult(tests_run=1, tests_failed=1, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100559
560 def run_suite(self, suite, xml):
561 """Invoke the test platform and request to run all matching tests in
562 `suite`. Create new XML nodes with results under `xml`.
563 Suite skipped if it does not match the regex given to constructor."""
564 if not self.suite_re.match(suite["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100565 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100566
567 print(" SUITE", suite["name"])
568 suite_xml = ET.SubElement(xml, "testsuite")
569 suite_xml.set("name", suite["name"])
Andrew Walbran16ae62e2020-06-05 18:27:46 +0100570 properties_xml = ET.SubElement(suite_xml, "properties")
571
572 property_xml = ET.SubElement(properties_xml, "property")
573 property_xml.set("name", "driver")
574 property_xml.set("value", type(self.driver).__name__)
575
576 if self.driver.args.cpu:
577 property_xml = ET.SubElement(properties_xml, "property")
578 property_xml.set("name", "cpu")
579 property_xml.set("value", self.driver.args.cpu)
David Brazdil2df24082019-09-05 11:55:08 +0100580
581 return self.collect_results(
582 lambda test: self.run_test(suite, test, suite_xml),
583 suite["tests"],
584 suite_xml)
585
586 def run_tests(self):
587 """Run all suites and tests matching regexes given to constructor.
588 Write results to sponge log XML. Return the number of run and failed
589 tests."""
590
591 test_spec = self.get_test_json()
592 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
593
594 xml = ET.Element("testsuites")
595 xml.set("name", self.image_name)
596 xml.set("timestamp", timestamp)
597
598 result = self.collect_results(
599 lambda suite: self.run_suite(suite, xml),
600 test_spec["suites"],
601 xml)
602
603 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000604 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
605 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100606
607 if result.tests_failed > 0:
608 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
609 "tests failed")
610 elif result.tests_run > 0:
611 print(" PASS: all", result.tests_run, "tests passed")
612
David Brazdil94fd1e92020-02-03 16:45:20 +0000613 # Let the driver clean up.
614 self.driver.finish()
615
David Brazdil2df24082019-09-05 11:55:08 +0100616 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100617
618
619def Main():
620 parser = argparse.ArgumentParser()
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000621 parser.add_argument("image")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100622 parser.add_argument("--out", required=True)
Andrew Scull23e93a82018-10-26 14:56:04 +0100623 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100624 parser.add_argument("--out_initrd")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000625 parser.add_argument("--initrd")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100626 parser.add_argument("--suite")
627 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000628 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000629 parser.add_argument("--driver", default="qemu")
630 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
631 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000632 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100633 parser.add_argument("--skip-long-running-tests", action="store_true")
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100634 parser.add_argument("--force-long-running", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000635 parser.add_argument("--cpu",
636 help="Selects the CPU configuration for the run environment.")
Andrew Walbranf636b842020-01-10 11:46:12 +0000637 parser.add_argument("--tfa", action="store_true")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100638 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100639
Andrew Scullbc7189d2018-08-14 09:35:13 +0100640 # Resolve some paths.
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000641 image = os.path.join(args.out, args.image + ".bin")
642 initrd = None
David Brazdil2df24082019-09-05 11:55:08 +0100643 image_name = args.image
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000644 if args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100645 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
646 initrd = os.path.join(initrd_dir, "initrd.img")
David Brazdil2df24082019-09-05 11:55:08 +0100647 image_name += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +0000648 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +0100649
650 # Create class which will manage all test artifacts.
651 artifacts = ArtifactsManager(os.path.join(args.log, image_name))
652
653 # Create a driver for the platform we want to test on.
David Brazdil9d4ed962020-02-06 17:23:48 +0000654 driver_args = DriverArgs(artifacts, image, initrd, vm_args, args.cpu)
David Brazdil17e76652020-01-29 14:44:19 +0000655
656 if args.driver == "qemu":
Andrew Walbranf636b842020-01-10 11:46:12 +0000657 driver = QemuDriver(driver_args, args.out, args.tfa)
David Brazdil17e76652020-01-29 14:44:19 +0000658 elif args.driver == "fvp":
659 driver = FvpDriver(driver_args)
660 elif args.driver == "serial":
David Brazdil9d4ed962020-02-06 17:23:48 +0000661 driver = SerialDriver(driver_args, args.serial_dev,
662 args.serial_baudrate, not args.serial_no_init_wait)
David Brazdil17e76652020-01-29 14:44:19 +0000663 else:
664 raise Exception("Unknown driver name: {}".format(args.driver))
David Brazdil2df24082019-09-05 11:55:08 +0100665
666 # Create class which will drive test execution.
David Brazdil3cc24aa2019-09-27 10:24:41 +0100667 runner = TestRunner(artifacts, driver, image_name, args.suite, args.test,
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100668 args.skip_long_running_tests, args.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100669
670 # Run tests.
671 runner_result = runner.run_tests()
672
673 # Print error message if no tests were run as this is probably unexpected.
674 # Return suitable error code.
675 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100676 print("Error: no tests match")
677 return 10
David Brazdil2df24082019-09-05 11:55:08 +0100678 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100679 return 1
680 else:
David Brazdil2df24082019-09-05 11:55:08 +0100681 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +0100682
683if __name__ == "__main__":
684 sys.exit(Main())