device-crash-test 24 KB

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