conftest.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. """
  2. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  3. tests.conftest
  4. ~~~~~~~~~~~~~~
  5. Prepare py.test for our test suite
  6. """
  7. # pylint: disable=wrong-import-order,wrong-import-position,3rd-party-local-module-not-gated
  8. # pylint: disable=redefined-outer-name,invalid-name,3rd-party-module-not-gated
  9. import logging
  10. import os
  11. import pathlib
  12. import pprint
  13. import re
  14. import shutil
  15. import stat
  16. import sys
  17. import textwrap
  18. from functools import partial, wraps
  19. from unittest import TestCase # pylint: disable=blacklisted-module
  20. import _pytest.logging
  21. import _pytest.skipping
  22. import psutil
  23. import pytest
  24. import salt.config
  25. import salt.loader
  26. import salt.log.mixins
  27. import salt.log.setup
  28. import salt.utils.files
  29. import salt.utils.path
  30. import salt.utils.platform
  31. import salt.utils.win_functions
  32. import saltfactories.utils.compat
  33. from salt.serializers import yaml
  34. from salt.utils.immutabletypes import freeze
  35. from tests.support.helpers import (
  36. PRE_PYTEST_SKIP_OR_NOT,
  37. PRE_PYTEST_SKIP_REASON,
  38. get_virtualenv_binary_path,
  39. )
  40. from tests.support.pytest.helpers import * # pylint: disable=unused-wildcard-import
  41. from tests.support.runtests import RUNTIME_VARS
  42. from tests.support.sminion import check_required_sminion_attributes, create_sminion
  43. TESTS_DIR = pathlib.Path(__file__).resolve().parent
  44. PYTESTS_DIR = TESTS_DIR / "pytests"
  45. CODE_DIR = TESTS_DIR.parent
  46. # Change to code checkout directory
  47. os.chdir(str(CODE_DIR))
  48. # Make sure the current directory is the first item in sys.path
  49. if str(CODE_DIR) in sys.path:
  50. sys.path.remove(str(CODE_DIR))
  51. sys.path.insert(0, str(CODE_DIR))
  52. # Coverage
  53. if "COVERAGE_PROCESS_START" in os.environ:
  54. MAYBE_RUN_COVERAGE = True
  55. COVERAGERC_FILE = os.environ["COVERAGE_PROCESS_START"]
  56. else:
  57. COVERAGERC_FILE = str(CODE_DIR / ".coveragerc")
  58. MAYBE_RUN_COVERAGE = (
  59. sys.argv[0].endswith("pytest.py") or "_COVERAGE_RCFILE" in os.environ
  60. )
  61. if MAYBE_RUN_COVERAGE:
  62. # Flag coverage to track suprocesses by pointing it to the right .coveragerc file
  63. os.environ["COVERAGE_PROCESS_START"] = str(COVERAGERC_FILE)
  64. # Define the pytest plugins we rely on
  65. pytest_plugins = ["tempdir", "helpers_namespace"]
  66. # Define where not to collect tests from
  67. collect_ignore = ["setup.py"]
  68. # Patch PyTest logging handlers
  69. class LogCaptureHandler(
  70. salt.log.mixins.ExcInfoOnLogLevelFormatMixIn, _pytest.logging.LogCaptureHandler
  71. ):
  72. """
  73. Subclassing PyTest's LogCaptureHandler in order to add the
  74. exc_info_on_loglevel functionality and actually make it a NullHandler,
  75. it's only used to print log messages emmited during tests, which we
  76. have explicitly disabled in pytest.ini
  77. """
  78. _pytest.logging.LogCaptureHandler = LogCaptureHandler
  79. class LiveLoggingStreamHandler(
  80. salt.log.mixins.ExcInfoOnLogLevelFormatMixIn,
  81. _pytest.logging._LiveLoggingStreamHandler,
  82. ):
  83. """
  84. Subclassing PyTest's LiveLoggingStreamHandler in order to add the
  85. exc_info_on_loglevel functionality.
  86. """
  87. _pytest.logging._LiveLoggingStreamHandler = LiveLoggingStreamHandler
  88. # Reset logging root handlers
  89. for handler in logging.root.handlers[:]:
  90. logging.root.removeHandler(handler)
  91. # Reset the root logger to its default level(because salt changed it)
  92. logging.root.setLevel(logging.WARNING)
  93. log = logging.getLogger("salt.testsuite")
  94. # ----- PyTest Tempdir Plugin Hooks --------------------------------------------------------------------------------->
  95. def pytest_tempdir_basename():
  96. """
  97. Return the temporary directory basename for the salt test suite.
  98. """
  99. return "salt-tests-tmpdir"
  100. # <---- PyTest Tempdir Plugin Hooks ----------------------------------------------------------------------------------
  101. # ----- CLI Options Setup ------------------------------------------------------------------------------------------->
  102. def pytest_addoption(parser):
  103. """
  104. register argparse-style options and ini-style config values.
  105. """
  106. test_selection_group = parser.getgroup("Tests Selection")
  107. test_selection_group.addoption(
  108. "--from-filenames",
  109. default=None,
  110. help=(
  111. "Pass a comma-separated list of file paths, and any test module which corresponds to the "
  112. "specified file(s) will run. For example, if 'setup.py' was passed, then the corresponding "
  113. "test files defined in 'tests/filename_map.yml' would run. Absolute paths are assumed to be "
  114. "files containing relative paths, one per line. Providing the paths in a file can help get "
  115. "around shell character limits when the list of files is long."
  116. ),
  117. )
  118. # Add deprecated CLI flag until we completely switch to PyTest
  119. test_selection_group.addoption(
  120. "--names-file", default=None, help="Deprecated option"
  121. )
  122. test_selection_group.addoption(
  123. "--transport",
  124. default="zeromq",
  125. choices=("zeromq", "tcp"),
  126. help=(
  127. "Select which transport to run the integration tests with, zeromq or tcp. Default: %default"
  128. ),
  129. )
  130. test_selection_group.addoption(
  131. "--ssh",
  132. "--ssh-tests",
  133. dest="ssh",
  134. action="store_true",
  135. default=False,
  136. help="Run salt-ssh tests. These tests will spin up a temporary "
  137. "SSH server on your machine. In certain environments, this "
  138. "may be insecure! Default: False",
  139. )
  140. test_selection_group.addoption(
  141. "--proxy",
  142. "--proxy-tests",
  143. dest="proxy",
  144. action="store_true",
  145. default=False,
  146. help="Run proxy tests",
  147. )
  148. test_selection_group.addoption(
  149. "--run-slow", action="store_true", default=False, help="Run slow tests.",
  150. )
  151. output_options_group = parser.getgroup("Output Options")
  152. output_options_group.addoption(
  153. "--output-columns",
  154. default=80,
  155. type=int,
  156. help="Number of maximum columns to use on the output",
  157. )
  158. output_options_group.addoption(
  159. "--no-colors",
  160. "--no-colours",
  161. default=False,
  162. action="store_true",
  163. help="Disable colour printing.",
  164. )
  165. # ----- Test Groups --------------------------------------------------------------------------------------------->
  166. # This will allow running the tests in chunks
  167. test_selection_group.addoption(
  168. "--test-group-count",
  169. dest="test-group-count",
  170. type=int,
  171. help="The number of groups to split the tests into",
  172. )
  173. test_selection_group.addoption(
  174. "--test-group",
  175. dest="test-group",
  176. type=int,
  177. help="The group of tests that should be executed",
  178. )
  179. # <---- Test Groups ----------------------------------------------------------------------------------------------
  180. # <---- CLI Options Setup --------------------------------------------------------------------------------------------
  181. # ----- Register Markers -------------------------------------------------------------------------------------------->
  182. @pytest.mark.trylast
  183. def pytest_configure(config):
  184. """
  185. called after command line options have been parsed
  186. and all plugins and initial conftest files been loaded.
  187. """
  188. for dirname in CODE_DIR.iterdir():
  189. if not dirname.is_dir():
  190. continue
  191. if dirname != TESTS_DIR:
  192. config.addinivalue_line("norecursedirs", str(CODE_DIR / dirname))
  193. # Expose the markers we use to pytest CLI
  194. config.addinivalue_line(
  195. "markers",
  196. "requires_salt_modules(*required_module_names): Skip if at least one module is not available.",
  197. )
  198. config.addinivalue_line(
  199. "markers",
  200. "requires_salt_states(*required_state_names): Skip if at least one state module is not available.",
  201. )
  202. config.addinivalue_line(
  203. "markers", "windows_whitelisted: Mark test as whitelisted to run under Windows"
  204. )
  205. config.addinivalue_line(
  206. "markers", "requires_sshd_server: Mark test that require an SSH server running"
  207. )
  208. # Make sure the test suite "knows" this is a pytest test run
  209. RUNTIME_VARS.PYTEST_SESSION = True
  210. # "Flag" the slotTest decorator if we're skipping slow tests or not
  211. os.environ["SLOW_TESTS"] = str(config.getoption("--run-slow"))
  212. # <---- Register Markers ---------------------------------------------------------------------------------------------
  213. # ----- PyTest Tweaks ----------------------------------------------------------------------------------------------->
  214. def set_max_open_files_limits(min_soft=3072, min_hard=4096):
  215. # Get current limits
  216. if salt.utils.platform.is_windows():
  217. import win32file
  218. prev_hard = win32file._getmaxstdio()
  219. prev_soft = 512
  220. else:
  221. import resource
  222. prev_soft, prev_hard = resource.getrlimit(resource.RLIMIT_NOFILE)
  223. # Check minimum required limits
  224. set_limits = False
  225. if prev_soft < min_soft:
  226. soft = min_soft
  227. set_limits = True
  228. else:
  229. soft = prev_soft
  230. if prev_hard < min_hard:
  231. hard = min_hard
  232. set_limits = True
  233. else:
  234. hard = prev_hard
  235. # Increase limits
  236. if set_limits:
  237. log.debug(
  238. " * Max open files settings is too low (soft: %s, hard: %s) for running the tests. "
  239. "Trying to raise the limits to soft: %s, hard: %s",
  240. prev_soft,
  241. prev_hard,
  242. soft,
  243. hard,
  244. )
  245. try:
  246. if salt.utils.platform.is_windows():
  247. hard = 2048 if hard > 2048 else hard
  248. win32file._setmaxstdio(hard)
  249. else:
  250. resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))
  251. except Exception as err: # pylint: disable=broad-except
  252. log.error(
  253. "Failed to raise the max open files settings -> %s. Please issue the following command "
  254. "on your console: 'ulimit -u %s'",
  255. err,
  256. soft,
  257. )
  258. exit(1)
  259. return soft, hard
  260. def pytest_report_header():
  261. soft, hard = set_max_open_files_limits()
  262. return "max open files; soft: {}; hard: {}".format(soft, hard)
  263. def pytest_itemcollected(item):
  264. """We just collected a test item."""
  265. try:
  266. pathlib.Path(item.fspath.strpath).resolve().relative_to(PYTESTS_DIR)
  267. # Test is under tests/pytests
  268. if item.cls and issubclass(item.cls, TestCase):
  269. pytest.fail(
  270. "The tests under {0!r} MUST NOT use unittest's TestCase class or a subclass of it. "
  271. "Please move {1!r} outside of {0!r}".format(
  272. str(PYTESTS_DIR.relative_to(CODE_DIR)), item.nodeid
  273. )
  274. )
  275. except ValueError:
  276. # Test is not under tests/pytests
  277. if not item.cls or (item.cls and not issubclass(item.cls, TestCase)):
  278. pytest.fail(
  279. "The test {!r} appears to be written for pytest but it's not under {!r}. Please move it there.".format(
  280. item.nodeid, str(PYTESTS_DIR.relative_to(CODE_DIR)), pytrace=False
  281. )
  282. )
  283. @pytest.hookimpl(hookwrapper=True, trylast=True)
  284. def pytest_collection_modifyitems(config, items):
  285. """
  286. called after collection has been performed, may filter or re-order
  287. the items in-place.
  288. :param _pytest.main.Session session: the pytest session object
  289. :param _pytest.config.Config config: pytest config object
  290. :param List[_pytest.nodes.Item] items: list of item objects
  291. """
  292. # Let PyTest or other plugins handle the initial collection
  293. yield
  294. groups_collection_modifyitems(config, items)
  295. from_filenames_collection_modifyitems(config, items)
  296. log.warning("Mofifying collected tests to keep track of fixture usage")
  297. for item in items:
  298. for fixture in item.fixturenames:
  299. if fixture not in item._fixtureinfo.name2fixturedefs:
  300. continue
  301. for fixturedef in item._fixtureinfo.name2fixturedefs[fixture]:
  302. if fixturedef.scope != "package":
  303. continue
  304. try:
  305. fixturedef.finish.__wrapped__
  306. except AttributeError:
  307. original_func = fixturedef.finish
  308. def wrapper(func, fixturedef):
  309. @wraps(func)
  310. def wrapped(self, request, nextitem=False):
  311. try:
  312. return self._finished
  313. except AttributeError:
  314. if nextitem:
  315. fpath = pathlib.Path(self.baseid).resolve()
  316. tpath = pathlib.Path(
  317. nextitem.fspath.strpath
  318. ).resolve()
  319. try:
  320. tpath.relative_to(fpath)
  321. # The test module is within the same package that the fixture is
  322. if (
  323. not request.session.shouldfail
  324. and not request.session.shouldstop
  325. ):
  326. log.debug(
  327. "The next test item is still under the fixture package path. "
  328. "Not terminating %s",
  329. self,
  330. )
  331. return
  332. except ValueError:
  333. pass
  334. log.debug("Finish called on %s", self)
  335. try:
  336. return func(request)
  337. except BaseException as exc: # pylint: disable=broad-except
  338. pytest.fail(
  339. "Failed to run finish() on {}: {}".format(
  340. fixturedef, exc
  341. ),
  342. pytrace=True,
  343. )
  344. finally:
  345. self._finished = True
  346. return partial(wrapped, fixturedef)
  347. fixturedef.finish = wrapper(fixturedef.finish, fixturedef)
  348. try:
  349. fixturedef.finish.__wrapped__
  350. except AttributeError:
  351. fixturedef.finish.__wrapped__ = original_func
  352. @pytest.hookimpl(trylast=True, hookwrapper=True)
  353. def pytest_runtest_protocol(item, nextitem):
  354. """
  355. implements the runtest_setup/call/teardown protocol for
  356. the given test item, including capturing exceptions and calling
  357. reporting hooks.
  358. :arg item: test item for which the runtest protocol is performed.
  359. :arg nextitem: the scheduled-to-be-next test item (or None if this
  360. is the end my friend). This argument is passed on to
  361. :py:func:`pytest_runtest_teardown`.
  362. :return boolean: True if no further hook implementations should be invoked.
  363. Stops at first non-None result, see :ref:`firstresult`
  364. """
  365. request = item._request
  366. used_fixture_defs = []
  367. for fixture in item.fixturenames:
  368. if fixture not in item._fixtureinfo.name2fixturedefs:
  369. continue
  370. for fixturedef in reversed(item._fixtureinfo.name2fixturedefs[fixture]):
  371. if fixturedef.scope != "package":
  372. continue
  373. used_fixture_defs.append(fixturedef)
  374. try:
  375. # Run the test
  376. yield
  377. finally:
  378. for fixturedef in used_fixture_defs:
  379. fixturedef.finish(request, nextitem=nextitem)
  380. del request
  381. del used_fixture_defs
  382. # <---- PyTest Tweaks ------------------------------------------------------------------------------------------------
  383. # ----- Test Setup -------------------------------------------------------------------------------------------------->
  384. @pytest.hookimpl(tryfirst=True)
  385. def pytest_runtest_setup(item):
  386. """
  387. Fixtures injection based on markers or test skips based on CLI arguments
  388. """
  389. integration_utils_tests_path = str(TESTS_DIR / "integration" / "utils")
  390. if (
  391. str(item.fspath).startswith(integration_utils_tests_path)
  392. and PRE_PYTEST_SKIP_OR_NOT is True
  393. ):
  394. item._skipped_by_mark = True
  395. pytest.skip(PRE_PYTEST_SKIP_REASON)
  396. if saltfactories.utils.compat.has_unittest_attr(item, "__slow_test__"):
  397. if item.config.getoption("--run-slow") is False:
  398. item._skipped_by_mark = True
  399. pytest.skip("Slow tests are disabled!")
  400. requires_sshd_server_marker = item.get_closest_marker("requires_sshd_server")
  401. if requires_sshd_server_marker is not None:
  402. if not item.config.getoption("--ssh-tests"):
  403. item._skipped_by_mark = True
  404. pytest.skip("SSH tests are disabled, pass '--ssh-tests' to enable them.")
  405. item.fixturenames.append("sshd_server")
  406. requires_salt_modules_marker = item.get_closest_marker("requires_salt_modules")
  407. if requires_salt_modules_marker is not None:
  408. required_salt_modules = requires_salt_modules_marker.args
  409. if len(required_salt_modules) == 1 and isinstance(
  410. required_salt_modules[0], (list, tuple, set)
  411. ):
  412. required_salt_modules = required_salt_modules[0]
  413. required_salt_modules = set(required_salt_modules)
  414. not_available_modules = check_required_sminion_attributes(
  415. "functions", required_salt_modules
  416. )
  417. if not_available_modules:
  418. item._skipped_by_mark = True
  419. if len(not_available_modules) == 1:
  420. pytest.skip(
  421. "Salt module '{}' is not available".format(*not_available_modules)
  422. )
  423. pytest.skip(
  424. "Salt modules not available: {}".format(
  425. ", ".join(not_available_modules)
  426. )
  427. )
  428. requires_salt_states_marker = item.get_closest_marker("requires_salt_states")
  429. if requires_salt_states_marker is not None:
  430. required_salt_states = requires_salt_states_marker.args
  431. if len(required_salt_states) == 1 and isinstance(
  432. required_salt_states[0], (list, tuple, set)
  433. ):
  434. required_salt_states = required_salt_states[0]
  435. required_salt_states = set(required_salt_states)
  436. not_available_states = check_required_sminion_attributes(
  437. "states", required_salt_states
  438. )
  439. if not_available_states:
  440. item._skipped_by_mark = True
  441. if len(not_available_states) == 1:
  442. pytest.skip(
  443. "Salt state module '{}' is not available".format(
  444. *not_available_states
  445. )
  446. )
  447. pytest.skip(
  448. "Salt state modules not available: {}".format(
  449. ", ".join(not_available_states)
  450. )
  451. )
  452. if salt.utils.platform.is_windows():
  453. unit_tests_paths = (
  454. str(TESTS_DIR / "unit"),
  455. str(PYTESTS_DIR / "unit"),
  456. )
  457. if not str(pathlib.Path(item.fspath).resolve()).startswith(unit_tests_paths):
  458. # Unit tests are whitelisted on windows by default, so, we're only
  459. # after all other tests
  460. windows_whitelisted_marker = item.get_closest_marker("windows_whitelisted")
  461. if windows_whitelisted_marker is None:
  462. item._skipped_by_mark = True
  463. pytest.skip("Test is not whitelisted for Windows")
  464. # <---- Test Setup ---------------------------------------------------------------------------------------------------
  465. # ----- Test Groups Selection --------------------------------------------------------------------------------------->
  466. def get_group_size_and_start(total_items, total_groups, group_id):
  467. """
  468. Calculate group size and start index.
  469. """
  470. base_size = total_items // total_groups
  471. rem = total_items % total_groups
  472. start = base_size * (group_id - 1) + min(group_id - 1, rem)
  473. size = base_size + 1 if group_id <= rem else base_size
  474. return (start, size)
  475. def get_group(items, total_groups, group_id):
  476. """
  477. Get the items from the passed in group based on group size.
  478. """
  479. if not 0 < group_id <= total_groups:
  480. raise ValueError("Invalid test-group argument")
  481. start, size = get_group_size_and_start(len(items), total_groups, group_id)
  482. selected = items[start : start + size]
  483. deselected = items[:start] + items[start + size :]
  484. assert len(selected) + len(deselected) == len(items)
  485. return selected, deselected
  486. def groups_collection_modifyitems(config, items):
  487. group_count = config.getoption("test-group-count")
  488. group_id = config.getoption("test-group")
  489. if not group_count or not group_id:
  490. # We're not selection tests using groups, don't do any filtering
  491. return
  492. total_items = len(items)
  493. tests_in_group, deselected = get_group(items, group_count, group_id)
  494. # Replace all items in the list
  495. items[:] = tests_in_group
  496. if deselected:
  497. config.hook.pytest_deselected(items=deselected)
  498. terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
  499. terminal_reporter.write(
  500. "Running test group #{} ({} tests)\n".format(group_id, len(items)), yellow=True,
  501. )
  502. # <---- Test Groups Selection ----------------------------------------------------------------------------------------
  503. # ----- Fixtures Overrides ------------------------------------------------------------------------------------------>
  504. @pytest.fixture(scope="session")
  505. def salt_factories_config():
  506. """
  507. Return a dictionary with the keyworkd arguments for FactoriesManager
  508. """
  509. return {
  510. "code_dir": str(CODE_DIR),
  511. "inject_coverage": MAYBE_RUN_COVERAGE,
  512. "inject_sitecustomize": MAYBE_RUN_COVERAGE,
  513. "start_timeout": 120
  514. if (os.environ.get("JENKINS_URL") or os.environ.get("CI"))
  515. else 60,
  516. }
  517. # <---- Fixtures Overrides -------------------------------------------------------------------------------------------
  518. # ----- Salt Factories ---------------------------------------------------------------------------------------------->
  519. @pytest.fixture(scope="session")
  520. def integration_files_dir(salt_factories):
  521. """
  522. Fixture which returns the salt integration files directory path.
  523. Creates the directory if it does not yet exist.
  524. """
  525. dirname = salt_factories.root_dir / "integration-files"
  526. dirname.mkdir(exist_ok=True)
  527. return dirname
  528. @pytest.fixture(scope="session")
  529. def state_tree_root_dir(integration_files_dir):
  530. """
  531. Fixture which returns the salt state tree root directory path.
  532. Creates the directory if it does not yet exist.
  533. """
  534. dirname = integration_files_dir / "state-tree"
  535. dirname.mkdir(exist_ok=True)
  536. return dirname
  537. @pytest.fixture(scope="session")
  538. def pillar_tree_root_dir(integration_files_dir):
  539. """
  540. Fixture which returns the salt pillar tree root directory path.
  541. Creates the directory if it does not yet exist.
  542. """
  543. dirname = integration_files_dir / "pillar-tree"
  544. dirname.mkdir(exist_ok=True)
  545. return dirname
  546. @pytest.fixture(scope="session")
  547. def base_env_state_tree_root_dir(state_tree_root_dir):
  548. """
  549. Fixture which returns the salt base environment state tree directory path.
  550. Creates the directory if it does not yet exist.
  551. """
  552. dirname = state_tree_root_dir / "base"
  553. dirname.mkdir(exist_ok=True)
  554. RUNTIME_VARS.TMP_STATE_TREE = str(dirname.resolve())
  555. RUNTIME_VARS.TMP_BASEENV_STATE_TREE = RUNTIME_VARS.TMP_STATE_TREE
  556. return dirname
  557. @pytest.fixture(scope="session")
  558. def prod_env_state_tree_root_dir(state_tree_root_dir):
  559. """
  560. Fixture which returns the salt prod environment state tree directory path.
  561. Creates the directory if it does not yet exist.
  562. """
  563. dirname = state_tree_root_dir / "prod"
  564. dirname.mkdir(exist_ok=True)
  565. RUNTIME_VARS.TMP_PRODENV_STATE_TREE = str(dirname.resolve())
  566. return dirname
  567. @pytest.fixture(scope="session")
  568. def base_env_pillar_tree_root_dir(pillar_tree_root_dir):
  569. """
  570. Fixture which returns the salt base environment pillar tree directory path.
  571. Creates the directory if it does not yet exist.
  572. """
  573. dirname = pillar_tree_root_dir / "base"
  574. dirname.mkdir(exist_ok=True)
  575. RUNTIME_VARS.TMP_PILLAR_TREE = str(dirname.resolve())
  576. RUNTIME_VARS.TMP_BASEENV_PILLAR_TREE = RUNTIME_VARS.TMP_PILLAR_TREE
  577. return dirname
  578. @pytest.fixture(scope="session")
  579. def prod_env_pillar_tree_root_dir(pillar_tree_root_dir):
  580. """
  581. Fixture which returns the salt prod environment pillar tree directory path.
  582. Creates the directory if it does not yet exist.
  583. """
  584. dirname = pillar_tree_root_dir / "prod"
  585. dirname.mkdir(exist_ok=True)
  586. RUNTIME_VARS.TMP_PRODENV_PILLAR_TREE = str(dirname.resolve())
  587. return dirname
  588. @pytest.fixture(scope="session")
  589. def salt_syndic_master_factory(
  590. request,
  591. salt_factories,
  592. base_env_state_tree_root_dir,
  593. base_env_pillar_tree_root_dir,
  594. prod_env_state_tree_root_dir,
  595. prod_env_pillar_tree_root_dir,
  596. ):
  597. root_dir = salt_factories.get_root_dir_for_daemon("syndic_master")
  598. conf_dir = root_dir / "conf"
  599. conf_dir.mkdir(exist_ok=True)
  600. with salt.utils.files.fopen(
  601. os.path.join(RUNTIME_VARS.CONF_DIR, "syndic_master")
  602. ) as rfh:
  603. config_defaults = yaml.deserialize(rfh.read())
  604. tests_known_hosts_file = str(root_dir / "salt_ssh_known_hosts")
  605. with salt.utils.files.fopen(tests_known_hosts_file, "w") as known_hosts:
  606. known_hosts.write("")
  607. config_defaults["root_dir"] = str(root_dir)
  608. config_defaults["known_hosts_file"] = tests_known_hosts_file
  609. config_defaults["syndic_master"] = "localhost"
  610. config_defaults["transport"] = request.config.getoption("--transport")
  611. config_overrides = {}
  612. ext_pillar = []
  613. if salt.utils.platform.is_windows():
  614. ext_pillar.append(
  615. {"cmd_yaml": "type {}".format(os.path.join(RUNTIME_VARS.FILES, "ext.yaml"))}
  616. )
  617. else:
  618. ext_pillar.append(
  619. {"cmd_yaml": "cat {}".format(os.path.join(RUNTIME_VARS.FILES, "ext.yaml"))}
  620. )
  621. # We need to copy the extension modules into the new master root_dir or
  622. # it will be prefixed by it
  623. extension_modules_path = str(root_dir / "extension_modules")
  624. if not os.path.exists(extension_modules_path):
  625. shutil.copytree(
  626. os.path.join(RUNTIME_VARS.FILES, "extension_modules"),
  627. extension_modules_path,
  628. )
  629. # Copy the autosign_file to the new master root_dir
  630. autosign_file_path = str(root_dir / "autosign_file")
  631. shutil.copyfile(
  632. os.path.join(RUNTIME_VARS.FILES, "autosign_file"), autosign_file_path
  633. )
  634. # all read, only owner write
  635. autosign_file_permissions = (
  636. stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR
  637. )
  638. os.chmod(autosign_file_path, autosign_file_permissions)
  639. config_overrides.update(
  640. {
  641. "ext_pillar": ext_pillar,
  642. "extension_modules": extension_modules_path,
  643. "file_roots": {
  644. "base": [
  645. str(base_env_state_tree_root_dir),
  646. os.path.join(RUNTIME_VARS.FILES, "file", "base"),
  647. ],
  648. # Alternate root to test __env__ choices
  649. "prod": [
  650. str(prod_env_state_tree_root_dir),
  651. os.path.join(RUNTIME_VARS.FILES, "file", "prod"),
  652. ],
  653. },
  654. "pillar_roots": {
  655. "base": [
  656. str(base_env_pillar_tree_root_dir),
  657. os.path.join(RUNTIME_VARS.FILES, "pillar", "base"),
  658. ],
  659. "prod": [str(prod_env_pillar_tree_root_dir)],
  660. },
  661. }
  662. )
  663. factory = salt_factories.get_salt_master_daemon(
  664. "syndic_master",
  665. order_masters=True,
  666. config_defaults=config_defaults,
  667. config_overrides=config_overrides,
  668. extra_cli_arguments_after_first_start_failure=["--log-level=debug"],
  669. )
  670. return factory
  671. @pytest.fixture(scope="session")
  672. def salt_syndic_factory(salt_factories, salt_syndic_master_factory):
  673. config_defaults = {"master": None, "minion": None, "syndic": None}
  674. with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, "syndic")) as rfh:
  675. opts = yaml.deserialize(rfh.read())
  676. opts["hosts.file"] = os.path.join(RUNTIME_VARS.TMP, "hosts")
  677. opts["aliases.file"] = os.path.join(RUNTIME_VARS.TMP, "aliases")
  678. opts["transport"] = salt_syndic_master_factory.config["transport"]
  679. config_defaults["syndic"] = opts
  680. factory = salt_syndic_master_factory.get_salt_syndic_daemon(
  681. "syndic",
  682. config_defaults=config_defaults,
  683. extra_cli_arguments_after_first_start_failure=["--log-level=debug"],
  684. )
  685. return factory
  686. @pytest.fixture(scope="session")
  687. def salt_master_factory(
  688. salt_factories,
  689. salt_syndic_master_factory,
  690. base_env_state_tree_root_dir,
  691. base_env_pillar_tree_root_dir,
  692. prod_env_state_tree_root_dir,
  693. prod_env_pillar_tree_root_dir,
  694. ):
  695. root_dir = salt_factories.get_root_dir_for_daemon("master")
  696. conf_dir = root_dir / "conf"
  697. conf_dir.mkdir(exist_ok=True)
  698. with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, "master")) as rfh:
  699. config_defaults = yaml.deserialize(rfh.read())
  700. tests_known_hosts_file = str(root_dir / "salt_ssh_known_hosts")
  701. with salt.utils.files.fopen(tests_known_hosts_file, "w") as known_hosts:
  702. known_hosts.write("")
  703. config_defaults["root_dir"] = str(root_dir)
  704. config_defaults["known_hosts_file"] = tests_known_hosts_file
  705. config_defaults["syndic_master"] = "localhost"
  706. config_defaults["transport"] = salt_syndic_master_factory.config["transport"]
  707. config_defaults["reactor"] = [
  708. {"salt/test/reactor": [os.path.join(RUNTIME_VARS.FILES, "reactor-test.sls")]}
  709. ]
  710. config_overrides = {}
  711. ext_pillar = []
  712. if salt.utils.platform.is_windows():
  713. ext_pillar.append(
  714. {"cmd_yaml": "type {}".format(os.path.join(RUNTIME_VARS.FILES, "ext.yaml"))}
  715. )
  716. else:
  717. ext_pillar.append(
  718. {"cmd_yaml": "cat {}".format(os.path.join(RUNTIME_VARS.FILES, "ext.yaml"))}
  719. )
  720. ext_pillar.append(
  721. {
  722. "file_tree": {
  723. "root_dir": os.path.join(RUNTIME_VARS.PILLAR_DIR, "base", "file_tree"),
  724. "follow_dir_links": False,
  725. "keep_newline": True,
  726. }
  727. }
  728. )
  729. config_overrides["pillar_opts"] = True
  730. # We need to copy the extension modules into the new master root_dir or
  731. # it will be prefixed by it
  732. extension_modules_path = str(root_dir / "extension_modules")
  733. if not os.path.exists(extension_modules_path):
  734. shutil.copytree(
  735. os.path.join(RUNTIME_VARS.FILES, "extension_modules"),
  736. extension_modules_path,
  737. )
  738. # Copy the autosign_file to the new master root_dir
  739. autosign_file_path = str(root_dir / "autosign_file")
  740. shutil.copyfile(
  741. os.path.join(RUNTIME_VARS.FILES, "autosign_file"), autosign_file_path
  742. )
  743. # all read, only owner write
  744. autosign_file_permissions = (
  745. stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR
  746. )
  747. os.chmod(autosign_file_path, autosign_file_permissions)
  748. config_overrides.update(
  749. {
  750. "ext_pillar": ext_pillar,
  751. "extension_modules": extension_modules_path,
  752. "file_roots": {
  753. "base": [
  754. str(base_env_state_tree_root_dir),
  755. os.path.join(RUNTIME_VARS.FILES, "file", "base"),
  756. ],
  757. # Alternate root to test __env__ choices
  758. "prod": [
  759. str(prod_env_state_tree_root_dir),
  760. os.path.join(RUNTIME_VARS.FILES, "file", "prod"),
  761. ],
  762. },
  763. "pillar_roots": {
  764. "base": [
  765. str(base_env_pillar_tree_root_dir),
  766. os.path.join(RUNTIME_VARS.FILES, "pillar", "base"),
  767. ],
  768. "prod": [str(prod_env_pillar_tree_root_dir)],
  769. },
  770. }
  771. )
  772. # Let's copy over the test cloud config files and directories into the running master config directory
  773. for entry in os.listdir(RUNTIME_VARS.CONF_DIR):
  774. if not entry.startswith("cloud"):
  775. continue
  776. source = os.path.join(RUNTIME_VARS.CONF_DIR, entry)
  777. dest = str(conf_dir / entry)
  778. if os.path.isdir(source):
  779. shutil.copytree(source, dest)
  780. else:
  781. shutil.copyfile(source, dest)
  782. factory = salt_syndic_master_factory.get_salt_master_daemon(
  783. "master",
  784. config_defaults=config_defaults,
  785. config_overrides=config_overrides,
  786. extra_cli_arguments_after_first_start_failure=["--log-level=debug"],
  787. )
  788. return factory
  789. @pytest.fixture(scope="session")
  790. def salt_minion_factory(salt_master_factory):
  791. with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, "minion")) as rfh:
  792. config_defaults = yaml.deserialize(rfh.read())
  793. config_defaults["hosts.file"] = os.path.join(RUNTIME_VARS.TMP, "hosts")
  794. config_defaults["aliases.file"] = os.path.join(RUNTIME_VARS.TMP, "aliases")
  795. config_defaults["transport"] = salt_master_factory.config["transport"]
  796. config_overrides = {
  797. "file_roots": salt_master_factory.config["file_roots"].copy(),
  798. "pillar_roots": salt_master_factory.config["pillar_roots"].copy(),
  799. }
  800. virtualenv_binary = get_virtualenv_binary_path()
  801. if virtualenv_binary:
  802. config_overrides["venv_bin"] = virtualenv_binary
  803. factory = salt_master_factory.get_salt_minion_daemon(
  804. "minion",
  805. config_defaults=config_defaults,
  806. config_overrides=config_overrides,
  807. extra_cli_arguments_after_first_start_failure=["--log-level=debug"],
  808. )
  809. factory.register_after_terminate_callback(
  810. pytest.helpers.remove_stale_minion_key, salt_master_factory, factory.id
  811. )
  812. return factory
  813. @pytest.fixture(scope="session")
  814. def salt_sub_minion_factory(salt_master_factory):
  815. with salt.utils.files.fopen(
  816. os.path.join(RUNTIME_VARS.CONF_DIR, "sub_minion")
  817. ) as rfh:
  818. config_defaults = yaml.deserialize(rfh.read())
  819. config_defaults["hosts.file"] = os.path.join(RUNTIME_VARS.TMP, "hosts")
  820. config_defaults["aliases.file"] = os.path.join(RUNTIME_VARS.TMP, "aliases")
  821. config_defaults["transport"] = salt_master_factory.config["transport"]
  822. config_overrides = {
  823. "file_roots": salt_master_factory.config["file_roots"].copy(),
  824. "pillar_roots": salt_master_factory.config["pillar_roots"].copy(),
  825. }
  826. virtualenv_binary = get_virtualenv_binary_path()
  827. if virtualenv_binary:
  828. config_overrides["venv_bin"] = virtualenv_binary
  829. factory = salt_master_factory.get_salt_minion_daemon(
  830. "sub_minion",
  831. config_defaults=config_defaults,
  832. config_overrides=config_overrides,
  833. extra_cli_arguments_after_first_start_failure=["--log-level=debug"],
  834. )
  835. factory.register_after_terminate_callback(
  836. pytest.helpers.remove_stale_minion_key, salt_master_factory, factory.id
  837. )
  838. return factory
  839. @pytest.fixture(scope="session")
  840. def salt_proxy_factory(salt_factories, salt_master_factory):
  841. proxy_minion_id = "proxytest"
  842. root_dir = salt_factories.get_root_dir_for_daemon(proxy_minion_id)
  843. conf_dir = root_dir / "conf"
  844. conf_dir.mkdir(parents=True, exist_ok=True)
  845. RUNTIME_VARS.TMP_PROXY_CONF_DIR = str(conf_dir)
  846. with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, "proxy")) as rfh:
  847. config_defaults = yaml.deserialize(rfh.read())
  848. config_defaults["root_dir"] = str(root_dir)
  849. config_defaults["hosts.file"] = os.path.join(RUNTIME_VARS.TMP, "hosts")
  850. config_defaults["aliases.file"] = os.path.join(RUNTIME_VARS.TMP, "aliases")
  851. config_defaults["transport"] = salt_master_factory.config["transport"]
  852. factory = salt_master_factory.get_salt_proxy_minion_daemon(
  853. proxy_minion_id,
  854. config_defaults=config_defaults,
  855. extra_cli_arguments_after_first_start_failure=["--log-level=debug"],
  856. )
  857. factory.register_after_terminate_callback(
  858. pytest.helpers.remove_stale_minion_key, salt_master_factory, factory.id
  859. )
  860. return factory
  861. @pytest.fixture(scope="session")
  862. def salt_cli(salt_master_factory):
  863. return salt_master_factory.get_salt_cli()
  864. @pytest.fixture(scope="session")
  865. def salt_cp_cli(salt_master_factory):
  866. return salt_master_factory.get_salt_cp_cli()
  867. @pytest.fixture(scope="session")
  868. def salt_key_cli(salt_master_factory):
  869. return salt_master_factory.get_salt_key_cli()
  870. @pytest.fixture(scope="session")
  871. def salt_run_cli(salt_master_factory):
  872. return salt_master_factory.get_salt_run_cli()
  873. @pytest.fixture(scope="session")
  874. def salt_ssh_cli(salt_master_factory):
  875. return salt_master_factory.get_salt_ssh_cli()
  876. @pytest.fixture(scope="session")
  877. def salt_call_cli(salt_minion_factory):
  878. return salt_minion_factory.get_salt_call_cli()
  879. @pytest.fixture(scope="session", autouse=True)
  880. def bridge_pytest_and_runtests(
  881. reap_stray_processes,
  882. salt_factories,
  883. salt_syndic_master_factory,
  884. salt_syndic_factory,
  885. salt_master_factory,
  886. salt_minion_factory,
  887. salt_sub_minion_factory,
  888. sshd_config_dir,
  889. ):
  890. # Make sure unittest2 uses the pytest generated configuration
  891. RUNTIME_VARS.RUNTIME_CONFIGS["master"] = freeze(salt_master_factory.config)
  892. RUNTIME_VARS.RUNTIME_CONFIGS["minion"] = freeze(salt_minion_factory.config)
  893. RUNTIME_VARS.RUNTIME_CONFIGS["sub_minion"] = freeze(salt_sub_minion_factory.config)
  894. RUNTIME_VARS.RUNTIME_CONFIGS["syndic_master"] = freeze(
  895. salt_syndic_master_factory.config
  896. )
  897. RUNTIME_VARS.RUNTIME_CONFIGS["syndic"] = freeze(salt_syndic_factory.config)
  898. RUNTIME_VARS.RUNTIME_CONFIGS["client_config"] = freeze(
  899. salt.config.client_config(salt_master_factory.config["conf_file"])
  900. )
  901. # Make sure unittest2 classes know their paths
  902. RUNTIME_VARS.TMP_ROOT_DIR = str(salt_factories.root_dir.resolve())
  903. RUNTIME_VARS.TMP_CONF_DIR = os.path.dirname(salt_master_factory.config["conf_file"])
  904. RUNTIME_VARS.TMP_MINION_CONF_DIR = os.path.dirname(
  905. salt_minion_factory.config["conf_file"]
  906. )
  907. RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR = os.path.dirname(
  908. salt_sub_minion_factory.config["conf_file"]
  909. )
  910. RUNTIME_VARS.TMP_SYNDIC_MASTER_CONF_DIR = os.path.dirname(
  911. salt_syndic_master_factory.config["conf_file"]
  912. )
  913. RUNTIME_VARS.TMP_SYNDIC_MINION_CONF_DIR = os.path.dirname(
  914. salt_syndic_factory.config["conf_file"]
  915. )
  916. RUNTIME_VARS.TMP_SSH_CONF_DIR = str(sshd_config_dir)
  917. @pytest.fixture(scope="session")
  918. def sshd_config_dir(salt_factories):
  919. config_dir = salt_factories.get_root_dir_for_daemon("sshd")
  920. yield config_dir
  921. shutil.rmtree(str(config_dir), ignore_errors=True)
  922. @pytest.fixture(scope="module")
  923. def sshd_server(salt_factories, sshd_config_dir, salt_master):
  924. sshd_config_dict = {
  925. "Protocol": "2",
  926. # Turn strict modes off so that we can operate in /tmp
  927. "StrictModes": "no",
  928. # Logging
  929. "SyslogFacility": "AUTH",
  930. "LogLevel": "INFO",
  931. # Authentication:
  932. "LoginGraceTime": "120",
  933. "PermitRootLogin": "without-password",
  934. "PubkeyAuthentication": "yes",
  935. # Don't read the user's ~/.rhosts and ~/.shosts files
  936. "IgnoreRhosts": "yes",
  937. "HostbasedAuthentication": "no",
  938. # To enable empty passwords, change to yes (NOT RECOMMENDED)
  939. "PermitEmptyPasswords": "no",
  940. # Change to yes to enable challenge-response passwords (beware issues with
  941. # some PAM modules and threads)
  942. "ChallengeResponseAuthentication": "no",
  943. # Change to no to disable tunnelled clear text passwords
  944. "PasswordAuthentication": "no",
  945. "X11Forwarding": "no",
  946. "X11DisplayOffset": "10",
  947. "PrintMotd": "no",
  948. "PrintLastLog": "yes",
  949. "TCPKeepAlive": "yes",
  950. "AcceptEnv": "LANG LC_*",
  951. "Subsystem": "sftp /usr/lib/openssh/sftp-server",
  952. "UsePAM": "yes",
  953. }
  954. factory = salt_factories.get_sshd_daemon(
  955. sshd_config_dict=sshd_config_dict, config_dir=sshd_config_dir,
  956. )
  957. # We also need a salt-ssh roster config file
  958. roster_path = pathlib.Path(salt_master.config_dir) / "roster"
  959. roster_contents = textwrap.dedent(
  960. """\
  961. localhost:
  962. host: 127.0.0.1
  963. port: {}
  964. user: {}
  965. mine_functions:
  966. test.arg: ['itworked']
  967. """.format(
  968. factory.listen_port, RUNTIME_VARS.RUNNING_TESTS_USER
  969. )
  970. )
  971. if salt.utils.platform.is_darwin():
  972. roster_contents += " set_path: $PATH:/usr/local/bin/\n"
  973. log.debug(
  974. "Writing to configuration file %s. Configuration:\n%s",
  975. roster_path,
  976. roster_contents,
  977. )
  978. with salt.utils.files.fopen(str(roster_path), "w") as wfh:
  979. wfh.write(roster_contents)
  980. with factory.started():
  981. yield factory
  982. if roster_path.exists():
  983. roster_path.unlink()
  984. # <---- Salt Factories -----------------------------------------------------------------------------------------------
  985. # ----- From Filenames Test Selection ------------------------------------------------------------------------------->
  986. def _match_to_test_file(match):
  987. parts = match.split(".")
  988. parts[-1] += ".py"
  989. return TESTS_DIR.joinpath(*parts).relative_to(CODE_DIR)
  990. def from_filenames_collection_modifyitems(config, items):
  991. from_filenames = config.getoption("--from-filenames")
  992. if not from_filenames:
  993. # Don't do anything
  994. return
  995. test_categories_paths = (
  996. (TESTS_DIR / "integration").relative_to(CODE_DIR),
  997. (TESTS_DIR / "multimaster").relative_to(CODE_DIR),
  998. (TESTS_DIR / "unit").relative_to(CODE_DIR),
  999. (PYTESTS_DIR / "e2e").relative_to(CODE_DIR),
  1000. (PYTESTS_DIR / "functional").relative_to(CODE_DIR),
  1001. (PYTESTS_DIR / "integration").relative_to(CODE_DIR),
  1002. (PYTESTS_DIR / "unit").relative_to(CODE_DIR),
  1003. )
  1004. test_module_paths = set()
  1005. from_filenames_listing = set()
  1006. for path in [pathlib.Path(path.strip()) for path in from_filenames.split(",")]:
  1007. if path.is_absolute():
  1008. # In this case, this path is considered to be a file containing a line separated list
  1009. # of files to consider
  1010. with salt.utils.files.fopen(str(path)) as rfh:
  1011. for line in rfh:
  1012. line_path = pathlib.Path(line.strip())
  1013. if not line_path.exists():
  1014. continue
  1015. from_filenames_listing.add(line_path)
  1016. continue
  1017. from_filenames_listing.add(path)
  1018. filename_map = yaml.deserialize((TESTS_DIR / "filename_map.yml").read_text())
  1019. # Let's add the match all rule
  1020. for rule, matches in filename_map.items():
  1021. if rule == "*":
  1022. for match in matches:
  1023. test_module_paths.add(_match_to_test_file(match))
  1024. break
  1025. # Let's now go through the list of files gathered
  1026. for filename in from_filenames_listing:
  1027. if str(filename).startswith("tests/"):
  1028. # Tests in the listing don't require additional matching and will be added to the
  1029. # list of tests to run
  1030. test_module_paths.add(filename)
  1031. continue
  1032. if filename.name == "setup.py" or str(filename).startswith("salt/"):
  1033. if path.name == "__init__.py":
  1034. # No direct macthing
  1035. continue
  1036. # Now let's try a direct match between the passed file and possible test modules
  1037. for test_categories_path in test_categories_paths:
  1038. test_module_path = test_categories_path / "test_{}".format(path.name)
  1039. if test_module_path.is_file():
  1040. test_module_paths.add(test_module_path)
  1041. continue
  1042. # Do we have an entry in tests/filename_map.yml
  1043. for rule, matches in filename_map.items():
  1044. if rule == "*":
  1045. continue
  1046. elif "|" in rule:
  1047. # This is regex
  1048. if re.match(rule, str(filename)):
  1049. for match in matches:
  1050. test_module_paths.add(_match_to_test_file(match))
  1051. elif "*" in rule or "\\" in rule:
  1052. # Glob matching
  1053. for filerule in CODE_DIR.glob(rule):
  1054. if not filerule.exists():
  1055. continue
  1056. filerule = filerule.relative_to(CODE_DIR)
  1057. if filerule != filename:
  1058. continue
  1059. for match in matches:
  1060. test_module_paths.add(_match_to_test_file(match))
  1061. else:
  1062. if str(filename) != rule:
  1063. continue
  1064. # Direct file paths as rules
  1065. filerule = pathlib.Path(rule)
  1066. if not filerule.exists():
  1067. continue
  1068. for match in matches:
  1069. test_module_paths.add(_match_to_test_file(match))
  1070. continue
  1071. else:
  1072. log.debug("Don't know what to do with path %s", filename)
  1073. selected = []
  1074. deselected = []
  1075. for item in items:
  1076. itempath = pathlib.Path(str(item.fspath)).resolve().relative_to(CODE_DIR)
  1077. if itempath in test_module_paths:
  1078. selected.append(item)
  1079. else:
  1080. deselected.append(item)
  1081. items[:] = selected
  1082. if deselected:
  1083. config.hook.pytest_deselected(items=deselected)
  1084. # <---- From Filenames Test Selection --------------------------------------------------------------------------------
  1085. # ----- Custom Fixtures --------------------------------------------------------------------------------------------->
  1086. @pytest.fixture(scope="session")
  1087. def reap_stray_processes():
  1088. # Run tests
  1089. yield
  1090. children = psutil.Process(os.getpid()).children(recursive=True)
  1091. if not children:
  1092. log.info("No astray processes found")
  1093. return
  1094. def on_terminate(proc):
  1095. log.debug("Process %s terminated with exit code %s", proc, proc.returncode)
  1096. if children:
  1097. # Reverse the order, sublings first, parents after
  1098. children.reverse()
  1099. log.warning(
  1100. "Test suite left %d astray processes running. Killing those processes:\n%s",
  1101. len(children),
  1102. pprint.pformat(children),
  1103. )
  1104. _, alive = psutil.wait_procs(children, timeout=3, callback=on_terminate)
  1105. for child in alive:
  1106. try:
  1107. child.kill()
  1108. except psutil.NoSuchProcess:
  1109. continue
  1110. _, alive = psutil.wait_procs(alive, timeout=3, callback=on_terminate)
  1111. if alive:
  1112. # Give up
  1113. for child in alive:
  1114. log.warning(
  1115. "Process %s survived SIGKILL, giving up:\n%s",
  1116. child,
  1117. pprint.pformat(child.as_dict()),
  1118. )
  1119. @pytest.fixture(scope="session")
  1120. def sminion():
  1121. return create_sminion()
  1122. @pytest.fixture(scope="session")
  1123. def grains(sminion):
  1124. return sminion.opts["grains"].copy()
  1125. # <---- Custom Fixtures ----------------------------------------------------------------------------------------------