blob: 77dd45dcb8b8dced599bcbdf73672afde600c31a [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
34
Andrew Scull845fc9b2019-04-03 12:44:26 +010035HFTEST_LOG_PREFIX = "[hftest] "
36HFTEST_LOG_FAILURE_PREFIX = "Failure:"
37HFTEST_LOG_FINISHED = "FINISHED"
38
David Brazdil17e76652020-01-29 14:44:19 +000039HFTEST_CTRL_GET_COMMAND_LINE = "[hftest_ctrl:get_command_line]"
40HFTEST_CTRL_FINISHED = "[hftest_ctrl:finished]"
41
David Brazdil2df24082019-09-05 11:55:08 +010042HF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
43 os.path.abspath(__file__))))
David Brazdil5715f042019-08-27 11:11:51 +010044DTC_SCRIPT = os.path.join(HF_ROOT, "build", "image", "dtc.py")
David Brazdil2df24082019-09-05 11:55:08 +010045FVP_BINARY = os.path.join(
46 os.path.dirname(HF_ROOT), "fvp", "Base_RevC_AEMv8A_pkg", "models",
47 "Linux64_GCC-4.9", "FVP_Base_RevC-2xAEMv8A")
David Brazdil21204ae2019-10-30 19:22:38 +000048FVP_PREBUILTS_ROOT = os.path.join(
49 HF_ROOT, "prebuilts", "linux-aarch64", "arm-trusted-firmware", "fvp")
David Brazdil2df24082019-09-05 11:55:08 +010050FVP_PREBUILT_DTS = os.path.join(
David Brazdil21204ae2019-10-30 19:22:38 +000051 FVP_PREBUILTS_ROOT, "fvp-base-gicv3-psci-1t.dts")
52FVP_PREBUILT_BL31 = os.path.join(FVP_PREBUILTS_ROOT, "bl31.bin")
Andrew Scull845fc9b2019-04-03 12:44:26 +010053
David Brazdil2df24082019-09-05 11:55:08 +010054def read_file(path):
55 with open(path, "r") as f:
56 return f.read()
Andrew Scull845fc9b2019-04-03 12:44:26 +010057
David Brazdil2df24082019-09-05 11:55:08 +010058def write_file(path, to_write, append=False):
59 with open(path, "a" if append else "w") as f:
60 f.write(to_write)
61
62def append_file(path, to_write):
63 write_file(path, to_write, append=True)
64
65def join_if_not_None(*args):
66 return " ".join(filter(lambda x: x, args))
67
68class ArtifactsManager:
69 """Class which manages folder with test artifacts."""
70
71 def __init__(self, log_dir):
72 self.created_files = []
73 self.log_dir = log_dir
74
75 # Create directory.
Andrew Scull845fc9b2019-04-03 12:44:26 +010076 try:
David Brazdil2df24082019-09-05 11:55:08 +010077 os.makedirs(self.log_dir)
78 except OSError:
79 if not os.path.isdir(self.log_dir):
80 raise
81 print("Logs saved under", log_dir)
82
83 # Create files expected by the Sponge test result parser.
84 self.sponge_log_path = self.create_file("sponge_log", ".log")
85 self.sponge_xml_path = self.create_file("sponge_log", ".xml")
86
David Brazdil623b6812019-09-09 11:41:08 +010087 def gen_file_path(self, basename, extension):
88 """Generate path to a file in the log directory."""
89 return os.path.join(self.log_dir, basename + extension)
90
David Brazdil2df24082019-09-05 11:55:08 +010091 def create_file(self, basename, extension):
92 """Create and touch a new file in the log folder. Ensure that no other
93 file of the same name was created by this instance of ArtifactsManager.
94 """
95 # Determine the path of the file.
David Brazdil623b6812019-09-09 11:41:08 +010096 path = self.gen_file_path(basename, extension)
David Brazdil2df24082019-09-05 11:55:08 +010097
98 # Check that the path is unique.
99 assert(path not in self.created_files)
100 self.created_files += [ path ]
101
102 # Touch file.
103 with open(path, "w") as f:
104 pass
105
106 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +0100107
David Brazdil623b6812019-09-09 11:41:08 +0100108 def get_file(self, basename, extension):
109 """Return path to a file in the log folder. Assert that it was created
110 by this instance of ArtifactsManager."""
111 path = self.gen_file_path(basename, extension)
112 assert(path in self.created_files)
113 return path
114
Andrew Scullbc7189d2018-08-14 09:35:13 +0100115
David Brazdil2df24082019-09-05 11:55:08 +0100116# Tuple holding the arguments common to all driver constructors.
117# This is to avoid having to pass arguments from subclasses to superclasses.
118DriverArgs = collections.namedtuple("DriverArgs", [
119 "artifacts",
120 "kernel",
121 "initrd",
122 "vm_args",
David Brazdil17e76652020-01-29 14:44:19 +0000123 "cpu",
David Brazdil2df24082019-09-05 11:55:08 +0100124 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100125
Andrew Walbran98656252019-03-14 14:52:29 +0000126
David Brazdil2df24082019-09-05 11:55:08 +0100127# State shared between the common Driver class and its subclasses during
128# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100129class DriverRunState:
130 def __init__(self, log_path):
131 self.log_path = log_path
132 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000133
David Brazdil7325eaf2019-09-27 13:04:51 +0100134 def set_ret_code(self, ret_code):
135 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000136
David Brazdil0dbb41f2019-09-09 18:03:35 +0100137class DriverRunException(Exception):
138 """Exception thrown if subprocess invoked by a driver returned non-zero
139 status code. Used to fast-exit from a driver command sequence."""
140 pass
141
142
David Brazdil2df24082019-09-05 11:55:08 +0100143class Driver:
144 """Parent class of drivers for all testable platforms."""
145
146 def __init__(self, args):
147 self.args = args
148
David Brazdil623b6812019-09-09 11:41:08 +0100149 def get_run_log(self, run_name):
150 """Return path to the main log of a given test run."""
151 return self.args.artifacts.get_file(run_name, ".log")
152
David Brazdil2df24082019-09-05 11:55:08 +0100153 def start_run(self, run_name):
154 """Hook called by Driver subclasses before they invoke the target
155 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100156 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100157
Andrew Walbranf636b842020-01-10 11:46:12 +0000158 def exec_logged(self, run_state, exec_args, cwd=None):
David Brazdil2df24082019-09-05 11:55:08 +0100159 """Run a subprocess on behalf of a Driver subclass and append its
160 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100161 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100162 with open(run_state.log_path, "a") as f:
163 f.write("$ {}\r\n".format(" ".join(exec_args)))
164 f.flush()
Andrew Walbranf636b842020-01-10 11:46:12 +0000165 ret_code = subprocess.call(exec_args, stdout=f, stderr=f, cwd=cwd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100166 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100167 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100168 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100169
David Brazdil0dbb41f2019-09-09 18:03:35 +0100170 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100171 """Hook called by Driver subclasses after they finished running the
172 target platform. `ret_code` argument is the return code of the main
173 command run by the driver. A corresponding log message is printed."""
174 # Decode return code and add a message to the log.
175 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100176 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100177 f.write("\r\n{}{} timed out\r\n".format(
178 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100179 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100180 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100181 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
182 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100183
184 # Append log of this run to full test log.
185 log_content = read_file(run_state.log_path)
186 append_file(
187 self.args.artifacts.sponge_log_path,
188 log_content + "\r\n\r\n")
189 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000190
191
David Brazdil2df24082019-09-05 11:55:08 +0100192class QemuDriver(Driver):
193 """Driver which runs tests in QEMU."""
194
Andrew Walbranf636b842020-01-10 11:46:12 +0000195 def __init__(self, args, qemu_wd, tfa):
David Brazdil2df24082019-09-05 11:55:08 +0100196 Driver.__init__(self, args)
Andrew Walbranf636b842020-01-10 11:46:12 +0000197 self.qemu_wd = qemu_wd
198 self.tfa = tfa
David Brazdil2df24082019-09-05 11:55:08 +0100199
David Brazdila2358d42020-01-27 18:51:38 +0000200 def gen_exec_args(self, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100201 """Generate command line arguments for QEMU."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100202 time_limit = "120s" if is_long_running else "10s"
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000203 # If no CPU configuration is selected, then test against the maximum
204 # configuration, "max", supported by QEMU.
205 cpu = self.args.cpu or "max"
David Brazdil2df24082019-09-05 11:55:08 +0100206 exec_args = [
David Brazdil3cc24aa2019-09-27 10:24:41 +0100207 "timeout", "--foreground", time_limit,
Andrew Walbranf636b842020-01-10 11:46:12 +0000208 os.path.abspath("prebuilts/linux-x64/qemu/qemu-system-aarch64"),
Andrew Scull2925e422019-10-04 13:29:53 +0100209 "-machine", "virt,virtualization=on,gic_version=3",
Andrew Walbranf636b842020-01-10 11:46:12 +0000210 "-cpu", cpu, "-smp", "4", "-m", "1G",
David Brazdil2df24082019-09-05 11:55:08 +0100211 "-nographic", "-nodefaults", "-serial", "stdio",
Andrew Walbranf636b842020-01-10 11:46:12 +0000212 "-d", "unimp", "-kernel", os.path.abspath(self.args.kernel),
David Brazdil2df24082019-09-05 11:55:08 +0100213 ]
214
Andrew Walbranf636b842020-01-10 11:46:12 +0000215 if self.tfa:
216 exec_args += ["-bios",
217 os.path.abspath(
218 "prebuilts/linux-aarch64/arm-trusted-firmware/qemu/bl1.bin"
219 ), "-machine", "secure=on", "-semihosting-config",
220 "enable,target=native"]
221
David Brazdil2df24082019-09-05 11:55:08 +0100222 if self.args.initrd:
Andrew Walbranf636b842020-01-10 11:46:12 +0000223 exec_args += ["-initrd", os.path.abspath(self.args.initrd)]
David Brazdil2df24082019-09-05 11:55:08 +0100224
225 vm_args = join_if_not_None(self.args.vm_args, test_args)
226 if vm_args:
227 exec_args += ["-append", vm_args]
228
229 return exec_args
230
David Brazdil3cc24aa2019-09-27 10:24:41 +0100231 def run(self, run_name, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100232 """Run test given by `test_args` in QEMU."""
233 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100234
235 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100236 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000237 exec_args = self.gen_exec_args(test_args, is_long_running)
Andrew Walbranf636b842020-01-10 11:46:12 +0000238 self.exec_logged(run_state, exec_args,
239 cwd=self.qemu_wd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100240 except DriverRunException:
241 pass
242
243 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100244
David Brazdil94fd1e92020-02-03 16:45:20 +0000245 def finish(self):
246 """Clean up after running tests."""
247 pass
248
Andrew Scullbc7189d2018-08-14 09:35:13 +0100249
David Brazdil2df24082019-09-05 11:55:08 +0100250class FvpDriver(Driver):
Andrew Walbran20215742019-11-18 11:35:05 +0000251 """Driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100252
253 def __init__(self, args):
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000254 if args.cpu:
255 raise ValueError("FVP emulator does not support the --cpu option.")
David Brazdil2df24082019-09-05 11:55:08 +0100256 Driver.__init__(self, args)
257
258 def gen_dts(self, dts_path, test_args, initrd_start, initrd_end):
259 """Create a DeviceTree source which will be compiled into a DTB and
260 passed to FVP for a test run."""
261 vm_args = join_if_not_None(self.args.vm_args, test_args)
262 write_file(dts_path, read_file(FVP_PREBUILT_DTS))
263 append_file(dts_path, """
264 / {{
265 chosen {{
266 bootargs = "{}";
267 stdout-path = "serial0:115200n8";
268 linux,initrd-start = <{}>;
269 linux,initrd-end = <{}>;
270 }};
271 }};
272 """.format(vm_args, initrd_start, initrd_end))
273
274 def gen_fvp_args(
Andrew Walbranee5418e2019-11-27 17:43:05 +0000275 self, is_long_running, initrd_start, uart0_log_path, uart1_log_path,
276 dtb_path):
David Brazdil2df24082019-09-05 11:55:08 +0100277 """Generate command line arguments for FVP."""
Andrew Walbranee5418e2019-11-27 17:43:05 +0000278 time_limit = "80s" if is_long_running else "40s"
David Brazdil2df24082019-09-05 11:55:08 +0100279 fvp_args = [
Andrew Walbranee5418e2019-11-27 17:43:05 +0000280 "timeout", "--foreground", time_limit,
David Brazdil2df24082019-09-05 11:55:08 +0100281 FVP_BINARY,
282 "-C", "pctl.startup=0.0.0.0",
283 "-C", "bp.secure_memory=0",
284 "-C", "cluster0.NUM_CORES=4",
285 "-C", "cluster1.NUM_CORES=4",
286 "-C", "cache_state_modelled=0",
287 "-C", "bp.vis.disable_visualisation=true",
288 "-C", "bp.vis.rate_limit-enable=false",
289 "-C", "bp.terminal_0.start_telnet=false",
290 "-C", "bp.terminal_1.start_telnet=false",
291 "-C", "bp.terminal_2.start_telnet=false",
292 "-C", "bp.terminal_3.start_telnet=false",
293 "-C", "bp.pl011_uart0.untimed_fifos=1",
294 "-C", "bp.pl011_uart0.unbuffered_output=1",
295 "-C", "bp.pl011_uart0.out_file=" + uart0_log_path,
296 "-C", "bp.pl011_uart1.out_file=" + uart1_log_path,
297 "-C", "cluster0.cpu0.RVBAR=0x04020000",
298 "-C", "cluster0.cpu1.RVBAR=0x04020000",
299 "-C", "cluster0.cpu2.RVBAR=0x04020000",
300 "-C", "cluster0.cpu3.RVBAR=0x04020000",
301 "-C", "cluster1.cpu0.RVBAR=0x04020000",
302 "-C", "cluster1.cpu1.RVBAR=0x04020000",
303 "-C", "cluster1.cpu2.RVBAR=0x04020000",
304 "-C", "cluster1.cpu3.RVBAR=0x04020000",
David Brazdil21204ae2019-10-30 19:22:38 +0000305 "--data", "cluster0.cpu0=" + FVP_PREBUILT_BL31 + "@0x04020000",
David Brazdil2df24082019-09-05 11:55:08 +0100306 "--data", "cluster0.cpu0=" + dtb_path + "@0x82000000",
307 "--data", "cluster0.cpu0=" + self.args.kernel + "@0x80000000",
308 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
309 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
310 ]
311
312 if self.args.initrd:
313 fvp_args += [
314 "--data",
315 "cluster0.cpu0={}@{}".format(
316 self.args.initrd, hex(initrd_start))
317 ]
318
319 return fvp_args
320
David Brazdil3cc24aa2019-09-27 10:24:41 +0100321 def run(self, run_name, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100322 run_state = self.start_run(run_name)
323
David Brazdila2358d42020-01-27 18:51:38 +0000324 dts_path = self.args.artifacts.create_file(run_name, ".dts")
David Brazdil2df24082019-09-05 11:55:08 +0100325 dtb_path = self.args.artifacts.create_file(run_name, ".dtb")
326 uart0_log_path = self.args.artifacts.create_file(run_name, ".uart0.log")
327 uart1_log_path = self.args.artifacts.create_file(run_name, ".uart1.log")
328
329 initrd_start = 0x84000000
330 if self.args.initrd:
331 initrd_end = initrd_start + os.path.getsize(self.args.initrd)
332 else:
333 initrd_end = 0x85000000 # Default value
334
David Brazdil0dbb41f2019-09-09 18:03:35 +0100335 try:
336 # Create a DT to pass to FVP.
David Brazdila2358d42020-01-27 18:51:38 +0000337 self.gen_dts(dts_path, test_args, initrd_start, initrd_end)
David Brazdil2df24082019-09-05 11:55:08 +0100338
David Brazdil0dbb41f2019-09-09 18:03:35 +0100339 # Compile DTS to DTB.
340 dtc_args = [
David Brazdila2358d42020-01-27 18:51:38 +0000341 DTC_SCRIPT, "compile", "-i", dts_path, "-o", dtb_path,
David Brazdil0dbb41f2019-09-09 18:03:35 +0100342 ]
343 self.exec_logged(run_state, dtc_args)
344
David Brazdil0dbb41f2019-09-09 18:03:35 +0100345 # Run FVP.
346 fvp_args = self.gen_fvp_args(
Andrew Walbranee5418e2019-11-27 17:43:05 +0000347 is_long_running, initrd_start, uart0_log_path, uart1_log_path,
348 dtb_path)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100349 self.exec_logged(run_state, fvp_args)
350 except DriverRunException:
351 pass
David Brazdil2df24082019-09-05 11:55:08 +0100352
353 # Append UART0 output to main log.
354 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100355 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100356
David Brazdil94fd1e92020-02-03 16:45:20 +0000357 def finish(self):
358 """Clean up after running tests."""
359 pass
360
David Brazdil2df24082019-09-05 11:55:08 +0100361
David Brazdil17e76652020-01-29 14:44:19 +0000362class SerialDriver(Driver):
363 """Driver which communicates with a device over the serial port."""
364
David Brazdil9d4ed962020-02-06 17:23:48 +0000365 def __init__(self, args, tty_file, baudrate, init_wait):
David Brazdil17e76652020-01-29 14:44:19 +0000366 Driver.__init__(self, args)
David Brazdil9d4ed962020-02-06 17:23:48 +0000367 self.tty_file = tty_file
368 self.baudrate = baudrate
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000369 self.pyserial = importlib.import_module("serial")
David Brazdild8013f92020-02-03 16:40:25 +0000370
David Brazdil9d4ed962020-02-06 17:23:48 +0000371 if init_wait:
David Brazdild8013f92020-02-03 16:40:25 +0000372 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000373
David Brazdil9d4ed962020-02-06 17:23:48 +0000374 def connect(self):
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000375 return self.pyserial.Serial(self.tty_file, self.baudrate, timeout=10)
David Brazdil9d4ed962020-02-06 17:23:48 +0000376
David Brazdil17e76652020-01-29 14:44:19 +0000377 def run(self, run_name, test_args, is_long_running):
378 """Communicate `test_args` to the device over the serial port."""
379 run_state = self.start_run(run_name)
380
David Brazdil9d4ed962020-02-06 17:23:48 +0000381 with self.connect() as ser:
David Brazdil17e76652020-01-29 14:44:19 +0000382 with open(run_state.log_path, "a") as f:
383 while True:
384 # Read one line from the serial port.
385 line = ser.readline().decode('utf-8')
386 if len(line) == 0:
387 # Timeout
388 run_state.set_ret_code(124)
389 input("Timeout. " +
390 "Press ENTER and then reset the device...")
391 break
392 # Write the line to the log file.
393 f.write(line)
394 if HFTEST_CTRL_GET_COMMAND_LINE in line:
395 # Device is waiting for `test_args`.
396 ser.write(test_args.encode('ascii'))
397 ser.write(b'\r')
398 elif HFTEST_CTRL_FINISHED in line:
399 # Device has finished running this test and will reboot.
400 break
401 return self.finish_run(run_state)
402
David Brazdil94fd1e92020-02-03 16:45:20 +0000403 def finish(self):
404 """Clean up after running tests."""
David Brazdil9d4ed962020-02-06 17:23:48 +0000405 with self.connect() as ser:
David Brazdil94fd1e92020-02-03 16:45:20 +0000406 while True:
407 line = ser.readline().decode('utf-8')
408 if len(line) == 0:
409 input("Timeout. Press ENTER and then reset the device...")
410 elif HFTEST_CTRL_GET_COMMAND_LINE in line:
411 # Device is waiting for a command. Instruct it to exit
412 # the test environment.
413 ser.write("exit".encode('ascii'))
414 ser.write(b'\r')
415 break
416
David Brazdil17e76652020-01-29 14:44:19 +0000417
David Brazdil2df24082019-09-05 11:55:08 +0100418# Tuple used to return information about the results of running a set of tests.
419TestRunnerResult = collections.namedtuple("TestRunnerResult", [
420 "tests_run",
421 "tests_failed",
Andrew Walbranf9463922020-06-05 16:44:42 +0100422 "tests_skipped",
David Brazdil2df24082019-09-05 11:55:08 +0100423 ])
424
425
426class TestRunner:
427 """Class which communicates with a test platform to obtain a list of
428 available tests and driving their execution."""
429
David Brazdil3cc24aa2019-09-27 10:24:41 +0100430 def __init__(self, artifacts, driver, image_name, suite_regex, test_regex,
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100431 skip_long_running_tests, force_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100432 self.artifacts = artifacts
433 self.driver = driver
434 self.image_name = image_name
David Brazdil3cc24aa2019-09-27 10:24:41 +0100435 self.skip_long_running_tests = skip_long_running_tests
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100436 self.force_long_running = force_long_running
David Brazdil2df24082019-09-05 11:55:08 +0100437
438 self.suite_re = re.compile(suite_regex or ".*")
439 self.test_re = re.compile(test_regex or ".*")
440
441 def extract_hftest_lines(self, raw):
442 """Extract hftest-specific lines from a raw output from an invocation
443 of the test platform."""
444 lines = []
445 for line in raw.splitlines():
446 if line.startswith("VM "):
447 line = line[len("VM 0: "):]
448 if line.startswith(HFTEST_LOG_PREFIX):
449 lines.append(line[len(HFTEST_LOG_PREFIX):])
450 return lines
451
452 def get_test_json(self):
453 """Invoke the test platform and request a JSON of available test and
454 test suites."""
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100455 out = self.driver.run("json", "json", self.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100456 hf_out = "\n".join(self.extract_hftest_lines(out))
457 try:
458 return json.loads(hf_out)
459 except ValueError as e:
460 print(out)
461 raise e
462
463 def collect_results(self, fn, it, xml_node):
464 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
465 Insert "tests" and "failures" nodes to `xml_node`."""
466 tests_run = 0
467 tests_failed = 0
Andrew Walbranf9463922020-06-05 16:44:42 +0100468 tests_skipped = 0
David Brazdil2df24082019-09-05 11:55:08 +0100469 for i in it:
470 sub_result = fn(i)
471 assert(sub_result.tests_run >= sub_result.tests_failed)
472 tests_run += sub_result.tests_run
473 tests_failed += sub_result.tests_failed
Andrew Walbranf9463922020-06-05 16:44:42 +0100474 tests_skipped += sub_result.tests_skipped
David Brazdil2df24082019-09-05 11:55:08 +0100475
Andrew Walbranf9463922020-06-05 16:44:42 +0100476 xml_node.set("tests", str(tests_run + tests_skipped))
David Brazdil2df24082019-09-05 11:55:08 +0100477 xml_node.set("failures", str(tests_failed))
Andrew Walbranf9463922020-06-05 16:44:42 +0100478 xml_node.set("skipped", str(tests_skipped))
479 return TestRunnerResult(tests_run, tests_failed, tests_skipped)
David Brazdil2df24082019-09-05 11:55:08 +0100480
481 def is_passed_test(self, test_out):
482 """Parse the output of a test and return True if it passed."""
483 return \
484 len(test_out) > 0 and \
485 test_out[-1] == HFTEST_LOG_FINISHED and \
486 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
487
Andrew Walbranf9463922020-06-05 16:44:42 +0100488 def get_failure_message(self, test_out):
489 """Parse the output of a test and return the message of the first
490 assertion failure."""
491 for i, line in enumerate(test_out):
492 if line.startswith(HFTEST_LOG_FAILURE_PREFIX) and i + 1 < len(test_out):
493 # The assertion message is on the line after the 'Failure:'
494 return test_out[i + 1].strip()
495
496 return None
497
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000498 def get_log_name(self, suite, test):
499 """Returns a string with a generated log name for the test."""
500 log_name = ""
501
502 cpu = self.driver.args.cpu
503 if cpu:
504 log_name += cpu + "."
505
506 log_name += suite["name"] + "." + test["name"]
507
508 return log_name
509
David Brazdil2df24082019-09-05 11:55:08 +0100510 def run_test(self, suite, test, suite_xml):
511 """Invoke the test platform and request to run a given `test` in given
512 `suite`. Create a new XML node with results under `suite_xml`.
513 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100514 if not self.test_re.match(test["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100515 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100516
517 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100518 test_xml.set("name", test["name"])
519 test_xml.set("classname", suite["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100520
521 if self.skip_long_running_tests and test["is_long_running"]:
522 print(" SKIP", test["name"])
523 test_xml.set("status", "notrun")
524 skipped_xml = ET.SubElement(test_xml, "skipped")
525 skipped_xml.set("message", "Long running")
526 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=1)
527
528 print(" RUN", test["name"])
529 log_name = self.get_log_name(suite, test)
530
David Brazdil2df24082019-09-05 11:55:08 +0100531 test_xml.set("status", "run")
532
Andrew Walbranf9463922020-06-05 16:44:42 +0100533 out = self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100534 log_name, "run {} {}".format(suite["name"], test["name"]),
Andrew Walbranf9463922020-06-05 16:44:42 +0100535 test["is_long_running"] or self.force_long_running)
536 hftest_out = self.extract_hftest_lines(out)
David Brazdil2df24082019-09-05 11:55:08 +0100537
Andrew Walbranf9463922020-06-05 16:44:42 +0100538 system_out_xml = ET.SubElement(test_xml, "system-out")
539 system_out_xml.text = out
540
541 if self.is_passed_test(hftest_out):
David Brazdil2df24082019-09-05 11:55:08 +0100542 print(" PASS")
Andrew Walbranf9463922020-06-05 16:44:42 +0100543 return TestRunnerResult(tests_run=1, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100544 else:
David Brazdil623b6812019-09-09 11:41:08 +0100545 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100546 failure_xml = ET.SubElement(test_xml, "failure")
Andrew Walbranf9463922020-06-05 16:44:42 +0100547 failure_message = self.get_failure_message(hftest_out) or "Test failed"
548 failure_xml.set("message", failure_message)
549 failure_xml.text = '\n'.join(hftest_out)
550 return TestRunnerResult(tests_run=1, tests_failed=1, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100551
552 def run_suite(self, suite, xml):
553 """Invoke the test platform and request to run all matching tests in
554 `suite`. Create new XML nodes with results under `xml`.
555 Suite skipped if it does not match the regex given to constructor."""
556 if not self.suite_re.match(suite["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100557 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100558
559 print(" SUITE", suite["name"])
560 suite_xml = ET.SubElement(xml, "testsuite")
561 suite_xml.set("name", suite["name"])
Andrew Walbran16ae62e2020-06-05 18:27:46 +0100562 properties_xml = ET.SubElement(suite_xml, "properties")
563
564 property_xml = ET.SubElement(properties_xml, "property")
565 property_xml.set("name", "driver")
566 property_xml.set("value", type(self.driver).__name__)
567
568 if self.driver.args.cpu:
569 property_xml = ET.SubElement(properties_xml, "property")
570 property_xml.set("name", "cpu")
571 property_xml.set("value", self.driver.args.cpu)
David Brazdil2df24082019-09-05 11:55:08 +0100572
573 return self.collect_results(
574 lambda test: self.run_test(suite, test, suite_xml),
575 suite["tests"],
576 suite_xml)
577
578 def run_tests(self):
579 """Run all suites and tests matching regexes given to constructor.
580 Write results to sponge log XML. Return the number of run and failed
581 tests."""
582
583 test_spec = self.get_test_json()
584 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
585
586 xml = ET.Element("testsuites")
587 xml.set("name", self.image_name)
588 xml.set("timestamp", timestamp)
589
590 result = self.collect_results(
591 lambda suite: self.run_suite(suite, xml),
592 test_spec["suites"],
593 xml)
594
595 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000596 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
597 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100598
599 if result.tests_failed > 0:
600 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
601 "tests failed")
602 elif result.tests_run > 0:
603 print(" PASS: all", result.tests_run, "tests passed")
604
David Brazdil94fd1e92020-02-03 16:45:20 +0000605 # Let the driver clean up.
606 self.driver.finish()
607
David Brazdil2df24082019-09-05 11:55:08 +0100608 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100609
610
611def Main():
612 parser = argparse.ArgumentParser()
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000613 parser.add_argument("image")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100614 parser.add_argument("--out", required=True)
Andrew Scull23e93a82018-10-26 14:56:04 +0100615 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100616 parser.add_argument("--out_initrd")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000617 parser.add_argument("--initrd")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100618 parser.add_argument("--suite")
619 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000620 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000621 parser.add_argument("--driver", default="qemu")
622 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
623 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000624 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100625 parser.add_argument("--skip-long-running-tests", action="store_true")
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100626 parser.add_argument("--force-long-running", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000627 parser.add_argument("--cpu",
628 help="Selects the CPU configuration for the run environment.")
Andrew Walbranf636b842020-01-10 11:46:12 +0000629 parser.add_argument("--tfa", action="store_true")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100630 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100631
Andrew Scullbc7189d2018-08-14 09:35:13 +0100632 # Resolve some paths.
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000633 image = os.path.join(args.out, args.image + ".bin")
634 initrd = None
David Brazdil2df24082019-09-05 11:55:08 +0100635 image_name = args.image
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000636 if args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100637 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
638 initrd = os.path.join(initrd_dir, "initrd.img")
David Brazdil2df24082019-09-05 11:55:08 +0100639 image_name += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +0000640 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +0100641
642 # Create class which will manage all test artifacts.
643 artifacts = ArtifactsManager(os.path.join(args.log, image_name))
644
645 # Create a driver for the platform we want to test on.
David Brazdil9d4ed962020-02-06 17:23:48 +0000646 driver_args = DriverArgs(artifacts, image, initrd, vm_args, args.cpu)
David Brazdil17e76652020-01-29 14:44:19 +0000647
648 if args.driver == "qemu":
Andrew Walbranf636b842020-01-10 11:46:12 +0000649 driver = QemuDriver(driver_args, args.out, args.tfa)
David Brazdil17e76652020-01-29 14:44:19 +0000650 elif args.driver == "fvp":
651 driver = FvpDriver(driver_args)
652 elif args.driver == "serial":
David Brazdil9d4ed962020-02-06 17:23:48 +0000653 driver = SerialDriver(driver_args, args.serial_dev,
654 args.serial_baudrate, not args.serial_no_init_wait)
David Brazdil17e76652020-01-29 14:44:19 +0000655 else:
656 raise Exception("Unknown driver name: {}".format(args.driver))
David Brazdil2df24082019-09-05 11:55:08 +0100657
658 # Create class which will drive test execution.
David Brazdil3cc24aa2019-09-27 10:24:41 +0100659 runner = TestRunner(artifacts, driver, image_name, args.suite, args.test,
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100660 args.skip_long_running_tests, args.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100661
662 # Run tests.
663 runner_result = runner.run_tests()
664
665 # Print error message if no tests were run as this is probably unexpected.
666 # Return suitable error code.
667 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100668 print("Error: no tests match")
669 return 10
David Brazdil2df24082019-09-05 11:55:08 +0100670 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100671 return 1
672 else:
David Brazdil2df24082019-09-05 11:55:08 +0100673 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +0100674
675if __name__ == "__main__":
676 sys.exit(Main())