device-crash-test 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2017 Red Hat Inc
  4. #
  5. # Author:
  6. # Eduardo Habkost <ehabkost@redhat.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. """
  22. Run QEMU with all combinations of -machine and -device types,
  23. check for crashes and unexpected errors.
  24. """
  25. from __future__ import print_function
  26. import os
  27. import sys
  28. import glob
  29. import logging
  30. import traceback
  31. import re
  32. import random
  33. import argparse
  34. from itertools import chain
  35. sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'python'))
  36. from qemu.machine import QEMUMachine
  37. logger = logging.getLogger('device-crash-test')
  38. dbg = logger.debug
  39. # Purposes of the following whitelist:
  40. # * Avoiding verbose log messages when we find known non-fatal
  41. # (exitcode=1) errors
  42. # * Avoiding fatal errors when we find known crashes
  43. # * Skipping machines/devices that are known not to work out of
  44. # the box, when running in --quick mode
  45. #
  46. # Keeping the whitelist updated is desirable, but not required,
  47. # because unexpected cases where QEMU exits with exitcode=1 will
  48. # just trigger a INFO message.
  49. # Valid whitelist entry keys:
  50. # * accel: regexp, full match only
  51. # * machine: regexp, full match only
  52. # * device: regexp, full match only
  53. # * log: regexp, partial match allowed
  54. # * exitcode: if not present, defaults to 1. If None, matches any exitcode
  55. # * warn: if True, matching failures will be logged as warnings
  56. # * expected: if True, QEMU is expected to always fail every time
  57. # when testing the corresponding test case
  58. # * loglevel: log level of log output when there's a match.
  59. ERROR_WHITELIST = [
  60. # Machines that won't work out of the box:
  61. # MACHINE | ERROR MESSAGE
  62. {'machine':'niagara', 'expected':True}, # Unable to load a firmware for -M niagara
  63. {'machine':'boston', 'expected':True}, # Please provide either a -kernel or -bios argument
  64. {'machine':'leon3_generic', 'expected':True}, # Can't read bios image (null)
  65. # devices that don't work out of the box because they require extra options to "-device DEV":
  66. # DEVICE | ERROR MESSAGE
  67. {'device':'.*-(i386|x86_64)-cpu', 'expected':True}, # CPU socket-id is not set
  68. {'device':'icp', 'expected':True}, # icp_realize: required link 'xics' not found: Property '.xics' not found
  69. {'device':'ics', 'expected':True}, # ics_base_realize: required link 'xics' not found: Property '.xics' not found
  70. # "-device ide-cd" does work on more recent QEMU versions, so it doesn't have expected=True
  71. {'device':'ide-cd'}, # No drive specified
  72. {'device':'ide-drive', 'expected':True}, # No drive specified
  73. {'device':'ide-hd', 'expected':True}, # No drive specified
  74. {'device':'ipmi-bmc-extern', 'expected':True}, # IPMI external bmc requires chardev attribute
  75. {'device':'isa-debugcon', 'expected':True}, # Can't create serial device, empty char device
  76. {'device':'isa-ipmi-bt', 'expected':True}, # IPMI device requires a bmc attribute to be set
  77. {'device':'isa-ipmi-kcs', 'expected':True}, # IPMI device requires a bmc attribute to be set
  78. {'device':'isa-parallel', 'expected':True}, # Can't create serial device, empty char device
  79. {'device':'ivshmem-doorbell', 'expected':True}, # You must specify a 'chardev'
  80. {'device':'ivshmem-plain', 'expected':True}, # You must specify a 'memdev'
  81. {'device':'loader', 'expected':True}, # please include valid arguments
  82. {'device':'nand', 'expected':True}, # Unsupported NAND block size 0x1
  83. {'device':'nvdimm', 'expected':True}, # 'memdev' property is not set
  84. {'device':'nvme', 'expected':True}, # Device initialization failed
  85. {'device':'pc-dimm', 'expected':True}, # 'memdev' property is not set
  86. {'device':'pci-bridge', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  87. {'device':'pci-bridge-seat', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  88. {'device':'pxb', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  89. {'device':'scsi-block', 'expected':True}, # drive property not set
  90. {'device':'scsi-disk', 'expected':True}, # drive property not set
  91. {'device':'scsi-generic', 'expected':True}, # drive property not set
  92. {'device':'scsi-hd', 'expected':True}, # drive property not set
  93. {'device':'spapr-pci-host-bridge', 'expected':True}, # BUID not specified for PHB
  94. {'device':'spapr-rng', 'expected':True}, # spapr-rng needs an RNG backend!
  95. {'device':'spapr-vty', 'expected':True}, # chardev property not set
  96. {'device':'tpm-tis', 'expected':True}, # tpm_tis: backend driver with id (null) could not be found
  97. {'device':'unimplemented-device', 'expected':True}, # property 'size' not specified or zero
  98. {'device':'usb-braille', 'expected':True}, # Property chardev is required
  99. {'device':'usb-mtp', 'expected':True}, # rootdir property must be configured
  100. {'device':'usb-redir', 'expected':True}, # Parameter 'chardev' is missing
  101. {'device':'usb-serial', 'expected':True}, # Property chardev is required
  102. {'device':'usb-storage', 'expected':True}, # drive property not set
  103. {'device':'vfio-amd-xgbe', 'expected':True}, # -device vfio-amd-xgbe: vfio error: wrong host device name
  104. {'device':'vfio-calxeda-xgmac', 'expected':True}, # -device vfio-calxeda-xgmac: vfio error: wrong host device name
  105. {'device':'vfio-pci', 'expected':True}, # No provided host device
  106. {'device':'vfio-pci-igd-lpc-bridge', 'expected':True}, # VFIO dummy ISA/LPC bridge must have address 1f.0
  107. {'device':'vhost-scsi.*', 'expected':True}, # vhost-scsi: missing wwpn
  108. {'device':'vhost-vsock-device', 'expected':True}, # guest-cid property must be greater than 2
  109. {'device':'vhost-vsock-pci', 'expected':True}, # guest-cid property must be greater than 2
  110. {'device':'virtio-9p-ccw', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  111. {'device':'virtio-9p-device', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  112. {'device':'virtio-9p-pci', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  113. {'device':'virtio-blk-ccw', 'expected':True}, # drive property not set
  114. {'device':'virtio-blk-device', 'expected':True}, # drive property not set
  115. {'device':'virtio-blk-device', 'expected':True}, # drive property not set
  116. {'device':'virtio-blk-pci', 'expected':True}, # drive property not set
  117. {'device':'virtio-crypto-ccw', 'expected':True}, # 'cryptodev' parameter expects a valid object
  118. {'device':'virtio-crypto-device', 'expected':True}, # 'cryptodev' parameter expects a valid object
  119. {'device':'virtio-crypto-pci', 'expected':True}, # 'cryptodev' parameter expects a valid object
  120. {'device':'virtio-input-host-device', 'expected':True}, # evdev property is required
  121. {'device':'virtio-input-host-pci', 'expected':True}, # evdev property is required
  122. {'device':'xen-pvdevice', 'expected':True}, # Device ID invalid, it must always be supplied
  123. {'device':'vhost-vsock-ccw', 'expected':True}, # guest-cid property must be greater than 2
  124. {'device':'zpci', 'expected':True}, # target must be defined
  125. {'device':'pnv-(occ|icp|lpc)', 'expected':True}, # required link 'xics' not found: Property '.xics' not found
  126. {'device':'powernv-cpu-.*', 'expected':True}, # pnv_core_realize: required link 'xics' not found: Property '.xics' not found
  127. # ioapic devices are already created by pc and will fail:
  128. {'machine':'q35|pc.*', 'device':'kvm-ioapic', 'expected':True}, # Only 1 ioapics allowed
  129. {'machine':'q35|pc.*', 'device':'ioapic', 'expected':True}, # Only 1 ioapics allowed
  130. # "spapr-cpu-core needs a pseries machine"
  131. {'machine':'(?!pseries).*', 'device':'.*-spapr-cpu-core', 'expected':True},
  132. # KVM-specific devices shouldn't be tried without accel=kvm:
  133. {'accel':'(?!kvm).*', 'device':'kvmclock', 'expected':True},
  134. # xen-specific machines and devices:
  135. {'accel':'(?!xen).*', 'machine':'xen.*', 'expected':True},
  136. {'accel':'(?!xen).*', 'device':'xen-.*', 'expected':True},
  137. # this fails on some machine-types, but not all, so they don't have expected=True:
  138. {'device':'vmgenid'}, # vmgenid requires DMA write support in fw_cfg, which this machine type does not provide
  139. # Silence INFO messages for errors that are common on multiple
  140. # devices/machines:
  141. {'log':r"No '[\w-]+' bus found for device '[\w-]+'"},
  142. {'log':r"images* must be given with the 'pflash' parameter"},
  143. {'log':r"(Guest|ROM|Flash|Kernel) image must be specified"},
  144. {'log':r"[cC]ould not load [\w ]+ (BIOS|bios) '[\w-]+\.bin'"},
  145. {'log':r"Couldn't find rom image '[\w-]+\.bin'"},
  146. {'log':r"speed mismatch trying to attach usb device"},
  147. {'log':r"Can't create a second ISA bus"},
  148. {'log':r"duplicate fw_cfg file name"},
  149. # sysbus-related error messages: most machines reject most dynamic sysbus devices:
  150. {'log':r"Option '-device [\w.,-]+' cannot be handled by this machine"},
  151. {'log':r"Device [\w.,-]+ is not supported by this machine yet"},
  152. {'log':r"Device [\w.,-]+ can not be dynamically instantiated"},
  153. {'log':r"Platform Bus: Can not fit MMIO region of size "},
  154. # other more specific errors we will ignore:
  155. {'device':'.*-spapr-cpu-core', 'log':r"CPU core type should be"},
  156. {'log':r"MSI(-X)? is not supported by interrupt controller"},
  157. {'log':r"pxb-pcie? devices cannot reside on a PCIe? bus"},
  158. {'log':r"Ignoring smp_cpus value"},
  159. {'log':r"sd_init failed: Drive 'sd0' is already in use because it has been automatically connected to another device"},
  160. {'log':r"This CPU requires a smaller page size than the system is using"},
  161. {'log':r"MSI-X support is mandatory in the S390 architecture"},
  162. {'log':r"rom check and register reset failed"},
  163. {'log':r"Unable to initialize GIC, CPUState for CPU#0 not valid"},
  164. {'log':r"Multiple VT220 operator consoles are not supported"},
  165. {'log':r"core 0 already populated"},
  166. {'log':r"could not find stage1 bootloader"},
  167. # other exitcode=1 failures not listed above will just generate INFO messages:
  168. {'exitcode':1, 'loglevel':logging.INFO},
  169. # everything else (including SIGABRT and SIGSEGV) will be a fatal error:
  170. {'exitcode':None, 'fatal':True, 'loglevel':logging.FATAL},
  171. ]
  172. def whitelistTestCaseMatch(wl, t):
  173. """Check if a test case specification can match a whitelist entry
  174. This only checks if a whitelist entry is a candidate match
  175. for a given test case, it won't check if the test case
  176. results/output match the entry. See whitelistResultMatch().
  177. """
  178. return (('machine' not in wl or
  179. 'machine' not in t or
  180. re.match(wl['machine'] + '$', t['machine'])) and
  181. ('accel' not in wl or
  182. 'accel' not in t or
  183. re.match(wl['accel'] + '$', t['accel'])) and
  184. ('device' not in wl or
  185. 'device' not in t or
  186. re.match(wl['device'] + '$', t['device'])))
  187. def whitelistCandidates(t):
  188. """Generate the list of candidates that can match a test case"""
  189. for i, wl in enumerate(ERROR_WHITELIST):
  190. if whitelistTestCaseMatch(wl, t):
  191. yield (i, wl)
  192. def findExpectedResult(t):
  193. """Check if there's an expected=True whitelist entry for a test case
  194. Returns (i, wl) tuple, where i is the index in
  195. ERROR_WHITELIST and wl is the whitelist entry itself.
  196. """
  197. for i, wl in whitelistCandidates(t):
  198. if wl.get('expected'):
  199. return (i, wl)
  200. def whitelistResultMatch(wl, r):
  201. """Check if test case results/output match a whitelist entry
  202. It is valid to call this function only if
  203. whitelistTestCaseMatch() is True for the entry (e.g. on
  204. entries returned by whitelistCandidates())
  205. """
  206. assert whitelistTestCaseMatch(wl, r['testcase'])
  207. return ((wl.get('exitcode', 1) is None or
  208. r['exitcode'] == wl.get('exitcode', 1)) and
  209. ('log' not in wl or
  210. re.search(wl['log'], r['log'], re.MULTILINE)))
  211. def checkResultWhitelist(r):
  212. """Look up whitelist entry for a given test case result
  213. Returns (i, wl) tuple, where i is the index in
  214. ERROR_WHITELIST and wl is the whitelist entry itself.
  215. """
  216. for i, wl in whitelistCandidates(r['testcase']):
  217. if whitelistResultMatch(wl, r):
  218. return i, wl
  219. raise Exception("this should never happen")
  220. def qemuOptsEscape(s):
  221. """Escape option value QemuOpts"""
  222. return s.replace(",", ",,")
  223. def formatTestCase(t):
  224. """Format test case info as "key=value key=value" for prettier logging output"""
  225. return ' '.join('%s=%s' % (k, v) for k, v in t.items())
  226. def qomListTypeNames(vm, **kwargs):
  227. """Run qom-list-types QMP command, return type names"""
  228. types = vm.command('qom-list-types', **kwargs)
  229. return [t['name'] for t in types]
  230. def infoQDM(vm):
  231. """Parse 'info qdm' output"""
  232. args = {'command-line': 'info qdm'}
  233. devhelp = vm.command('human-monitor-command', **args)
  234. for l in devhelp.split('\n'):
  235. l = l.strip()
  236. if l == '' or l.endswith(':'):
  237. continue
  238. d = {'name': re.search(r'name "([^"]+)"', l).group(1),
  239. 'no-user': (re.search(', no-user', l) is not None)}
  240. yield d
  241. class QemuBinaryInfo(object):
  242. def __init__(self, binary, devtype):
  243. if devtype is None:
  244. devtype = 'device'
  245. self.binary = binary
  246. self._machine_info = {}
  247. dbg("devtype: %r", devtype)
  248. args = ['-S', '-machine', 'none,accel=kvm:tcg']
  249. dbg("querying info for QEMU binary: %s", binary)
  250. vm = QEMUMachine(binary=binary, args=args)
  251. vm.launch()
  252. try:
  253. self.alldevs = set(qomListTypeNames(vm, implements=devtype, abstract=False))
  254. # there's no way to query DeviceClass::user_creatable using QMP,
  255. # so use 'info qdm':
  256. self.no_user_devs = set([d['name'] for d in infoQDM(vm, ) if d['no-user']])
  257. self.machines = list(m['name'] for m in vm.command('query-machines'))
  258. self.user_devs = self.alldevs.difference(self.no_user_devs)
  259. self.kvm_available = vm.command('query-kvm')['enabled']
  260. finally:
  261. vm.shutdown()
  262. def machineInfo(self, machine):
  263. """Query for information on a specific machine-type
  264. Results are cached internally, in case the same machine-
  265. type is queried multiple times.
  266. """
  267. if machine in self._machine_info:
  268. return self._machine_info[machine]
  269. mi = {}
  270. args = ['-S', '-machine', '%s' % (machine)]
  271. dbg("querying machine info for binary=%s machine=%s", self.binary, machine)
  272. vm = QEMUMachine(binary=self.binary, args=args)
  273. try:
  274. vm.launch()
  275. mi['runnable'] = True
  276. except KeyboardInterrupt:
  277. raise
  278. except:
  279. dbg("exception trying to run binary=%s machine=%s", self.binary, machine, exc_info=sys.exc_info())
  280. dbg("log: %r", vm.get_log())
  281. mi['runnable'] = False
  282. vm.shutdown()
  283. self._machine_info[machine] = mi
  284. return mi
  285. BINARY_INFO = {}
  286. def getBinaryInfo(args, binary):
  287. if binary not in BINARY_INFO:
  288. BINARY_INFO[binary] = QemuBinaryInfo(binary, args.devtype)
  289. return BINARY_INFO[binary]
  290. def checkOneCase(args, testcase):
  291. """Check one specific case
  292. Returns a dictionary containing failure information on error,
  293. or None on success
  294. """
  295. binary = testcase['binary']
  296. accel = testcase['accel']
  297. machine = testcase['machine']
  298. device = testcase['device']
  299. dbg("will test: %r", testcase)
  300. args = ['-S', '-machine', '%s,accel=%s' % (machine, accel),
  301. '-device', qemuOptsEscape(device)]
  302. cmdline = ' '.join([binary] + args)
  303. dbg("will launch QEMU: %s", cmdline)
  304. vm = QEMUMachine(binary=binary, args=args)
  305. exc_traceback = None
  306. try:
  307. vm.launch()
  308. except KeyboardInterrupt:
  309. raise
  310. except:
  311. exc_traceback = traceback.format_exc()
  312. dbg("Exception while running test case")
  313. finally:
  314. vm.shutdown()
  315. ec = vm.exitcode()
  316. log = vm.get_log()
  317. if exc_traceback is not None or ec != 0:
  318. return {'exc_traceback':exc_traceback,
  319. 'exitcode':ec,
  320. 'log':log,
  321. 'testcase':testcase,
  322. 'cmdline':cmdline}
  323. def binariesToTest(args, testcase):
  324. if args.qemu:
  325. r = args.qemu
  326. else:
  327. r = glob.glob('./*-softmmu/qemu-system-*')
  328. return r
  329. def accelsToTest(args, testcase):
  330. if getBinaryInfo(args, testcase['binary']).kvm_available:
  331. yield 'kvm'
  332. yield 'tcg'
  333. def machinesToTest(args, testcase):
  334. return getBinaryInfo(args, testcase['binary']).machines
  335. def devicesToTest(args, testcase):
  336. return getBinaryInfo(args, testcase['binary']).user_devs
  337. TESTCASE_VARIABLES = [
  338. ('binary', binariesToTest),
  339. ('accel', accelsToTest),
  340. ('machine', machinesToTest),
  341. ('device', devicesToTest),
  342. ]
  343. def genCases1(args, testcases, var, fn):
  344. """Generate new testcases for one variable
  345. If an existing item already has a variable set, don't
  346. generate new items and just return it directly. This
  347. allows the "-t" command-line option to be used to choose
  348. a specific test case.
  349. """
  350. for testcase in testcases:
  351. if var in testcase:
  352. yield testcase.copy()
  353. else:
  354. for i in fn(args, testcase):
  355. t = testcase.copy()
  356. t[var] = i
  357. yield t
  358. def genCases(args, testcase):
  359. """Generate test cases for all variables
  360. """
  361. cases = [testcase.copy()]
  362. for var, fn in TESTCASE_VARIABLES:
  363. dbg("var: %r, fn: %r", var, fn)
  364. cases = genCases1(args, cases, var, fn)
  365. return cases
  366. def casesToTest(args, testcase):
  367. cases = genCases(args, testcase)
  368. if args.random:
  369. cases = list(cases)
  370. cases = random.sample(cases, min(args.random, len(cases)))
  371. if args.debug:
  372. cases = list(cases)
  373. dbg("%d test cases to test", len(cases))
  374. if args.shuffle:
  375. cases = list(cases)
  376. random.shuffle(cases)
  377. return cases
  378. def logFailure(f, level):
  379. t = f['testcase']
  380. logger.log(level, "failed: %s", formatTestCase(t))
  381. logger.log(level, "cmdline: %s", f['cmdline'])
  382. for l in f['log'].strip().split('\n'):
  383. logger.log(level, "log: %s", l)
  384. logger.log(level, "exit code: %r", f['exitcode'])
  385. if f['exc_traceback']:
  386. logger.log(level, "exception:")
  387. for l in f['exc_traceback'].split('\n'):
  388. logger.log(level, " %s", l.rstrip('\n'))
  389. def main():
  390. parser = argparse.ArgumentParser(description="QEMU -device crash test")
  391. parser.add_argument('-t', metavar='KEY=VALUE', nargs='*',
  392. help="Limit test cases to KEY=VALUE",
  393. action='append', dest='testcases', default=[])
  394. parser.add_argument('-d', '--debug', action='store_true',
  395. help='debug output')
  396. parser.add_argument('-v', '--verbose', action='store_true', default=True,
  397. help='verbose output')
  398. parser.add_argument('-q', '--quiet', dest='verbose', action='store_false',
  399. help='non-verbose output')
  400. parser.add_argument('-r', '--random', type=int, metavar='COUNT',
  401. help='run a random sample of COUNT test cases',
  402. default=0)
  403. parser.add_argument('--shuffle', action='store_true',
  404. help='Run test cases in random order')
  405. parser.add_argument('--dry-run', action='store_true',
  406. help="Don't run any tests, just generate list")
  407. parser.add_argument('-D', '--devtype', metavar='TYPE',
  408. help="Test only device types that implement TYPE")
  409. parser.add_argument('-Q', '--quick', action='store_true', default=True,
  410. help="Quick mode: skip test cases that are expected to fail")
  411. parser.add_argument('-F', '--full', action='store_false', dest='quick',
  412. help="Full mode: test cases that are expected to fail")
  413. parser.add_argument('--strict', action='store_true', dest='strict',
  414. help="Treat all warnings as fatal")
  415. parser.add_argument('qemu', nargs='*', metavar='QEMU',
  416. help='QEMU binary to run')
  417. args = parser.parse_args()
  418. if args.debug:
  419. lvl = logging.DEBUG
  420. elif args.verbose:
  421. lvl = logging.INFO
  422. else:
  423. lvl = logging.WARN
  424. logging.basicConfig(stream=sys.stdout, level=lvl, format='%(levelname)s: %(message)s')
  425. fatal_failures = []
  426. wl_stats = {}
  427. skipped = 0
  428. total = 0
  429. tc = {}
  430. dbg("testcases: %r", args.testcases)
  431. if args.testcases:
  432. for t in chain(*args.testcases):
  433. for kv in t.split():
  434. k, v = kv.split('=', 1)
  435. tc[k] = v
  436. if len(binariesToTest(args, tc)) == 0:
  437. print("No QEMU binary found", file=sys.stderr)
  438. parser.print_usage(sys.stderr)
  439. return 1
  440. for t in casesToTest(args, tc):
  441. logger.info("running test case: %s", formatTestCase(t))
  442. total += 1
  443. expected_match = findExpectedResult(t)
  444. if (args.quick and
  445. (expected_match or
  446. not getBinaryInfo(args, t['binary']).machineInfo(t['machine'])['runnable'])):
  447. dbg("skipped: %s", formatTestCase(t))
  448. skipped += 1
  449. continue
  450. if args.dry_run:
  451. continue
  452. try:
  453. f = checkOneCase(args, t)
  454. except KeyboardInterrupt:
  455. break
  456. if f:
  457. i, wl = checkResultWhitelist(f)
  458. dbg("testcase: %r, whitelist match: %r", t, wl)
  459. wl_stats.setdefault(i, []).append(f)
  460. level = wl.get('loglevel', logging.DEBUG)
  461. logFailure(f, level)
  462. if wl.get('fatal') or (args.strict and level >= logging.WARN):
  463. fatal_failures.append(f)
  464. else:
  465. dbg("success: %s", formatTestCase(t))
  466. if expected_match:
  467. logger.warn("Didn't fail as expected: %s", formatTestCase(t))
  468. logger.info("Total: %d test cases", total)
  469. if skipped:
  470. logger.info("Skipped %d test cases", skipped)
  471. if args.debug:
  472. stats = sorted([(len(wl_stats.get(i, [])), wl) for i, wl in
  473. enumerate(ERROR_WHITELIST)], key=lambda x: x[0])
  474. for count, wl in stats:
  475. dbg("whitelist entry stats: %d: %r", count, wl)
  476. if fatal_failures:
  477. for f in fatal_failures:
  478. t = f['testcase']
  479. logger.error("Fatal failure: %s", formatTestCase(t))
  480. logger.error("Fatal failures on some machine/device combinations")
  481. return 1
  482. if __name__ == '__main__':
  483. sys.exit(main())