__init__.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. # -*- coding: utf-8 -*-
  2. '''
  3. tests.support.parser
  4. ~~~~~~~~~~~~~~~~~~~~
  5. Salt Tests CLI access classes
  6. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  7. :copyright: Copyright 2013-2017 by the SaltStack Team, see AUTHORS for more details
  8. :license: Apache 2.0, see LICENSE for more details.
  9. '''
  10. # pylint: disable=repr-flag-used-in-string
  11. from __future__ import absolute_import, print_function
  12. import fnmatch
  13. import os
  14. import sys
  15. import time
  16. import signal
  17. import shutil
  18. import logging
  19. import platform
  20. import optparse
  21. import re
  22. import tempfile
  23. import traceback
  24. import subprocess
  25. import warnings
  26. from functools import partial
  27. from collections import namedtuple
  28. import tests.support.paths
  29. from tests.support import helpers
  30. from tests.support.unit import TestLoader, TextTestRunner
  31. from tests.support.xmlunit import HAS_XMLRUNNER, XMLTestRunner
  32. # Import 3rd-party libs
  33. from salt.ext import six
  34. import salt.utils.data
  35. import salt.utils.files
  36. import salt.utils.path
  37. import salt.utils.platform
  38. import salt.utils.stringutils
  39. import salt.utils.yaml
  40. try:
  41. from tests.support.ext import console
  42. WIDTH, HEIGHT = console.getTerminalSize()
  43. PNUM = WIDTH
  44. except Exception: # pylint: disable=broad-except
  45. PNUM = 70
  46. log = logging.getLogger(__name__)
  47. # This is a completely random and meaningful number intended to identify our
  48. # own signal triggering.
  49. WEIRD_SIGNAL_NUM = -45654
  50. def __global_logging_exception_handler(exc_type, exc_value, exc_traceback,
  51. _logger=logging.getLogger(__name__),
  52. _stderr=sys.__stderr__,
  53. _format_exception=traceback.format_exception):
  54. '''
  55. This function will log all python exceptions.
  56. '''
  57. if exc_type.__name__ == "KeyboardInterrupt":
  58. # Call the original sys.excepthook
  59. sys.__excepthook__(exc_type, exc_value, exc_traceback)
  60. return
  61. # Log the exception
  62. try:
  63. msg = (
  64. 'An un-handled exception was caught by salt-testing\'s global exception handler:\n{}: {}\n{}'.format(
  65. exc_type.__name__,
  66. exc_value,
  67. ''.join(_format_exception(exc_type, exc_value, exc_traceback)).strip()
  68. )
  69. )
  70. except Exception: # pylint: disable=broad-except
  71. msg = (
  72. 'An un-handled exception was caught by salt-testing\'s global exception handler:\n{}: {}\n'
  73. '(UNABLE TO FORMAT TRACEBACK)'.format(
  74. exc_type.__name__,
  75. exc_value,
  76. )
  77. )
  78. try:
  79. _logger(__name__).error(msg)
  80. except Exception: # pylint: disable=broad-except
  81. # Python is shutting down and logging has been set to None already
  82. try:
  83. _stderr.write(msg + '\n')
  84. except Exception: # pylint: disable=broad-except
  85. # We have also lost reference to sys.__stderr__ ?!
  86. print(msg)
  87. # Call the original sys.excepthook
  88. try:
  89. sys.__excepthook__(exc_type, exc_value, exc_traceback)
  90. except Exception: # pylint: disable=broad-except
  91. # Python is shutting down and sys has been set to None already
  92. pass
  93. # Set our own exception handler as the one to use
  94. sys.excepthook = __global_logging_exception_handler
  95. TestsuiteResult = namedtuple('TestsuiteResult', ['header', 'errors', 'skipped', 'failures', 'passed'])
  96. TestResult = namedtuple('TestResult', ['id', 'reason'])
  97. def print_header(header, sep='~', top=True, bottom=True, inline=False,
  98. centered=False, width=PNUM):
  99. '''
  100. Allows some pretty printing of headers on the console, either with a
  101. "ruler" on bottom and/or top, inline, centered, etc.
  102. '''
  103. if top and not inline:
  104. print(sep * width)
  105. if centered and not inline:
  106. fmt = u'{0:^{width}}'
  107. elif inline and not centered:
  108. fmt = u'{0:{sep}<{width}}'
  109. elif inline and centered:
  110. fmt = u'{0:{sep}^{width}}'
  111. else:
  112. fmt = u'{0}'
  113. print(fmt.format(header, sep=sep, width=width))
  114. if bottom and not inline:
  115. print(sep * width)
  116. class SaltTestingParser(optparse.OptionParser):
  117. support_docker_execution = False
  118. support_destructive_tests_selection = False
  119. support_expensive_tests_selection = False
  120. source_code_basedir = None
  121. _known_interpreters = {
  122. 'salttest/arch': 'python2',
  123. 'salttest/centos-5': 'python2.6',
  124. 'salttest/centos-6': 'python2.6',
  125. 'salttest/debian-7': 'python2.7',
  126. 'salttest/opensuse-12.3': 'python2.7',
  127. 'salttest/ubuntu-12.04': 'python2.7',
  128. 'salttest/ubuntu-12.10': 'python2.7',
  129. 'salttest/ubuntu-13.04': 'python2.7',
  130. 'salttest/ubuntu-13.10': 'python2.7',
  131. 'salttest/py3': 'python3'
  132. }
  133. def __init__(self, testsuite_directory, *args, **kwargs):
  134. if kwargs.pop('html_output_from_env', None) is not None or \
  135. kwargs.pop('html_output_dir', None) is not None:
  136. warnings.warn(
  137. 'The unit tests HTML support was removed from {0}. Please '
  138. 'stop passing \'html_output_dir\' or \'html_output_from_env\' '
  139. 'as arguments to {0}'.format(self.__class__.__name__),
  140. category=DeprecationWarning,
  141. stacklevel=2
  142. )
  143. # Get XML output settings
  144. xml_output_dir_env_var = kwargs.pop(
  145. 'xml_output_from_env',
  146. 'XML_TESTS_OUTPUT_DIR'
  147. )
  148. xml_output_dir = kwargs.pop('xml_output_dir', None)
  149. if xml_output_dir_env_var in os.environ:
  150. xml_output_dir = os.environ.get(xml_output_dir_env_var)
  151. if not xml_output_dir:
  152. xml_output_dir = os.path.join(
  153. tempfile.gettempdir() if platform.system() != 'Darwin' else '/tmp',
  154. 'xml-tests-output'
  155. )
  156. self.xml_output_dir = xml_output_dir
  157. # Get the desired logfile to use while running tests
  158. self.tests_logfile = kwargs.pop('tests_logfile', None)
  159. optparse.OptionParser.__init__(self, *args, **kwargs)
  160. self.testsuite_directory = testsuite_directory
  161. self.testsuite_results = []
  162. self.test_selection_group = optparse.OptionGroup(
  163. self,
  164. 'Tests Selection Options',
  165. 'Select which tests are to be executed'
  166. )
  167. if self.support_destructive_tests_selection is True:
  168. self.test_selection_group.add_option(
  169. '--run-destructive',
  170. action='store_true',
  171. default=False,
  172. help=('Run destructive tests. These tests can include adding '
  173. 'or removing users from your system for example. '
  174. 'Default: %default')
  175. )
  176. if self.support_expensive_tests_selection is True:
  177. self.test_selection_group.add_option(
  178. '--run-expensive',
  179. action='store_true',
  180. default=False,
  181. help=('Run expensive tests. Expensive tests are any tests that, '
  182. 'once configured, cost money to run, such as creating or '
  183. 'destroying cloud instances on a cloud provider.')
  184. )
  185. self.test_selection_group.add_option(
  186. '-n',
  187. '--name',
  188. dest='name',
  189. action='append',
  190. default=[],
  191. help=('Specific test name to run. A named test is the module path '
  192. 'relative to the tests directory')
  193. )
  194. self.test_selection_group.add_option(
  195. '--names-file',
  196. dest='names_file',
  197. default=None,
  198. help=('The location of a newline delimited file of test names to '
  199. 'run')
  200. )
  201. self.test_selection_group.add_option(
  202. '--from-filenames',
  203. dest='from_filenames',
  204. action='append',
  205. default=None,
  206. help=('Pass a comma-separated list of file paths, and any '
  207. 'unit/integration test module which corresponds to the '
  208. 'specified file(s) will be run. For example, a path of '
  209. 'salt/modules/git.py would result in unit.modules.test_git '
  210. 'and integration.modules.test_git being run. Absolute paths '
  211. 'are assumed to be files containing relative paths, one per '
  212. 'line. Providing the paths in a file can help get around '
  213. 'shell character limits when the list of files is long.')
  214. )
  215. self.test_selection_group.add_option(
  216. '--filename-map',
  217. dest='filename_map',
  218. default=None,
  219. help=('Path to a YAML file mapping paths/path globs to a list '
  220. 'of test names to run. See tests/filename_map.yml '
  221. 'for example usage (when --from-filenames is used, this '
  222. 'map file will be the default one used).')
  223. )
  224. self.add_option_group(self.test_selection_group)
  225. if self.support_docker_execution is True:
  226. self.docked_selection_group = optparse.OptionGroup(
  227. self,
  228. 'Docked Tests Execution',
  229. 'Run the tests suite under a Docker container. This allows, '
  230. 'for example, to run destructive tests on your machine '
  231. 'without actually breaking it in any way.'
  232. )
  233. self.docked_selection_group.add_option(
  234. '--docked',
  235. default=None,
  236. metavar='CONTAINER',
  237. help='Run the tests suite in the chosen Docker container'
  238. )
  239. self.docked_selection_group.add_option(
  240. '--docked-interpreter',
  241. default=None,
  242. metavar='PYTHON_INTERPRETER',
  243. help='The python binary name to use when calling the tests '
  244. 'suite.'
  245. )
  246. self.docked_selection_group.add_option(
  247. '--docked-skip-delete',
  248. default=False,
  249. action='store_true',
  250. help='Skip docker container deletion on exit. Default: False'
  251. )
  252. self.docked_selection_group.add_option(
  253. '--docked-skip-delete-on-errors',
  254. default=False,
  255. action='store_true',
  256. help='Skip docker container deletion on exit if errors '
  257. 'occurred. Default: False'
  258. )
  259. self.docked_selection_group.add_option(
  260. '--docker-binary',
  261. help='The docker binary on the host system. Default: %default',
  262. default='/usr/bin/docker',
  263. )
  264. self.add_option_group(self.docked_selection_group)
  265. self.output_options_group = optparse.OptionGroup(
  266. self, 'Output Options'
  267. )
  268. self.output_options_group.add_option(
  269. '-F',
  270. '--fail-fast',
  271. dest='failfast',
  272. default=False,
  273. action='store_true',
  274. help='Stop on first failure'
  275. )
  276. self.output_options_group.add_option(
  277. '-v',
  278. '--verbose',
  279. dest='verbosity',
  280. default=1,
  281. action='count',
  282. help='Verbose test runner output'
  283. )
  284. self.output_options_group.add_option(
  285. '--output-columns',
  286. default=PNUM,
  287. type=int,
  288. help='Number of maximum columns to use on the output'
  289. )
  290. self.output_options_group.add_option(
  291. '--tests-logfile',
  292. default=self.tests_logfile,
  293. help='The path to the tests suite logging logfile'
  294. )
  295. if self.xml_output_dir is not None:
  296. self.output_options_group.add_option(
  297. '-x',
  298. '--xml',
  299. '--xml-out',
  300. dest='xml_out',
  301. default=False,
  302. help='XML test runner output(Output directory: {0})'.format(
  303. self.xml_output_dir
  304. )
  305. )
  306. self.output_options_group.add_option(
  307. '--no-report',
  308. default=False,
  309. action='store_true',
  310. help='Do NOT show the overall tests result'
  311. )
  312. self.add_option_group(self.output_options_group)
  313. self.fs_cleanup_options_group = optparse.OptionGroup(
  314. self, 'File system cleanup Options'
  315. )
  316. self.fs_cleanup_options_group.add_option(
  317. '--clean',
  318. dest='clean',
  319. default=True,
  320. action='store_true',
  321. help=('Clean up test environment before and after running the '
  322. 'tests suite (default behaviour)')
  323. )
  324. self.fs_cleanup_options_group.add_option(
  325. '--no-clean',
  326. dest='clean',
  327. action='store_false',
  328. help=('Don\'t clean up test environment before and after the '
  329. 'tests suite execution (speed up test process)')
  330. )
  331. self.add_option_group(self.fs_cleanup_options_group)
  332. self.setup_additional_options()
  333. @staticmethod
  334. def _expand_paths(paths):
  335. '''
  336. Expand any comma-separated lists of paths, and return a set of all
  337. paths to ensure there are no duplicates.
  338. '''
  339. ret = set()
  340. for path in paths:
  341. for item in [x.strip() for x in path.split(',')]:
  342. if not item:
  343. continue
  344. elif os.path.isabs(item):
  345. try:
  346. with salt.utils.files.fopen(item, 'rb') as fp_:
  347. for line in fp_:
  348. line = salt.utils.stringutils.to_unicode(line.strip())
  349. if os.path.isabs(line):
  350. log.warning(
  351. 'Invalid absolute path %s in %s, '
  352. 'ignoring', line, item
  353. )
  354. else:
  355. ret.add(line)
  356. except (IOError, OSError) as exc:
  357. log.error('Failed to read from %s: %s', item, exc)
  358. else:
  359. ret.add(item)
  360. return ret
  361. @property
  362. def _test_mods(self):
  363. '''
  364. Use the test_mods generator to get all of the test module names, and
  365. then store them in a set so that further references to this attribute
  366. will not need to re-walk the test dir.
  367. '''
  368. try:
  369. return self.__test_mods
  370. except AttributeError:
  371. self.__test_mods = set(tests.support.paths.test_mods())
  372. return self.__test_mods
  373. def _map_files(self, files):
  374. '''
  375. Map the passed paths to test modules, returning a set of the mapped
  376. module names.
  377. '''
  378. ret = set()
  379. if self.options.filename_map is not None:
  380. try:
  381. with salt.utils.files.fopen(self.options.filename_map) as fp_:
  382. filename_map = salt.utils.yaml.safe_load(fp_)
  383. except Exception as exc:
  384. raise RuntimeError(
  385. 'Failed to load filename map: {0}'.format(exc)
  386. )
  387. else:
  388. filename_map = {}
  389. def _add(comps):
  390. '''
  391. Helper to add unit and integration tests matching a given mod path
  392. '''
  393. mod_relname = '.'.join(comps)
  394. ret.update(
  395. x for x in
  396. ['.'.join(('unit', mod_relname)),
  397. '.'.join(('integration', mod_relname)),
  398. '.'.join(('multimaster', mod_relname))]
  399. if x in self._test_mods
  400. )
  401. # First, try a path match
  402. for path in files:
  403. match = re.match(r'^(salt/|tests/(unit|integration|multimaster)/)(.+\.py)$', path)
  404. if match:
  405. comps = match.group(3).split('/')
  406. # Find matches for a source file
  407. if match.group(1) == 'salt/':
  408. if comps[-1] == '__init__.py':
  409. comps.pop(-1)
  410. comps[-1] = 'test_' + comps[-1]
  411. else:
  412. comps[-1] = 'test_{0}'.format(comps[-1][:-3])
  413. # Direct name matches
  414. _add(comps)
  415. # State matches for execution modules of the same name
  416. # (e.g. unit.states.test_archive if
  417. # unit.modules.test_archive is being run)
  418. try:
  419. if comps[-2] == 'modules':
  420. comps[-2] = 'states'
  421. _add(comps)
  422. except IndexError:
  423. # Not an execution module. This is either directly in
  424. # the salt/ directory, or salt/something/__init__.py
  425. pass
  426. # Make sure to run a test module if it's been modified
  427. elif match.group(1).startswith('tests/'):
  428. comps.insert(0, match.group(2))
  429. if fnmatch.fnmatch(comps[-1], 'test_*.py'):
  430. comps[-1] = comps[-1][:-3]
  431. test_name = '.'.join(comps)
  432. if test_name in self._test_mods:
  433. ret.add(test_name)
  434. # Next, try the filename_map
  435. for path_expr in filename_map:
  436. for filename in files:
  437. if salt.utils.stringutils.expr_match(filename, path_expr):
  438. ret.update(filename_map[path_expr])
  439. break
  440. if any(x.startswith('integration.proxy.') for x in ret):
  441. # Ensure that the salt-proxy daemon is started for these tests.
  442. self.options.proxy = True
  443. if any(x.startswith('integration.ssh.') for x in ret):
  444. # Ensure that an ssh daemon is started for these tests.
  445. self.options.ssh = True
  446. return ret
  447. def parse_args(self, args=None, values=None):
  448. self.options, self.args = optparse.OptionParser.parse_args(self, args, values)
  449. file_names = []
  450. if self.options.names_file:
  451. with open(self.options.names_file, 'rb') as fp_: # pylint: disable=resource-leakage
  452. for line in fp_.readlines():
  453. if six.PY2:
  454. file_names.append(line.strip())
  455. else:
  456. file_names.append(
  457. line.decode(__salt_system_encoding__).strip())
  458. if self.args:
  459. for fpath in self.args:
  460. if os.path.isfile(fpath) and \
  461. fpath.endswith('.py') and \
  462. os.path.basename(fpath).startswith('test_'):
  463. if fpath in file_names:
  464. self.options.name.append(fpath)
  465. continue
  466. self.exit(status=1, msg='\'{}\' is not a valid test module\n'.format(fpath))
  467. if self.options.from_filenames is not None:
  468. self.options.from_filenames = self._expand_paths(self.options.from_filenames)
  469. # Locate the default map file if one was not passed
  470. if self.options.filename_map is None:
  471. self.options.filename_map = salt.utils.path.join(
  472. tests.support.paths.TESTS_DIR,
  473. 'filename_map.yml'
  474. )
  475. self.options.name.extend(self._map_files(self.options.from_filenames))
  476. if self.options.name and file_names:
  477. self.options.name = list(set(self.options.name).intersection(file_names))
  478. elif file_names:
  479. self.options.name = file_names
  480. print_header(u'', inline=True, width=self.options.output_columns)
  481. self.pre_execution_cleanup()
  482. if self.support_docker_execution and self.options.docked is not None:
  483. if self.source_code_basedir is None:
  484. raise RuntimeError(
  485. 'You need to define the \'source_code_basedir\' attribute '
  486. 'in \'{0}\'.'.format(self.__class__.__name__)
  487. )
  488. if '/' not in self.options.docked:
  489. self.options.docked = 'salttest/{0}'.format(
  490. self.options.docked
  491. )
  492. if self.options.docked_interpreter is None:
  493. self.options.docked_interpreter = self._known_interpreters.get(
  494. self.options.docked, 'python'
  495. )
  496. # No more processing should be done. We'll exit with the return
  497. # code we get from the docker container execution
  498. self.exit(self.run_suite_in_docker())
  499. # Validate options after checking that we're not goint to execute the
  500. # tests suite under a docker container
  501. self._validate_options()
  502. print(' * Current Directory: {0}'.format(os.getcwd()))
  503. print(' * Test suite is running under PID {0}'.format(os.getpid()))
  504. self._setup_logging()
  505. try:
  506. return (self.options, self.args)
  507. finally:
  508. print_header(u'', inline=True, width=self.options.output_columns)
  509. def setup_additional_options(self):
  510. '''
  511. Subclasses should add additional options in this overridden method
  512. '''
  513. def _validate_options(self):
  514. '''
  515. Validate the default available options
  516. '''
  517. if self.xml_output_dir is not None and self.options.xml_out and HAS_XMLRUNNER is False:
  518. self.error(
  519. '\'--xml\' is not available. The xmlrunner library is not '
  520. 'installed.'
  521. )
  522. if self.options.xml_out:
  523. # Override any environment setting with the passed value
  524. self.xml_output_dir = self.options.xml_out
  525. if self.xml_output_dir is not None and self.options.xml_out:
  526. if not os.path.isdir(self.xml_output_dir):
  527. os.makedirs(self.xml_output_dir)
  528. os.environ['TESTS_XML_OUTPUT_DIR'] = self.xml_output_dir
  529. print(
  530. ' * Generated unit test XML reports will be stored '
  531. 'at {0!r}'.format(self.xml_output_dir)
  532. )
  533. self.validate_options()
  534. if self.support_destructive_tests_selection:
  535. # Set the required environment variable in order to know if
  536. # destructive tests should be executed or not.
  537. os.environ['DESTRUCTIVE_TESTS'] = str(self.options.run_destructive)
  538. if self.support_expensive_tests_selection:
  539. # Set the required environment variable in order to know if
  540. # expensive tests should be executed or not.
  541. os.environ['EXPENSIVE_TESTS'] = str(self.options.run_expensive)
  542. def validate_options(self):
  543. '''
  544. Validate the provided options. Override this method to run your own
  545. validation procedures.
  546. '''
  547. def _setup_logging(self):
  548. '''
  549. Setup python's logging system to work with/for the tests suite
  550. '''
  551. # Setup tests logging
  552. formatter = logging.Formatter(
  553. '%(asctime)s,%(msecs)03.0f [%(name)-5s:%(lineno)-4d]'
  554. '[%(levelname)-8s] %(message)s',
  555. datefmt='%H:%M:%S'
  556. )
  557. if not hasattr(logging, 'TRACE'):
  558. logging.TRACE = 5
  559. logging.addLevelName(logging.TRACE, 'TRACE')
  560. if not hasattr(logging, 'GARBAGE'):
  561. logging.GARBAGE = 1
  562. logging.addLevelName(logging.GARBAGE, 'GARBAGE')
  563. # Default logging level: ERROR
  564. logging.root.setLevel(logging.NOTSET)
  565. log_levels_to_evaluate = [
  566. logging.ERROR, # Default log level
  567. ]
  568. if self.options.tests_logfile:
  569. filehandler = logging.FileHandler(
  570. mode='w', # Not preserved between re-runs
  571. filename=self.options.tests_logfile,
  572. encoding='utf-8',
  573. )
  574. # The logs of the file are the most verbose possible
  575. filehandler.setLevel(logging.DEBUG)
  576. filehandler.setFormatter(formatter)
  577. logging.root.addHandler(filehandler)
  578. log_levels_to_evaluate.append(logging.DEBUG)
  579. print(' * Logging tests on {0}'.format(self.options.tests_logfile))
  580. # With greater verbosity we can also log to the console
  581. if self.options.verbosity >= 2:
  582. consolehandler = logging.StreamHandler(sys.stderr)
  583. consolehandler.setFormatter(formatter)
  584. if self.options.verbosity >= 6: # -vvvvv
  585. logging_level = logging.GARBAGE
  586. elif self.options.verbosity == 5: # -vvvv
  587. logging_level = logging.TRACE
  588. elif self.options.verbosity == 4: # -vvv
  589. logging_level = logging.DEBUG
  590. elif self.options.verbosity == 3: # -vv
  591. logging_level = logging.INFO
  592. else:
  593. logging_level = logging.ERROR
  594. log_levels_to_evaluate.append(logging_level)
  595. os.environ['TESTS_LOG_LEVEL'] = str(self.options.verbosity) # future lint: disable=blacklisted-function
  596. consolehandler.setLevel(logging_level)
  597. logging.root.addHandler(consolehandler)
  598. log.info('Runtests logging has been setup')
  599. os.environ['TESTS_MIN_LOG_LEVEL_NAME'] = logging.getLevelName(min(log_levels_to_evaluate))
  600. def pre_execution_cleanup(self):
  601. '''
  602. Run any initial clean up operations. If sub-classed, don't forget to
  603. call SaltTestingParser.pre_execution_cleanup(self) from the overridden
  604. method.
  605. '''
  606. if self.options.clean is True:
  607. for path in (self.xml_output_dir,):
  608. if path is None:
  609. continue
  610. if os.path.isdir(path):
  611. shutil.rmtree(path)
  612. def run_suite(self, path, display_name, suffix='test_*.py',
  613. load_from_name=False, additional_test_dirs=None, failfast=False):
  614. '''
  615. Execute a unit test suite
  616. '''
  617. loaded_custom = False
  618. loader = TestLoader()
  619. try:
  620. if load_from_name:
  621. tests = loader.loadTestsFromName(display_name)
  622. else:
  623. if additional_test_dirs is None or self.testsuite_directory.startswith(path):
  624. tests = loader.discover(path, suffix, self.testsuite_directory)
  625. else:
  626. tests = loader.discover(path, suffix)
  627. loaded_custom = True
  628. except (AttributeError, ImportError):
  629. print('Could not locate test \'{0}\'. Exiting.'.format(display_name))
  630. sys.exit(1)
  631. if additional_test_dirs and not loaded_custom:
  632. for test_dir in additional_test_dirs:
  633. additional_tests = loader.discover(test_dir, suffix, test_dir)
  634. tests.addTests(additional_tests)
  635. header = '{0} Tests'.format(display_name)
  636. print_header('Starting {0}'.format(header),
  637. width=self.options.output_columns)
  638. if self.options.xml_out:
  639. runner = XMLTestRunner(
  640. stream=sys.stdout,
  641. output=self.xml_output_dir,
  642. verbosity=self.options.verbosity,
  643. failfast=failfast,
  644. ).run(tests)
  645. else:
  646. runner = TextTestRunner(
  647. stream=sys.stdout,
  648. verbosity=self.options.verbosity,
  649. failfast=failfast
  650. ).run(tests)
  651. errors = []
  652. skipped = []
  653. failures = []
  654. for testcase, reason in runner.errors:
  655. errors.append(TestResult(testcase.id(), reason))
  656. for testcase, reason in runner.skipped:
  657. skipped.append(TestResult(testcase.id(), reason))
  658. for testcase, reason in runner.failures:
  659. failures.append(TestResult(testcase.id(), reason))
  660. self.testsuite_results.append(
  661. TestsuiteResult(header,
  662. errors,
  663. skipped,
  664. failures,
  665. runner.testsRun - len(errors + skipped + failures))
  666. )
  667. success = runner.wasSuccessful()
  668. del loader
  669. del runner
  670. return success
  671. def print_overall_testsuite_report(self):
  672. '''
  673. Print a nicely formatted report about the test suite results
  674. '''
  675. print()
  676. print_header(
  677. u' Overall Tests Report ', sep=u'=', centered=True, inline=True,
  678. width=self.options.output_columns
  679. )
  680. failures = errors = skipped = passed = 0
  681. no_problems_found = True
  682. for results in self.testsuite_results:
  683. failures += len(results.failures)
  684. errors += len(results.errors)
  685. skipped += len(results.skipped)
  686. passed += results.passed
  687. if not results.failures and not results.errors and not results.skipped:
  688. continue
  689. no_problems_found = False
  690. print_header(
  691. u'*** {0} '.format(results.header), sep=u'*', inline=True,
  692. width=self.options.output_columns
  693. )
  694. if results.skipped:
  695. print_header(
  696. u' -------- Skipped Tests ', sep='-', inline=True,
  697. width=self.options.output_columns
  698. )
  699. maxlen = len(
  700. max([testcase.id for testcase in results.skipped], key=len)
  701. )
  702. fmt = u' -> {0: <{maxlen}} -> {1}'
  703. for testcase in results.skipped:
  704. print(fmt.format(testcase.id, testcase.reason, maxlen=maxlen))
  705. print_header(u' ', sep='-', inline=True,
  706. width=self.options.output_columns)
  707. if results.errors:
  708. print_header(
  709. u' -------- Tests with Errors ', sep='-', inline=True,
  710. width=self.options.output_columns
  711. )
  712. for testcase in results.errors:
  713. print_header(
  714. u' -> {0} '.format(testcase.id),
  715. sep=u'.', inline=True,
  716. width=self.options.output_columns
  717. )
  718. for line in testcase.reason.rstrip().splitlines():
  719. print(' {0}'.format(line.rstrip()))
  720. print_header(u' ', sep=u'.', inline=True,
  721. width=self.options.output_columns)
  722. print_header(u' ', sep='-', inline=True,
  723. width=self.options.output_columns)
  724. if results.failures:
  725. print_header(
  726. u' -------- Failed Tests ', sep='-', inline=True,
  727. width=self.options.output_columns
  728. )
  729. for testcase in results.failures:
  730. print_header(
  731. u' -> {0} '.format(testcase.id),
  732. sep=u'.', inline=True,
  733. width=self.options.output_columns
  734. )
  735. for line in testcase.reason.rstrip().splitlines():
  736. print(' {0}'.format(line.rstrip()))
  737. print_header(u' ', sep=u'.', inline=True,
  738. width=self.options.output_columns)
  739. print_header(u' ', sep='-', inline=True,
  740. width=self.options.output_columns)
  741. if no_problems_found:
  742. print_header(
  743. u'*** No Problems Found While Running Tests ',
  744. sep=u'*', inline=True, width=self.options.output_columns
  745. )
  746. print_header(u'', sep=u'=', inline=True,
  747. width=self.options.output_columns)
  748. total = sum([passed, skipped, errors, failures])
  749. print(
  750. '{0} (total={1}, skipped={2}, passed={3}, failures={4}, '
  751. 'errors={5}) '.format(
  752. (errors or failures) and 'FAILED' or 'OK',
  753. total, skipped, passed, failures, errors
  754. )
  755. )
  756. print_header(
  757. ' Overall Tests Report ', sep='=', centered=True, inline=True,
  758. width=self.options.output_columns
  759. )
  760. def post_execution_cleanup(self):
  761. '''
  762. Run any final clean-up operations. If sub-classed, don't forget to
  763. call SaltTestingParser.post_execution_cleanup(self) from the overridden
  764. method.
  765. '''
  766. def finalize(self, exit_code=0):
  767. '''
  768. Run the finalization procedures. Show report, clean-up file-system, etc
  769. '''
  770. # Collect any child processes still laying around
  771. children = helpers.collect_child_processes(os.getpid())
  772. if self.options.no_report is False:
  773. self.print_overall_testsuite_report()
  774. self.post_execution_cleanup()
  775. # Brute force approach to terminate this process and its children
  776. if children:
  777. log.info('Terminating test suite child processes: %s', children)
  778. helpers.terminate_process(children=children, kill_children=True)
  779. children = helpers.collect_child_processes(os.getpid())
  780. if children:
  781. log.info('Second run at terminating test suite child processes: %s', children)
  782. helpers.terminate_process(children=children, kill_children=True)
  783. exit_msg = 'Test suite execution finalized with exit code: {}'.format(exit_code)
  784. log.info(exit_msg)
  785. self.exit(status=exit_code, msg=exit_msg + '\n')
  786. def run_suite_in_docker(self):
  787. '''
  788. Run the tests suite in a Docker container
  789. '''
  790. def stop_running_docked_container(cid, signum=None, frame=None):
  791. # Allow some time for the container to stop if it's going to be
  792. # stopped by docker or any signals docker might have received
  793. time.sleep(0.5)
  794. print_header('', inline=True, width=self.options.output_columns)
  795. # Let's check if, in fact, the container is stopped
  796. scode_call = subprocess.Popen(
  797. [self.options.docker_binary, 'inspect', '--format={{.State.Running}}', cid],
  798. env=os.environ.copy(),
  799. close_fds=True,
  800. stdout=subprocess.PIPE
  801. )
  802. scode_call.wait()
  803. parsed_scode = scode_call.stdout.read().strip()
  804. if six.PY3:
  805. parsed_scode = parsed_scode.decode(__salt_system_encoding__)
  806. if parsed_scode != 'false':
  807. # If the container is still running, let's make sure it
  808. # properly stops
  809. sys.stdout.write(' * Making sure the container is stopped. CID: ')
  810. sys.stdout.flush()
  811. stop_call = subprocess.Popen(
  812. [self.options.docker_binary, 'stop', '--time=15', cid],
  813. env=os.environ.copy(),
  814. close_fds=True,
  815. stdout=subprocess.PIPE
  816. )
  817. stop_call.wait()
  818. output = stop_call.stdout.read().strip()
  819. if six.PY3:
  820. output = output.decode(__salt_system_encoding__)
  821. print(output)
  822. sys.stdout.flush()
  823. time.sleep(0.5)
  824. # Let's get the container's exit code. We can't trust on Popen's
  825. # returncode because it's not reporting the proper one? Still
  826. # haven't narrowed it down why.
  827. sys.stdout.write(' * Container exit code: ')
  828. sys.stdout.flush()
  829. rcode_call = subprocess.Popen(
  830. [self.options.docker_binary, 'inspect', '--format={{.State.ExitCode}}', cid],
  831. env=os.environ.copy(),
  832. close_fds=True,
  833. stdout=subprocess.PIPE
  834. )
  835. rcode_call.wait()
  836. parsed_rcode = rcode_call.stdout.read().strip()
  837. if six.PY3:
  838. parsed_rcode = parsed_rcode.decode(__salt_system_encoding__)
  839. try:
  840. returncode = int(parsed_rcode)
  841. except ValueError:
  842. returncode = -1
  843. print(parsed_rcode)
  844. sys.stdout.flush()
  845. if self.options.docked_skip_delete is False and \
  846. (self.options.docked_skip_delete_on_errors is False or
  847. (self.options.docked_skip_delete_on_error and returncode == 0)):
  848. sys.stdout.write(' * Cleaning Up Temporary Docker Container. CID: ')
  849. sys.stdout.flush()
  850. cleanup_call = subprocess.Popen(
  851. [self.options.docker_binary, 'rm', cid],
  852. env=os.environ.copy(),
  853. close_fds=True,
  854. stdout=subprocess.PIPE
  855. )
  856. cleanup_call.wait()
  857. output = cleanup_call.stdout.read().strip()
  858. if six.PY3:
  859. output = output.decode(__salt_system_encoding__)
  860. print(output)
  861. if 'DOCKER_CIDFILE' not in os.environ:
  862. # The CID file was not created "from the outside", so delete it
  863. os.unlink(cidfile)
  864. print_header('', inline=True, width=self.options.output_columns)
  865. # Finally, EXIT!
  866. sys.exit(returncode)
  867. # Let's start the Docker container and run the tests suite there
  868. if '/' not in self.options.docked:
  869. container = 'salttest/{0}'.format(self.options.docked)
  870. else:
  871. container = self.options.docked
  872. calling_args = [self.options.docked_interpreter,
  873. '/salt-source/tests/runtests.py']
  874. for option in self._get_all_options():
  875. if option.dest is None:
  876. # For example --version
  877. continue
  878. if option.dest and (option.dest in ('verbosity',) or
  879. option.dest.startswith('docked')):
  880. # We don't need to pass any docker related arguments inside the
  881. # container, and verbose will be handled bellow
  882. continue
  883. default = self.defaults.get(option.dest)
  884. value = getattr(self.options, option.dest, default)
  885. if default == value:
  886. # This is the default value, no need to pass the option to the
  887. # parser
  888. continue
  889. if option.action.startswith('store_'):
  890. calling_args.append(option.get_opt_string())
  891. elif option.action == 'append':
  892. for val in value is not None and value or default:
  893. calling_args.extend([option.get_opt_string(), str(val)])
  894. elif option.action == 'count':
  895. calling_args.extend([option.get_opt_string()] * value)
  896. else:
  897. calling_args.extend(
  898. [option.get_opt_string(),
  899. str(value is not None and value or default)]
  900. )
  901. if not self.options.run_destructive:
  902. calling_args.append('--run-destructive')
  903. if self.options.verbosity > 1:
  904. calling_args.append(
  905. '-{0}'.format('v' * (self.options.verbosity - 1))
  906. )
  907. sys.stdout.write(' * Docker command: {0}\n'.format(' '.join(calling_args)))
  908. sys.stdout.write(' * Running the tests suite under the {0!r} docker '
  909. 'container. CID: '.format(container))
  910. sys.stdout.flush()
  911. cidfile = os.environ.get(
  912. 'DOCKER_CIDFILE',
  913. tempfile.mktemp(prefix='docked-testsuite-', suffix='.cid')
  914. )
  915. call = subprocess.Popen(
  916. [self.options.docker_binary,
  917. 'run',
  918. # '--rm=true', Do not remove the container automatically, we need
  919. # to get information back, even for stopped containers
  920. '--tty',
  921. '--interactive',
  922. '-v',
  923. '{0}:/salt-source'.format(self.source_code_basedir),
  924. '-w',
  925. '/salt-source',
  926. '-e',
  927. 'SHELL=/bin/sh',
  928. '-e',
  929. 'COLUMNS={0}'.format(WIDTH),
  930. '-e',
  931. 'LINES={0}'.format(HEIGHT),
  932. '--cidfile={0}'.format(cidfile),
  933. container,
  934. # We need to pass the runtests.py arguments as a single string so
  935. # that the start-me-up.sh script can handle them properly
  936. ' '.join(calling_args),
  937. ],
  938. env=os.environ.copy(),
  939. close_fds=True,
  940. )
  941. cid = None
  942. cid_printed = terminating = exiting = False
  943. signal_handler_installed = signalled = False
  944. time.sleep(0.25)
  945. while True:
  946. try:
  947. time.sleep(0.15)
  948. if cid_printed is False:
  949. with open(cidfile) as cidfile_fd: # pylint: disable=resource-leakage
  950. cid = cidfile_fd.read()
  951. if cid:
  952. print(cid)
  953. sys.stdout.flush()
  954. cid_printed = True
  955. # Install our signal handler to properly shutdown
  956. # the docker container
  957. for sig in (signal.SIGTERM, signal.SIGINT,
  958. signal.SIGHUP, signal.SIGQUIT):
  959. signal.signal(
  960. sig,
  961. partial(stop_running_docked_container, cid)
  962. )
  963. signal_handler_installed = True
  964. if exiting:
  965. break
  966. elif terminating and not exiting:
  967. exiting = True
  968. call.kill()
  969. break
  970. elif signalled and not terminating:
  971. terminating = True
  972. call.terminate()
  973. else:
  974. call.poll()
  975. if call.returncode is not None:
  976. # Finished
  977. break
  978. except KeyboardInterrupt:
  979. print('Caught CTRL-C, exiting...')
  980. signalled = True
  981. call.send_signal(signal.SIGINT)
  982. call.wait()
  983. time.sleep(0.25)
  984. # Finish up
  985. if signal_handler_installed:
  986. stop_running_docked_container(
  987. cid,
  988. signum=(signal.SIGINT if signalled else WEIRD_SIGNAL_NUM)
  989. )
  990. else:
  991. sys.exit(call.returncode)
  992. class SaltTestcaseParser(SaltTestingParser):
  993. '''
  994. Option parser to run one or more ``unittest.case.TestCase``, ie, no
  995. discovery involved.
  996. '''
  997. def __init__(self, *args, **kwargs):
  998. SaltTestingParser.__init__(self, None, *args, **kwargs)
  999. self.usage = '%prog [options]'
  1000. self.option_groups.remove(self.test_selection_group)
  1001. if self.has_option('--xml-out'):
  1002. self.remove_option('--xml-out')
  1003. def get_prog_name(self):
  1004. return '{0} {1}'.format(sys.executable.split(os.sep)[-1], sys.argv[0])
  1005. def run_testcase(self, testcase):
  1006. '''
  1007. Run one or more ``unittest.case.TestCase``
  1008. '''
  1009. header = ''
  1010. loader = TestLoader()
  1011. if isinstance(testcase, list):
  1012. for case in testcase:
  1013. tests = loader.loadTestsFromTestCase(case)
  1014. else:
  1015. tests = loader.loadTestsFromTestCase(testcase)
  1016. if not isinstance(testcase, list):
  1017. header = '{0} Tests'.format(testcase.__name__)
  1018. print_header('Starting {0}'.format(header),
  1019. width=self.options.output_columns)
  1020. runner = TextTestRunner(
  1021. verbosity=self.options.verbosity,
  1022. failfast=self.options.failfast,
  1023. ).run(tests)
  1024. self.testsuite_results.append((header, runner))
  1025. return runner.wasSuccessful()