__init__.py 45 KB

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