run.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 curses
  23. import itertools
  24. import logging
  25. import logging.handlers
  26. import os
  27. import socket
  28. import subprocess
  29. import sys
  30. import unittest
  31. import unittest.signals
  32. import qubes.tests
  33. class CursesColor(dict):
  34. colors = (
  35. 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
  36. attrs = {
  37. 'bold': 'bold', 'normal': 'sgr0'}
  38. def __init__(self):
  39. super(CursesColor, self).__init__()
  40. self.has_colors = False
  41. try:
  42. curses.setupterm()
  43. self.has_colors = True
  44. except curses.error:
  45. return
  46. def __missing__(self, key):
  47. # pylint: disable=unused-argument,no-self-use
  48. if not self.has_colors:
  49. return ''
  50. try:
  51. value = curses.tigetstr(self.attrs[key])
  52. except KeyError:
  53. try:
  54. value = curses.tparm(
  55. curses.tigetstr('setaf'), self.colors.index(key))
  56. except ValueError:
  57. return ''
  58. value = value.decode()
  59. self[key] = value
  60. return value
  61. class QubesTestResult(unittest.TestResult):
  62. '''A test result class that can print colourful text results to a stream.
  63. Used by TextTestRunner. This is a lightly rewritten unittest.TextTestResult.
  64. '''
  65. separator1 = unittest.TextTestResult.separator1
  66. separator2 = unittest.TextTestResult.separator2
  67. def __init__(self, stream, descriptions, verbosity):
  68. super(QubesTestResult, self).__init__(stream, descriptions, verbosity)
  69. self.stream = stream
  70. self.showAll = verbosity > 1 # pylint: disable=invalid-name
  71. self.dots = verbosity == 1
  72. self.descriptions = descriptions
  73. self.color = CursesColor()
  74. self.hostname = socket.gethostname()
  75. self.log = logging.getLogger('qubes.tests')
  76. def _fmtexc(self, err):
  77. if str(err[1]):
  78. return '{color[bold]}{}:{color[normal]} {!s}'.format(
  79. err[0].__name__, err[1], color=self.color)
  80. else:
  81. return '{color[bold]}{}{color[normal]}'.format(
  82. err[0].__name__, color=self.color)
  83. def get_log(self, test):
  84. try:
  85. return test.log
  86. except AttributeError:
  87. return self.log
  88. def getDescription(self, test): # pylint: disable=invalid-name
  89. teststr = str(test).split('/')
  90. for i in range(-2, 0):
  91. try:
  92. fullname = teststr[i].split('_', 2)
  93. except IndexError:
  94. continue
  95. fullname[-1] = '{color[bold]}{}{color[normal]}'.format(
  96. fullname[-1], color=self.color)
  97. teststr[i] = '_'.join(fullname)
  98. teststr = '/'.join(teststr)
  99. doc_first_line = test.shortDescription()
  100. if self.descriptions and doc_first_line:
  101. return '\n'.join((teststr, ' {}'.format(
  102. doc_first_line, color=self.color)))
  103. else:
  104. return teststr
  105. def startTest(self, test): # pylint: disable=invalid-name
  106. super(QubesTestResult, self).startTest(test)
  107. self.get_log(test).critical('started')
  108. if self.showAll:
  109. if not qubes.tests.in_git:
  110. self.stream.write('{}: '.format(self.hostname))
  111. self.stream.write(self.getDescription(test))
  112. self.stream.write(' ... ')
  113. self.stream.flush()
  114. def addSuccess(self, test): # pylint: disable=invalid-name
  115. super(QubesTestResult, self).addSuccess(test)
  116. self.get_log(test).warning('ok')
  117. if self.showAll:
  118. self.stream.writeln('{color[green]}ok{color[normal]}'.format(
  119. color=self.color))
  120. elif self.dots:
  121. self.stream.write('.')
  122. self.stream.flush()
  123. def addError(self, test, err): # pylint: disable=invalid-name
  124. super(QubesTestResult, self).addError(test, err)
  125. self.get_log(test).critical(
  126. 'ERROR ({err[0].__name__}: {err[1]!r})'.format(err=err))
  127. if self.showAll:
  128. self.stream.writeln(
  129. '{color[red]}{color[bold]}ERROR{color[normal]} ({})'.format(
  130. self._fmtexc(err), color=self.color))
  131. elif self.dots:
  132. self.stream.write(
  133. '{color[red]}{color[bold]}E{color[normal]}'.format(
  134. color=self.color))
  135. self.stream.flush()
  136. def addFailure(self, test, err): # pylint: disable=invalid-name
  137. super(QubesTestResult, self).addFailure(test, err)
  138. self.get_log(test).error(
  139. 'FAIL ({err[0].__name__}: {err[1]!r})'.format(err=err))
  140. if self.showAll:
  141. self.stream.writeln('{color[red]}FAIL{color[normal]}'.format(
  142. color=self.color))
  143. elif self.dots:
  144. self.stream.write('{color[red]}F{color[normal]}'.format(
  145. color=self.color))
  146. self.stream.flush()
  147. def addSkip(self, test, reason): # pylint: disable=invalid-name
  148. super(QubesTestResult, self).addSkip(test, reason)
  149. self.get_log(test).warning('skipped ({})'.format(reason))
  150. if self.showAll:
  151. self.stream.writeln(
  152. '{color[cyan]}skipped{color[normal]} ({})'.format(
  153. reason, color=self.color))
  154. elif self.dots:
  155. self.stream.write('{color[cyan]}s{color[normal]}'.format(
  156. color=self.color))
  157. self.stream.flush()
  158. def addExpectedFailure(self, test, err): # pylint: disable=invalid-name
  159. super(QubesTestResult, self).addExpectedFailure(test, err)
  160. self.get_log(test).warning('expected failure')
  161. if self.showAll:
  162. self.stream.writeln(
  163. '{color[yellow]}expected failure{color[normal]}'.format(
  164. color=self.color))
  165. elif self.dots:
  166. self.stream.write('{color[yellow]}x{color[normal]}'.format(
  167. color=self.color))
  168. self.stream.flush()
  169. def addUnexpectedSuccess(self, test): # pylint: disable=invalid-name
  170. super(QubesTestResult, self).addUnexpectedSuccess(test)
  171. self.get_log(test).error('unexpected success')
  172. if self.showAll:
  173. self.stream.writeln(
  174. '{color[yellow]}{color[bold]}unexpected success'
  175. '{color[normal]}'.format(color=self.color))
  176. elif self.dots:
  177. self.stream.write(
  178. '{color[yellow]}{color[bold]}u{color[normal]}'.format(
  179. color=self.color))
  180. self.stream.flush()
  181. def printErrors(self): # pylint: disable=invalid-name
  182. if self.dots or self.showAll:
  183. self.stream.writeln()
  184. self.printErrorList(
  185. '{color[red]}{color[bold]}ERROR{color[normal]}'.format(
  186. color=self.color),
  187. self.errors)
  188. self.printErrorList(
  189. '{color[red]}FAIL{color[normal]}'.format(
  190. color=self.color),
  191. self.failures)
  192. self.printErrorList(
  193. '{color[yellow]}EXPECTED{color[normal]}'.format(
  194. color=self.color),
  195. self.expectedFailures)
  196. def printErrorList(self, flavour, errors): # pylint: disable=invalid-name
  197. for test, err in errors:
  198. self.stream.writeln(self.separator1)
  199. self.stream.writeln('%s: %s' % (flavour, self.getDescription(test)))
  200. self.stream.writeln(self.separator2)
  201. self.stream.writeln('%s' % err)
  202. class QubesDNCTestResult(QubesTestResult):
  203. do_not_clean = True
  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. parser.add_argument('--do-not-clean', '--dnc', '-D',
  256. action='store_true', dest='do_not_clean',
  257. help='do not execute tearDown on failed tests. Implies --failfast.')
  258. parser.add_argument('--do-clean', '-C',
  259. action='store_false', dest='do_not_clean',
  260. help='do execute tearDown even on failed tests.')
  261. # pylint: disable=protected-access
  262. try:
  263. name_to_level = logging._nameToLevel
  264. except AttributeError:
  265. name_to_level = logging._levelNames
  266. parser.add_argument('--loglevel', '-L', metavar='LEVEL',
  267. action='store', choices=tuple(k
  268. for k in sorted(name_to_level.keys(),
  269. key=lambda x: name_to_level[x])
  270. if isinstance(k, str)),
  271. help='logging level for file and syslog forwarding '
  272. '(one of: %(choices)s; default: %(default)s)')
  273. del name_to_level
  274. # pylint: enable=protected-access
  275. parser.add_argument('--logfile', '-o', metavar='FILE',
  276. action='store',
  277. help='if set, test run will be also logged to file')
  278. parser.add_argument('--syslog',
  279. action='store_true', dest='syslog',
  280. help='reenable logging to syslog')
  281. parser.add_argument('--no-syslog',
  282. action='store_false', dest='syslog',
  283. help='disable logging to syslog')
  284. parser.add_argument('--kmsg', '--very-brave-or-very-stupid',
  285. action='store_true', dest='kmsg',
  286. help='log most important things to kernel ring-buffer')
  287. parser.add_argument('--no-kmsg', '--i-am-smarter-than-kay-sievers',
  288. action='store_false', dest='kmsg',
  289. help='do not abuse kernel ring-buffer')
  290. parser.add_argument('names', metavar='TESTNAME',
  291. action='store', nargs='*',
  292. help='list of tests to run named like in description '
  293. '(default: run all tests)')
  294. parser.set_defaults(
  295. failfast=False,
  296. loglevel='DEBUG',
  297. logfile=None,
  298. syslog=True,
  299. kmsg=False,
  300. verbose=2,
  301. quiet=0)
  302. def list_test_cases(suite):
  303. for test in suite:
  304. if isinstance(test, unittest.TestSuite):
  305. #yield from
  306. for i in list_test_cases(test):
  307. yield i
  308. else:
  309. yield test
  310. def main():
  311. args = parser.parse_args()
  312. suite = unittest.TestSuite()
  313. loader = unittest.TestLoader()
  314. if args.names:
  315. alltests = loader.loadTestsFromName('qubes.tests')
  316. for name in args.names:
  317. suite.addTests(
  318. [test for test in list_test_cases(alltests)
  319. if str(test).startswith(name)])
  320. else:
  321. suite.addTests(loader.loadTestsFromName('qubes.tests'))
  322. if args.list:
  323. for test in list_test_cases(suite):
  324. print(str(test)) # pylint: disable=superfluous-parens
  325. return True
  326. if args.do_not_clean:
  327. args.failfast = True
  328. logging.root.setLevel(args.loglevel)
  329. if args.logfile is not None:
  330. ha_file = logging.FileHandler(
  331. os.path.join(os.environ['HOME'], args.logfile))
  332. ha_file.setFormatter(
  333. logging.Formatter('%(asctime)s %(name)s[%(process)d]: %(message)s'))
  334. logging.root.addHandler(ha_file)
  335. if args.syslog:
  336. ha_syslog = logging.handlers.SysLogHandler('/dev/log')
  337. ha_syslog.setFormatter(
  338. logging.Formatter('%(name)s[%(process)d]: %(message)s'))
  339. logging.root.addHandler(ha_syslog)
  340. if args.kmsg:
  341. try:
  342. subprocess.check_call(('sudo', 'chmod', '666', '/dev/kmsg'))
  343. except subprocess.CalledProcessError:
  344. parser.error('could not chmod /dev/kmsg')
  345. else:
  346. ha_kmsg = logging.FileHandler('/dev/kmsg', 'w')
  347. ha_kmsg.setFormatter(
  348. logging.Formatter('%(name)s[%(process)d]: %(message)s'))
  349. ha_kmsg.setLevel(logging.CRITICAL)
  350. logging.root.addHandler(ha_kmsg)
  351. runner = unittest.TextTestRunner(stream=sys.stdout,
  352. verbosity=(args.verbose-args.quiet),
  353. failfast=args.failfast)
  354. unittest.signals.installHandler()
  355. runner.resultclass = QubesDNCTestResult \
  356. if args.do_not_clean else QubesTestResult
  357. return runner.run(suite).wasSuccessful()
  358. if __name__ == '__main__':
  359. sys.exit(not main())