1
0

conftest.py 48 KB

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