blob: a10f93234c95665623f836a828e4b96c41da7070 [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
Andrew Scullbc7189d2018-08-14 09:35:13 +010028import json
29import os
30import re
David Brazdil17e76652020-01-29 14:44:19 +000031import serial
Andrew Scullbc7189d2018-08-14 09:35:13 +010032import 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",
124 "serial_dev",
125 "serial_baudrate",
David Brazdild8013f92020-02-03 16:40:25 +0000126 "serial_init_wait",
David Brazdil2df24082019-09-05 11:55:08 +0100127 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100128
Andrew Walbran98656252019-03-14 14:52:29 +0000129
David Brazdil2df24082019-09-05 11:55:08 +0100130# State shared between the common Driver class and its subclasses during
131# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100132class DriverRunState:
133 def __init__(self, log_path):
134 self.log_path = log_path
135 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000136
David Brazdil7325eaf2019-09-27 13:04:51 +0100137 def set_ret_code(self, ret_code):
138 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000139
David Brazdil0dbb41f2019-09-09 18:03:35 +0100140class DriverRunException(Exception):
141 """Exception thrown if subprocess invoked by a driver returned non-zero
142 status code. Used to fast-exit from a driver command sequence."""
143 pass
144
145
David Brazdil2df24082019-09-05 11:55:08 +0100146class Driver:
147 """Parent class of drivers for all testable platforms."""
148
149 def __init__(self, args):
150 self.args = args
151
David Brazdil623b6812019-09-09 11:41:08 +0100152 def get_run_log(self, run_name):
153 """Return path to the main log of a given test run."""
154 return self.args.artifacts.get_file(run_name, ".log")
155
David Brazdil2df24082019-09-05 11:55:08 +0100156 def start_run(self, run_name):
157 """Hook called by Driver subclasses before they invoke the target
158 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100159 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100160
161 def exec_logged(self, run_state, exec_args):
162 """Run a subprocess on behalf of a Driver subclass and append its
163 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100164 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100165 with open(run_state.log_path, "a") as f:
166 f.write("$ {}\r\n".format(" ".join(exec_args)))
167 f.flush()
David Brazdil0dbb41f2019-09-09 18:03:35 +0100168 ret_code = subprocess.call(exec_args, stdout=f, stderr=f)
169 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100170 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100171 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100172
David Brazdil0dbb41f2019-09-09 18:03:35 +0100173 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100174 """Hook called by Driver subclasses after they finished running the
175 target platform. `ret_code` argument is the return code of the main
176 command run by the driver. A corresponding log message is printed."""
177 # Decode return code and add a message to the log.
178 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100179 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100180 f.write("\r\n{}{} timed out\r\n".format(
181 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100182 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100183 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100184 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
185 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100186
187 # Append log of this run to full test log.
188 log_content = read_file(run_state.log_path)
189 append_file(
190 self.args.artifacts.sponge_log_path,
191 log_content + "\r\n\r\n")
192 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000193
194
David Brazdil2df24082019-09-05 11:55:08 +0100195class QemuDriver(Driver):
196 """Driver which runs tests in QEMU."""
197
198 def __init__(self, args):
199 Driver.__init__(self, args)
200
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,
David Brazdil2df24082019-09-05 11:55:08 +0100209 "./prebuilts/linux-x64/qemu/qemu-system-aarch64",
Andrew Scull2925e422019-10-04 13:29:53 +0100210 "-machine", "virt,virtualization=on,gic_version=3",
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000211 "-cpu", cpu, "-smp", "4", "-m", "64M",
David Brazdil2df24082019-09-05 11:55:08 +0100212 "-nographic", "-nodefaults", "-serial", "stdio",
Andrew Scull2925e422019-10-04 13:29:53 +0100213 "-d", "unimp", "-kernel", self.args.kernel,
David Brazdil2df24082019-09-05 11:55:08 +0100214 ]
215
216 if self.args.initrd:
217 exec_args += ["-initrd", self.args.initrd]
218
219 vm_args = join_if_not_None(self.args.vm_args, test_args)
220 if vm_args:
221 exec_args += ["-append", vm_args]
222
223 return exec_args
224
David Brazdil3cc24aa2019-09-27 10:24:41 +0100225 def run(self, run_name, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100226 """Run test given by `test_args` in QEMU."""
227 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100228
229 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100230 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000231 exec_args = self.gen_exec_args(test_args, is_long_running)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100232 self.exec_logged(run_state, exec_args)
233 except DriverRunException:
234 pass
235
236 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100237
238
David Brazdil2df24082019-09-05 11:55:08 +0100239class FvpDriver(Driver):
Andrew Walbran20215742019-11-18 11:35:05 +0000240 """Driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100241
242 def __init__(self, args):
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000243 if args.cpu:
244 raise ValueError("FVP emulator does not support the --cpu option.")
David Brazdil2df24082019-09-05 11:55:08 +0100245 Driver.__init__(self, args)
246
247 def gen_dts(self, dts_path, test_args, initrd_start, initrd_end):
248 """Create a DeviceTree source which will be compiled into a DTB and
249 passed to FVP for a test run."""
250 vm_args = join_if_not_None(self.args.vm_args, test_args)
251 write_file(dts_path, read_file(FVP_PREBUILT_DTS))
252 append_file(dts_path, """
253 / {{
254 chosen {{
255 bootargs = "{}";
256 stdout-path = "serial0:115200n8";
257 linux,initrd-start = <{}>;
258 linux,initrd-end = <{}>;
259 }};
260 }};
261 """.format(vm_args, initrd_start, initrd_end))
262
263 def gen_fvp_args(
Andrew Walbranee5418e2019-11-27 17:43:05 +0000264 self, is_long_running, initrd_start, uart0_log_path, uart1_log_path,
265 dtb_path):
David Brazdil2df24082019-09-05 11:55:08 +0100266 """Generate command line arguments for FVP."""
Andrew Walbranee5418e2019-11-27 17:43:05 +0000267 time_limit = "80s" if is_long_running else "40s"
David Brazdil2df24082019-09-05 11:55:08 +0100268 fvp_args = [
Andrew Walbranee5418e2019-11-27 17:43:05 +0000269 "timeout", "--foreground", time_limit,
David Brazdil2df24082019-09-05 11:55:08 +0100270 FVP_BINARY,
271 "-C", "pctl.startup=0.0.0.0",
272 "-C", "bp.secure_memory=0",
273 "-C", "cluster0.NUM_CORES=4",
274 "-C", "cluster1.NUM_CORES=4",
275 "-C", "cache_state_modelled=0",
276 "-C", "bp.vis.disable_visualisation=true",
277 "-C", "bp.vis.rate_limit-enable=false",
278 "-C", "bp.terminal_0.start_telnet=false",
279 "-C", "bp.terminal_1.start_telnet=false",
280 "-C", "bp.terminal_2.start_telnet=false",
281 "-C", "bp.terminal_3.start_telnet=false",
282 "-C", "bp.pl011_uart0.untimed_fifos=1",
283 "-C", "bp.pl011_uart0.unbuffered_output=1",
284 "-C", "bp.pl011_uart0.out_file=" + uart0_log_path,
285 "-C", "bp.pl011_uart1.out_file=" + uart1_log_path,
286 "-C", "cluster0.cpu0.RVBAR=0x04020000",
287 "-C", "cluster0.cpu1.RVBAR=0x04020000",
288 "-C", "cluster0.cpu2.RVBAR=0x04020000",
289 "-C", "cluster0.cpu3.RVBAR=0x04020000",
290 "-C", "cluster1.cpu0.RVBAR=0x04020000",
291 "-C", "cluster1.cpu1.RVBAR=0x04020000",
292 "-C", "cluster1.cpu2.RVBAR=0x04020000",
293 "-C", "cluster1.cpu3.RVBAR=0x04020000",
David Brazdil21204ae2019-10-30 19:22:38 +0000294 "--data", "cluster0.cpu0=" + FVP_PREBUILT_BL31 + "@0x04020000",
David Brazdil2df24082019-09-05 11:55:08 +0100295 "--data", "cluster0.cpu0=" + dtb_path + "@0x82000000",
296 "--data", "cluster0.cpu0=" + self.args.kernel + "@0x80000000",
297 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
298 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
299 ]
300
301 if self.args.initrd:
302 fvp_args += [
303 "--data",
304 "cluster0.cpu0={}@{}".format(
305 self.args.initrd, hex(initrd_start))
306 ]
307
308 return fvp_args
309
David Brazdil3cc24aa2019-09-27 10:24:41 +0100310 def run(self, run_name, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100311 run_state = self.start_run(run_name)
312
David Brazdila2358d42020-01-27 18:51:38 +0000313 dts_path = self.args.artifacts.create_file(run_name, ".dts")
David Brazdil2df24082019-09-05 11:55:08 +0100314 dtb_path = self.args.artifacts.create_file(run_name, ".dtb")
315 uart0_log_path = self.args.artifacts.create_file(run_name, ".uart0.log")
316 uart1_log_path = self.args.artifacts.create_file(run_name, ".uart1.log")
317
318 initrd_start = 0x84000000
319 if self.args.initrd:
320 initrd_end = initrd_start + os.path.getsize(self.args.initrd)
321 else:
322 initrd_end = 0x85000000 # Default value
323
David Brazdil0dbb41f2019-09-09 18:03:35 +0100324 try:
325 # Create a DT to pass to FVP.
David Brazdila2358d42020-01-27 18:51:38 +0000326 self.gen_dts(dts_path, test_args, initrd_start, initrd_end)
David Brazdil2df24082019-09-05 11:55:08 +0100327
David Brazdil0dbb41f2019-09-09 18:03:35 +0100328 # Compile DTS to DTB.
329 dtc_args = [
David Brazdila2358d42020-01-27 18:51:38 +0000330 DTC_SCRIPT, "compile", "-i", dts_path, "-o", dtb_path,
David Brazdil0dbb41f2019-09-09 18:03:35 +0100331 ]
332 self.exec_logged(run_state, dtc_args)
333
David Brazdil0dbb41f2019-09-09 18:03:35 +0100334 # Run FVP.
335 fvp_args = self.gen_fvp_args(
Andrew Walbranee5418e2019-11-27 17:43:05 +0000336 is_long_running, initrd_start, uart0_log_path, uart1_log_path,
337 dtb_path)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100338 self.exec_logged(run_state, fvp_args)
339 except DriverRunException:
340 pass
David Brazdil2df24082019-09-05 11:55:08 +0100341
342 # Append UART0 output to main log.
343 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100344 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100345
346
David Brazdil17e76652020-01-29 14:44:19 +0000347class SerialDriver(Driver):
348 """Driver which communicates with a device over the serial port."""
349
350 def __init__(self, args):
351 Driver.__init__(self, args)
352 self.tty_file = self.args.serial_dev
353 self.baudrate = self.args.serial_baudrate
David Brazdild8013f92020-02-03 16:40:25 +0000354
355 if self.args.serial_init_wait:
356 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000357
358 def run(self, run_name, test_args, is_long_running):
359 """Communicate `test_args` to the device over the serial port."""
360 run_state = self.start_run(run_name)
361
362 with serial.Serial(self.tty_file, self.baudrate, timeout=10) as ser:
363 with open(run_state.log_path, "a") as f:
364 while True:
365 # Read one line from the serial port.
366 line = ser.readline().decode('utf-8')
367 if len(line) == 0:
368 # Timeout
369 run_state.set_ret_code(124)
370 input("Timeout. " +
371 "Press ENTER and then reset the device...")
372 break
373 # Write the line to the log file.
374 f.write(line)
375 if HFTEST_CTRL_GET_COMMAND_LINE in line:
376 # Device is waiting for `test_args`.
377 ser.write(test_args.encode('ascii'))
378 ser.write(b'\r')
379 elif HFTEST_CTRL_FINISHED in line:
380 # Device has finished running this test and will reboot.
381 break
382 return self.finish_run(run_state)
383
384
David Brazdil2df24082019-09-05 11:55:08 +0100385# Tuple used to return information about the results of running a set of tests.
386TestRunnerResult = collections.namedtuple("TestRunnerResult", [
387 "tests_run",
388 "tests_failed",
389 ])
390
391
392class TestRunner:
393 """Class which communicates with a test platform to obtain a list of
394 available tests and driving their execution."""
395
David Brazdil3cc24aa2019-09-27 10:24:41 +0100396 def __init__(self, artifacts, driver, image_name, suite_regex, test_regex,
397 skip_long_running_tests):
David Brazdil2df24082019-09-05 11:55:08 +0100398 self.artifacts = artifacts
399 self.driver = driver
400 self.image_name = image_name
David Brazdil3cc24aa2019-09-27 10:24:41 +0100401 self.skip_long_running_tests = skip_long_running_tests
David Brazdil2df24082019-09-05 11:55:08 +0100402
403 self.suite_re = re.compile(suite_regex or ".*")
404 self.test_re = re.compile(test_regex or ".*")
405
406 def extract_hftest_lines(self, raw):
407 """Extract hftest-specific lines from a raw output from an invocation
408 of the test platform."""
409 lines = []
410 for line in raw.splitlines():
411 if line.startswith("VM "):
412 line = line[len("VM 0: "):]
413 if line.startswith(HFTEST_LOG_PREFIX):
414 lines.append(line[len(HFTEST_LOG_PREFIX):])
415 return lines
416
417 def get_test_json(self):
418 """Invoke the test platform and request a JSON of available test and
419 test suites."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100420 out = self.driver.run("json", "json", False)
David Brazdil2df24082019-09-05 11:55:08 +0100421 hf_out = "\n".join(self.extract_hftest_lines(out))
422 try:
423 return json.loads(hf_out)
424 except ValueError as e:
425 print(out)
426 raise e
427
428 def collect_results(self, fn, it, xml_node):
429 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
430 Insert "tests" and "failures" nodes to `xml_node`."""
431 tests_run = 0
432 tests_failed = 0
433 for i in it:
434 sub_result = fn(i)
435 assert(sub_result.tests_run >= sub_result.tests_failed)
436 tests_run += sub_result.tests_run
437 tests_failed += sub_result.tests_failed
438
439 xml_node.set("tests", str(tests_run))
440 xml_node.set("failures", str(tests_failed))
441 return TestRunnerResult(tests_run, tests_failed)
442
443 def is_passed_test(self, test_out):
444 """Parse the output of a test and return True if it passed."""
445 return \
446 len(test_out) > 0 and \
447 test_out[-1] == HFTEST_LOG_FINISHED and \
448 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
449
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000450 def get_log_name(self, suite, test):
451 """Returns a string with a generated log name for the test."""
452 log_name = ""
453
454 cpu = self.driver.args.cpu
455 if cpu:
456 log_name += cpu + "."
457
458 log_name += suite["name"] + "." + test["name"]
459
460 return log_name
461
David Brazdil2df24082019-09-05 11:55:08 +0100462 def run_test(self, suite, test, suite_xml):
463 """Invoke the test platform and request to run a given `test` in given
464 `suite`. Create a new XML node with results under `suite_xml`.
465 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100466 if not self.test_re.match(test["name"]):
David Brazdil2df24082019-09-05 11:55:08 +0100467 return TestRunnerResult(tests_run=0, tests_failed=0)
468
David Brazdil3cc24aa2019-09-27 10:24:41 +0100469 if self.skip_long_running_tests and test["is_long_running"]:
470 print(" SKIP", test["name"])
471 return TestRunnerResult(tests_run=0, tests_failed=0)
472
473 print(" RUN", test["name"])
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000474 log_name = self.get_log_name(suite, test)
David Brazdil2df24082019-09-05 11:55:08 +0100475
476 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100477 test_xml.set("name", test["name"])
478 test_xml.set("classname", suite["name"])
David Brazdil2df24082019-09-05 11:55:08 +0100479 test_xml.set("status", "run")
480
481 out = self.extract_hftest_lines(self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100482 log_name, "run {} {}".format(suite["name"], test["name"]),
483 test["is_long_running"]))
David Brazdil2df24082019-09-05 11:55:08 +0100484
485 if self.is_passed_test(out):
486 print(" PASS")
487 return TestRunnerResult(tests_run=1, tests_failed=0)
488 else:
David Brazdil623b6812019-09-09 11:41:08 +0100489 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100490 failure_xml = ET.SubElement(test_xml, "failure")
491 # TODO: set a meaningful message and put log in CDATA
492 failure_xml.set("message", "Test failed")
493 return TestRunnerResult(tests_run=1, tests_failed=1)
494
495 def run_suite(self, suite, xml):
496 """Invoke the test platform and request to run all matching tests in
497 `suite`. Create new XML nodes with results under `xml`.
498 Suite skipped if it does not match the regex given to constructor."""
499 if not self.suite_re.match(suite["name"]):
500 return TestRunnerResult(tests_run=0, tests_failed=0)
501
502 print(" SUITE", suite["name"])
503 suite_xml = ET.SubElement(xml, "testsuite")
504 suite_xml.set("name", suite["name"])
505
506 return self.collect_results(
507 lambda test: self.run_test(suite, test, suite_xml),
508 suite["tests"],
509 suite_xml)
510
511 def run_tests(self):
512 """Run all suites and tests matching regexes given to constructor.
513 Write results to sponge log XML. Return the number of run and failed
514 tests."""
515
516 test_spec = self.get_test_json()
517 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
518
519 xml = ET.Element("testsuites")
520 xml.set("name", self.image_name)
521 xml.set("timestamp", timestamp)
522
523 result = self.collect_results(
524 lambda suite: self.run_suite(suite, xml),
525 test_spec["suites"],
526 xml)
527
528 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000529 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
530 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100531
532 if result.tests_failed > 0:
533 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
534 "tests failed")
535 elif result.tests_run > 0:
536 print(" PASS: all", result.tests_run, "tests passed")
537
538 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100539
540
541def Main():
542 parser = argparse.ArgumentParser()
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000543 parser.add_argument("image")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100544 parser.add_argument("--out", required=True)
Andrew Scull23e93a82018-10-26 14:56:04 +0100545 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100546 parser.add_argument("--out_initrd")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000547 parser.add_argument("--initrd")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100548 parser.add_argument("--suite")
549 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000550 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000551 parser.add_argument("--driver", default="qemu")
552 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
553 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000554 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100555 parser.add_argument("--skip-long-running-tests", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000556 parser.add_argument("--cpu",
557 help="Selects the CPU configuration for the run environment.")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100558 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100559
Andrew Scullbc7189d2018-08-14 09:35:13 +0100560 # Resolve some paths.
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000561 image = os.path.join(args.out, args.image + ".bin")
562 initrd = None
David Brazdil2df24082019-09-05 11:55:08 +0100563 image_name = args.image
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000564 if args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100565 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
566 initrd = os.path.join(initrd_dir, "initrd.img")
David Brazdil2df24082019-09-05 11:55:08 +0100567 image_name += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +0000568 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +0100569
570 # Create class which will manage all test artifacts.
571 artifacts = ArtifactsManager(os.path.join(args.log, image_name))
572
573 # Create a driver for the platform we want to test on.
David Brazdil17e76652020-01-29 14:44:19 +0000574 driver_args = DriverArgs(artifacts, image, initrd, vm_args, args.cpu,
David Brazdild8013f92020-02-03 16:40:25 +0000575 args.serial_dev, args.serial_baudrate, not args.serial_no_init_wait)
David Brazdil17e76652020-01-29 14:44:19 +0000576
577 if args.driver == "qemu":
David Brazdil2df24082019-09-05 11:55:08 +0100578 driver = QemuDriver(driver_args)
David Brazdil17e76652020-01-29 14:44:19 +0000579 elif args.driver == "fvp":
580 driver = FvpDriver(driver_args)
581 elif args.driver == "serial":
582 driver = SerialDriver(driver_args)
583 else:
584 raise Exception("Unknown driver name: {}".format(args.driver))
David Brazdil2df24082019-09-05 11:55:08 +0100585
586 # Create class which will drive test execution.
David Brazdil3cc24aa2019-09-27 10:24:41 +0100587 runner = TestRunner(artifacts, driver, image_name, args.suite, args.test,
588 args.skip_long_running_tests)
David Brazdil2df24082019-09-05 11:55:08 +0100589
590 # Run tests.
591 runner_result = runner.run_tests()
592
593 # Print error message if no tests were run as this is probably unexpected.
594 # Return suitable error code.
595 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100596 print("Error: no tests match")
597 return 10
David Brazdil2df24082019-09-05 11:55:08 +0100598 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100599 return 1
600 else:
David Brazdil2df24082019-09-05 11:55:08 +0100601 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +0100602
603if __name__ == "__main__":
604 sys.exit(Main())