run.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. import argparse
  22. import code
  23. import curses
  24. import itertools
  25. import logging
  26. import logging.handlers
  27. import os
  28. import socket
  29. import subprocess
  30. import sys
  31. import unittest
  32. import unittest.signals
  33. import qubes.tests
  34. import qubes.api.admin
  35. class CursesColor(dict):
  36. colors = (
  37. 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
  38. attrs = {
  39. 'bold': 'bold', 'normal': 'sgr0'}
  40. def __init__(self):
  41. super(CursesColor, self).__init__()
  42. self.has_colors = False
  43. try:
  44. curses.setupterm()
  45. self.has_colors = True
  46. except curses.error:
  47. return
  48. def __missing__(self, key):
  49. # pylint: disable=unused-argument,no-self-use
  50. if not self.has_colors:
  51. return ''
  52. try:
  53. value = curses.tigetstr(self.attrs[key])
  54. except KeyError:
  55. try:
  56. value = curses.tparm(
  57. curses.tigetstr('setaf'), self.colors.index(key))
  58. except ValueError:
  59. return ''
  60. value = value.decode()
  61. self[key] = value
  62. return value
  63. class QubesTestResult(unittest.TestResult):
  64. '''A test result class that can print colourful text results to a stream.
  65. Used by TextTestRunner. This is a lightly rewritten unittest.TextTestResult.
  66. '''
  67. separator1 = unittest.TextTestResult.separator1
  68. separator2 = unittest.TextTestResult.separator2
  69. def __init__(self, stream, descriptions, verbosity):
  70. super(QubesTestResult, self).__init__(stream, descriptions, verbosity)
  71. self.stream = stream
  72. self.showAll = verbosity > 1 # pylint: disable=invalid-name
  73. self.dots = verbosity == 1
  74. self.descriptions = descriptions
  75. self.color = CursesColor()
  76. self.hostname = socket.gethostname()
  77. self.log = logging.getLogger('qubes.tests')
  78. def _fmtexc(self, err):
  79. if str(err[1]):
  80. return '{color[bold]}{}:{color[normal]} {!s}'.format(
  81. err[0].__name__, err[1], color=self.color)
  82. else:
  83. return '{color[bold]}{}{color[normal]}'.format(
  84. err[0].__name__, color=self.color)
  85. def get_log(self, test):
  86. try:
  87. return test.log
  88. except AttributeError:
  89. return self.log
  90. def getDescription(self, test): # pylint: disable=invalid-name
  91. teststr = str(test).split('/')
  92. for i in range(-2, 0):
  93. try:
  94. fullname = teststr[i].split('_', 2)
  95. except IndexError:
  96. continue
  97. fullname[-1] = '{color[bold]}{}{color[normal]}'.format(
  98. fullname[-1], color=self.color)
  99. teststr[i] = '_'.join(fullname)
  100. teststr = '/'.join(teststr)
  101. doc_first_line = test.shortDescription()
  102. if self.descriptions and doc_first_line:
  103. return '\n'.join((teststr, ' {}'.format(
  104. doc_first_line, color=self.color)))
  105. else:
  106. return teststr
  107. def startTest(self, test): # pylint: disable=invalid-name
  108. super(QubesTestResult, self).startTest(test)
  109. self.get_log(test).critical('started')
  110. if self.showAll:
  111. if not qubes.tests.in_git:
  112. self.stream.write('{}: '.format(self.hostname))
  113. self.stream.write(self.getDescription(test))
  114. self.stream.write(' ... ')
  115. self.stream.flush()
  116. def addSuccess(self, test): # pylint: disable=invalid-name
  117. super(QubesTestResult, self).addSuccess(test)
  118. self.get_log(test).warning('ok')
  119. if self.showAll:
  120. self.stream.writeln('{color[green]}ok{color[normal]}'.format(
  121. color=self.color))
  122. elif self.dots:
  123. self.stream.write('.')
  124. self.stream.flush()
  125. def addError(self, test, err): # pylint: disable=invalid-name
  126. super(QubesTestResult, self).addError(test, err)
  127. self.get_log(test).critical(
  128. 'ERROR ({err[0].__name__}: {err[1]!r})'.format(err=err))
  129. if self.showAll:
  130. self.stream.writeln(
  131. '{color[red]}{color[bold]}ERROR{color[normal]} ({})'.format(
  132. self._fmtexc(err), color=self.color))
  133. elif self.dots:
  134. self.stream.write(
  135. '{color[red]}{color[bold]}E{color[normal]}'.format(
  136. color=self.color))
  137. self.stream.flush()
  138. def addFailure(self, test, err): # pylint: disable=invalid-name
  139. super(QubesTestResult, self).addFailure(test, err)
  140. self.get_log(test).error(
  141. 'FAIL ({err[0].__name__}: {err[1]!r})'.format(err=err))
  142. if self.showAll:
  143. self.stream.writeln('{color[red]}FAIL{color[normal]}'.format(
  144. color=self.color))
  145. elif self.dots:
  146. self.stream.write('{color[red]}F{color[normal]}'.format(
  147. color=self.color))
  148. self.stream.flush()
  149. def addSkip(self, test, reason): # pylint: disable=invalid-name
  150. super(QubesTestResult, self).addSkip(test, reason)
  151. self.get_log(test).warning('skipped ({})'.format(reason))
  152. if self.showAll:
  153. self.stream.writeln(
  154. '{color[cyan]}skipped{color[normal]} ({})'.format(
  155. reason, color=self.color))
  156. elif self.dots:
  157. self.stream.write('{color[cyan]}s{color[normal]}'.format(
  158. color=self.color))
  159. self.stream.flush()
  160. def addExpectedFailure(self, test, err): # pylint: disable=invalid-name
  161. super(QubesTestResult, self).addExpectedFailure(test, err)
  162. self.get_log(test).warning('expected failure')
  163. if self.showAll:
  164. self.stream.writeln(
  165. '{color[yellow]}expected failure{color[normal]}'.format(
  166. color=self.color))
  167. elif self.dots:
  168. self.stream.write('{color[yellow]}x{color[normal]}'.format(
  169. color=self.color))
  170. self.stream.flush()
  171. def addUnexpectedSuccess(self, test): # pylint: disable=invalid-name
  172. super(QubesTestResult, self).addUnexpectedSuccess(test)
  173. self.get_log(test).error('unexpected success')
  174. if self.showAll:
  175. self.stream.writeln(
  176. '{color[yellow]}{color[bold]}unexpected success'
  177. '{color[normal]}'.format(color=self.color))
  178. elif self.dots:
  179. self.stream.write(
  180. '{color[yellow]}{color[bold]}u{color[normal]}'.format(
  181. color=self.color))
  182. self.stream.flush()
  183. def printErrors(self): # pylint: disable=invalid-name
  184. if self.dots or self.showAll:
  185. self.stream.writeln()
  186. self.printErrorList(
  187. '{color[red]}{color[bold]}ERROR{color[normal]}'.format(
  188. color=self.color),
  189. self.errors)
  190. self.printErrorList(
  191. '{color[red]}FAIL{color[normal]}'.format(
  192. color=self.color),
  193. self.failures)
  194. self.printErrorList(
  195. '{color[yellow]}EXPECTED{color[normal]}'.format(
  196. color=self.color),
  197. self.expectedFailures)
  198. def printErrorList(self, flavour, errors): # pylint: disable=invalid-name
  199. for test, err in errors:
  200. self.stream.writeln(self.separator1)
  201. self.stream.writeln('%s: %s' % (flavour, self.getDescription(test)))
  202. self.stream.writeln(self.separator2)
  203. self.stream.writeln('%s' % err)
  204. def demo(verbosity=2):
  205. class TC_00_Demo(qubes.tests.QubesTestCase):
  206. '''Demo class'''
  207. # pylint: disable=no-self-use
  208. def test_0_success(self):
  209. '''Demo test (success)'''
  210. pass
  211. def test_1_error(self):
  212. '''Demo test (error)'''
  213. raise Exception()
  214. def test_2_failure(self):
  215. '''Demo test (failure)'''
  216. self.fail('boo')
  217. def test_3_skip(self):
  218. '''Demo test (skipped by call to self.skipTest())'''
  219. self.skipTest('skip')
  220. @unittest.skip(None)
  221. def test_4_skip_decorator(self):
  222. '''Demo test (skipped by decorator)'''
  223. pass
  224. @unittest.expectedFailure
  225. def test_5_expected_failure(self):
  226. '''Demo test (expected failure)'''
  227. self.fail()
  228. @unittest.expectedFailure
  229. def test_6_unexpected_success(self):
  230. '''Demo test (unexpected success)'''
  231. pass
  232. suite = unittest.TestLoader().loadTestsFromTestCase(TC_00_Demo)
  233. runner = unittest.TextTestRunner(stream=sys.stdout, verbosity=verbosity)
  234. runner.resultclass = QubesTestResult
  235. return runner.run(suite).wasSuccessful()
  236. parser = argparse.ArgumentParser(
  237. epilog='''When running only specific tests, write their names like in log,
  238. in format: MODULE+"/"+CLASS+"/"+FUNCTION. MODULE should omit initial
  239. "qubes.tests.". Example: basic/TC_00_Basic/test_000_create''')
  240. parser.add_argument('--verbose', '-v',
  241. action='count',
  242. help='increase console verbosity level')
  243. parser.add_argument('--quiet', '-q',
  244. action='count',
  245. help='decrease console verbosity level')
  246. parser.add_argument('--list', '-l',
  247. action='store_true', dest='list',
  248. help='list all available tests and exit')
  249. parser.add_argument('--failfast', '-f',
  250. action='store_true', dest='failfast',
  251. help='stop on the first fail, error or unexpected success')
  252. parser.add_argument('--no-failfast',
  253. action='store_false', dest='failfast',
  254. help='disable --failfast')
  255. # pylint: disable=protected-access
  256. try:
  257. name_to_level = logging._nameToLevel
  258. except AttributeError:
  259. name_to_level = logging._levelNames
  260. parser.add_argument('--loglevel', '-L', metavar='LEVEL',
  261. action='store', choices=tuple(k
  262. for k in sorted(name_to_level.keys(),
  263. key=lambda x: name_to_level[x])
  264. if isinstance(k, str)),
  265. help='logging level for file and syslog forwarding '
  266. '(one of: %(choices)s; default: %(default)s)')
  267. del name_to_level
  268. # pylint: enable=protected-access
  269. parser.add_argument('--logfile', '-o', metavar='FILE',
  270. action='store',
  271. help='if set, test run will be also logged to file')
  272. parser.add_argument('--syslog',
  273. action='store_true', dest='syslog',
  274. help='reenable logging to syslog')
  275. parser.add_argument('--no-syslog',
  276. action='store_false', dest='syslog',
  277. help='disable logging to syslog')
  278. parser.add_argument('--kmsg', '--very-brave-or-very-stupid',
  279. action='store_true', dest='kmsg',
  280. help='log most important things to kernel ring-buffer')
  281. parser.add_argument('--no-kmsg', '--i-am-smarter-than-kay-sievers',
  282. action='store_false', dest='kmsg',
  283. help='do not abuse kernel ring-buffer')
  284. parser.add_argument('--allow-running-along-qubesd',
  285. action='store_true', default=False,
  286. help='allow running in parallel with qubesd;'
  287. ' this is DANGEROUS and WILL RESULT IN INCONSISTENT SYSTEM STATE')
  288. parser.add_argument('--break-to-repl',
  289. action='store_true', default=False,
  290. help='break to REPL after tests')
  291. parser.add_argument('names', metavar='TESTNAME',
  292. action='store', nargs='*',
  293. help='list of tests to run named like in description '
  294. '(default: run all tests)')
  295. parser.set_defaults(
  296. failfast=False,
  297. loglevel='DEBUG',
  298. logfile=None,
  299. syslog=True,
  300. kmsg=False,
  301. verbose=2,
  302. quiet=0)
  303. def list_test_cases(suite):
  304. for test in suite:
  305. if isinstance(test, unittest.TestSuite):
  306. #yield from
  307. for i in list_test_cases(test):
  308. yield i
  309. else:
  310. yield test
  311. def main(args=None):
  312. args = parser.parse_args(args)
  313. suite = unittest.TestSuite()
  314. loader = unittest.TestLoader()
  315. if args.names:
  316. alltests = loader.loadTestsFromName('qubes.tests')
  317. for name in args.names:
  318. suite.addTests(
  319. [test for test in list_test_cases(alltests)
  320. if str(test).startswith(name)])
  321. else:
  322. suite.addTests(loader.loadTestsFromName('qubes.tests'))
  323. if args.list:
  324. for test in list_test_cases(suite):
  325. print(str(test)) # pylint: disable=superfluous-parens
  326. return True
  327. logging.root.setLevel(args.loglevel)
  328. if args.logfile is not None:
  329. ha_file = logging.FileHandler(
  330. os.path.join(os.environ['HOME'], args.logfile))
  331. ha_file.setFormatter(
  332. logging.Formatter('%(asctime)s %(name)s[%(process)d]: %(message)s'))
  333. logging.root.addHandler(ha_file)
  334. if args.syslog:
  335. ha_syslog = logging.handlers.SysLogHandler('/dev/log')
  336. ha_syslog.setFormatter(
  337. logging.Formatter('%(name)s[%(process)d]: %(message)s'))
  338. logging.root.addHandler(ha_syslog)
  339. if args.kmsg:
  340. try:
  341. subprocess.check_call(('sudo', 'chmod', '666', '/dev/kmsg'))
  342. except subprocess.CalledProcessError:
  343. parser.error('could not chmod /dev/kmsg')
  344. else:
  345. ha_kmsg = logging.FileHandler('/dev/kmsg', 'w')
  346. ha_kmsg.setFormatter(
  347. logging.Formatter('%(name)s[%(process)d]: %(message)s'))
  348. ha_kmsg.setLevel(logging.CRITICAL)
  349. logging.root.addHandler(ha_kmsg)
  350. if not args.allow_running_along_qubesd \
  351. and os.path.exists(qubes.api.admin.QubesAdminAPI.SOCKNAME):
  352. parser.error('refusing to run until qubesd is disabled')
  353. runner = unittest.TextTestRunner(stream=sys.stdout,
  354. verbosity=(args.verbose-args.quiet),
  355. failfast=args.failfast)
  356. unittest.signals.installHandler()
  357. runner.resultclass = QubesTestResult
  358. result = runner.run(suite)
  359. if args.break_to_repl:
  360. code.interact(local=locals())
  361. return result.wasSuccessful()
  362. if __name__ == '__main__':
  363. sys.exit(not main())