1
0

__init__.py 45 KB

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