noxfile.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. """
  2. noxfile
  3. ~~~~~~~
  4. Nox configuration script
  5. """
  6. # pylint: disable=resource-leakage,3rd-party-module-not-gated
  7. import datetime
  8. import glob
  9. import os
  10. import shutil
  11. import sys
  12. import tempfile
  13. # fmt: off
  14. if __name__ == "__main__":
  15. sys.stderr.write(
  16. "Do not execute this file directly. Use nox instead, it will know how to handle this file\n"
  17. )
  18. sys.stderr.flush()
  19. exit(1)
  20. # fmt: on
  21. import nox # isort:skip
  22. from nox.command import CommandFailed # isort:skip
  23. IS_PY3 = sys.version_info > (2,)
  24. # Be verbose when runing under a CI context
  25. CI_RUN = (
  26. os.environ.get("JENKINS_URL")
  27. or os.environ.get("CI")
  28. or os.environ.get("DRONE") is not None
  29. )
  30. PIP_INSTALL_SILENT = CI_RUN is False
  31. SKIP_REQUIREMENTS_INSTALL = "SKIP_REQUIREMENTS_INSTALL" in os.environ
  32. EXTRA_REQUIREMENTS_INSTALL = os.environ.get("EXTRA_REQUIREMENTS_INSTALL")
  33. # Global Path Definitions
  34. REPO_ROOT = os.path.abspath(os.path.dirname(__file__))
  35. SITECUSTOMIZE_DIR = os.path.join(REPO_ROOT, "tests", "support", "coverage")
  36. IS_DARWIN = sys.platform.lower().startswith("darwin")
  37. IS_WINDOWS = sys.platform.lower().startswith("win")
  38. IS_FREEBSD = sys.platform.lower().startswith("freebsd")
  39. # Python versions to run against
  40. _PYTHON_VERSIONS = ("3", "3.5", "3.6", "3.7", "3.8", "3.9")
  41. # Nox options
  42. # Reuse existing virtualenvs
  43. nox.options.reuse_existing_virtualenvs = True
  44. # Don't fail on missing interpreters
  45. nox.options.error_on_missing_interpreters = False
  46. # Change current directory to REPO_ROOT
  47. os.chdir(REPO_ROOT)
  48. RUNTESTS_LOGFILE = os.path.join(
  49. "artifacts",
  50. "logs",
  51. "runtests-{}.log".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S.%f")),
  52. )
  53. # Prevent Python from writing bytecode
  54. os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
  55. def find_session_runner(session, name, **kwargs):
  56. for s, _ in session._runner.manifest.list_all_sessions():
  57. if name not in s.signatures:
  58. continue
  59. for signature in s.signatures:
  60. for key, value in kwargs.items():
  61. param = "{}={!r}".format(key, value)
  62. if IS_PY3:
  63. # Under Python2 repr unicode string are always "u" prefixed, ie, u'a string'.
  64. param = param.replace("u'", "'")
  65. if param not in signature:
  66. break
  67. else:
  68. return s
  69. continue
  70. session.error(
  71. "Could not find a nox session by the name {!r} with the following keyword arguments: {!r}".format(
  72. name, kwargs
  73. )
  74. )
  75. def _create_ci_directories():
  76. for dirname in ("logs", "coverage", "xml-unittests-output"):
  77. path = os.path.join("artifacts", dirname)
  78. if not os.path.exists(path):
  79. os.makedirs(path)
  80. def _get_session_python_version_info(session):
  81. try:
  82. version_info = session._runner._real_python_version_info
  83. except AttributeError:
  84. old_install_only_value = session._runner.global_config.install_only
  85. try:
  86. # Force install only to be false for the following chunk of code
  87. # For additional information as to why see:
  88. # https://github.com/theacodes/nox/pull/181
  89. session._runner.global_config.install_only = False
  90. session_py_version = session.run(
  91. "python",
  92. "-c"
  93. 'import sys; sys.stdout.write("{}.{}.{}".format(*sys.version_info))',
  94. silent=True,
  95. log=False,
  96. )
  97. version_info = tuple(
  98. int(part) for part in session_py_version.split(".") if part.isdigit()
  99. )
  100. session._runner._real_python_version_info = version_info
  101. finally:
  102. session._runner.global_config.install_only = old_install_only_value
  103. return version_info
  104. def _get_session_python_site_packages_dir(session):
  105. try:
  106. site_packages_dir = session._runner._site_packages_dir
  107. except AttributeError:
  108. old_install_only_value = session._runner.global_config.install_only
  109. try:
  110. # Force install only to be false for the following chunk of code
  111. # For additional information as to why see:
  112. # https://github.com/theacodes/nox/pull/181
  113. session._runner.global_config.install_only = False
  114. site_packages_dir = session.run(
  115. "python",
  116. "-c"
  117. "import sys; from distutils.sysconfig import get_python_lib; sys.stdout.write(get_python_lib())",
  118. silent=True,
  119. log=False,
  120. )
  121. session._runner._site_packages_dir = site_packages_dir
  122. finally:
  123. session._runner.global_config.install_only = old_install_only_value
  124. return site_packages_dir
  125. def _get_pydir(session):
  126. version_info = _get_session_python_version_info(session)
  127. if version_info < (3, 5):
  128. session.error("Only Python >= 3.5 is supported")
  129. return "py{}.{}".format(*version_info)
  130. def _install_system_packages(session):
  131. """
  132. Because some python packages are provided by the distribution and cannot
  133. be pip installed, and because we don't want the whole system python packages
  134. on our virtualenvs, we copy the required system python packages into
  135. the virtualenv
  136. """
  137. version_info = _get_session_python_version_info(session)
  138. py_version_keys = ["{}".format(*version_info), "{}.{}".format(*version_info)]
  139. session_site_packages_dir = _get_session_python_site_packages_dir(session)
  140. session_site_packages_dir = os.path.relpath(session_site_packages_dir, REPO_ROOT)
  141. for py_version in py_version_keys:
  142. dist_packages_path = "/usr/lib/python{}/dist-packages".format(py_version)
  143. if not os.path.isdir(dist_packages_path):
  144. continue
  145. for aptpkg in glob.glob(os.path.join(dist_packages_path, "*apt*")):
  146. src = os.path.realpath(aptpkg)
  147. dst = os.path.join(session_site_packages_dir, os.path.basename(src))
  148. if os.path.exists(dst):
  149. session.log("Not overwritting already existing %s with %s", dst, src)
  150. continue
  151. session.log("Copying %s into %s", src, dst)
  152. if os.path.isdir(src):
  153. shutil.copytree(src, dst)
  154. else:
  155. shutil.copyfile(src, dst)
  156. def _get_pip_requirements_file(session, transport, crypto=None):
  157. pydir = _get_pydir(session)
  158. if IS_WINDOWS:
  159. if crypto is None:
  160. _requirements_file = os.path.join(
  161. "requirements", "static", pydir, "{}-windows.txt".format(transport)
  162. )
  163. if os.path.exists(_requirements_file):
  164. return _requirements_file
  165. _requirements_file = os.path.join(
  166. "requirements", "static", pydir, "windows.txt"
  167. )
  168. if os.path.exists(_requirements_file):
  169. return _requirements_file
  170. _requirements_file = os.path.join(
  171. "requirements", "static", pydir, "windows-crypto.txt"
  172. )
  173. if os.path.exists(_requirements_file):
  174. return _requirements_file
  175. elif IS_DARWIN:
  176. if crypto is None:
  177. _requirements_file = os.path.join(
  178. "requirements", "static", pydir, "{}-darwin.txt".format(transport)
  179. )
  180. if os.path.exists(_requirements_file):
  181. return _requirements_file
  182. _requirements_file = os.path.join(
  183. "requirements", "static", pydir, "darwin.txt"
  184. )
  185. if os.path.exists(_requirements_file):
  186. return _requirements_file
  187. _requirements_file = os.path.join(
  188. "requirements", "static", pydir, "darwin-crypto.txt"
  189. )
  190. if os.path.exists(_requirements_file):
  191. return _requirements_file
  192. elif IS_FREEBSD:
  193. if crypto is None:
  194. _requirements_file = os.path.join(
  195. "requirements", "static", pydir, "{}-freebsd.txt".format(transport)
  196. )
  197. if os.path.exists(_requirements_file):
  198. return _requirements_file
  199. _requirements_file = os.path.join(
  200. "requirements", "static", pydir, "freebsd.txt"
  201. )
  202. if os.path.exists(_requirements_file):
  203. return _requirements_file
  204. _requirements_file = os.path.join(
  205. "requirements", "static", pydir, "freebsd-crypto.txt"
  206. )
  207. if os.path.exists(_requirements_file):
  208. return _requirements_file
  209. else:
  210. _install_system_packages(session)
  211. if crypto is None:
  212. _requirements_file = os.path.join(
  213. "requirements", "static", pydir, "{}-linux.txt".format(transport)
  214. )
  215. if os.path.exists(_requirements_file):
  216. return _requirements_file
  217. _requirements_file = os.path.join(
  218. "requirements", "static", pydir, "linux.txt"
  219. )
  220. if os.path.exists(_requirements_file):
  221. return _requirements_file
  222. _requirements_file = os.path.join(
  223. "requirements", "static", pydir, "linux-crypto.txt"
  224. )
  225. if os.path.exists(_requirements_file):
  226. return _requirements_file
  227. def _install_requirements(session, transport, *extra_requirements):
  228. if SKIP_REQUIREMENTS_INSTALL:
  229. session.log(
  230. "Skipping Python Requirements because SKIP_REQUIREMENTS_INSTALL was found in the environ"
  231. )
  232. return
  233. # setuptools 50.0.0 is broken
  234. # https://github.com/pypa/setuptools/issues?q=is%3Aissue+setuptools+50+
  235. install_command = ["--progress-bar=off", "-U", "setuptools<50.0.0"]
  236. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  237. # Install requirements
  238. requirements_file = _get_pip_requirements_file(session, transport)
  239. install_command = ["--progress-bar=off", "-r", requirements_file]
  240. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  241. if extra_requirements:
  242. install_command = ["--progress-bar=off"]
  243. install_command += list(extra_requirements)
  244. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  245. if EXTRA_REQUIREMENTS_INSTALL:
  246. session.log(
  247. "Installing the following extra requirements because the EXTRA_REQUIREMENTS_INSTALL environment variable "
  248. "was set: %s",
  249. EXTRA_REQUIREMENTS_INSTALL,
  250. )
  251. # We pass --constraint in this step because in case any of these extra dependencies has a requirement
  252. # we're already using, we want to maintain the locked version
  253. install_command = ["--progress-bar=off", "--constraint", requirements_file]
  254. install_command += EXTRA_REQUIREMENTS_INSTALL.split()
  255. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  256. def _run_with_coverage(session, *test_cmd):
  257. if SKIP_REQUIREMENTS_INSTALL is False:
  258. session.install(
  259. "--progress-bar=off", "coverage==5.2", silent=PIP_INSTALL_SILENT
  260. )
  261. session.run("coverage", "erase")
  262. python_path_env_var = os.environ.get("PYTHONPATH") or None
  263. if python_path_env_var is None:
  264. python_path_env_var = SITECUSTOMIZE_DIR
  265. else:
  266. python_path_entries = python_path_env_var.split(os.pathsep)
  267. if SITECUSTOMIZE_DIR in python_path_entries:
  268. python_path_entries.remove(SITECUSTOMIZE_DIR)
  269. python_path_entries.insert(0, SITECUSTOMIZE_DIR)
  270. python_path_env_var = os.pathsep.join(python_path_entries)
  271. env = {
  272. # The updated python path so that sitecustomize is importable
  273. "PYTHONPATH": python_path_env_var,
  274. # The full path to the .coverage data file. Makes sure we always write
  275. # them to the same directory
  276. "COVERAGE_FILE": os.path.abspath(os.path.join(REPO_ROOT, ".coverage")),
  277. # Instruct sub processes to also run under coverage
  278. "COVERAGE_PROCESS_START": os.path.join(REPO_ROOT, ".coveragerc"),
  279. }
  280. if IS_DARWIN:
  281. # Don't nuke our multiprocessing efforts objc!
  282. # https://stackoverflow.com/questions/50168647/multiprocessing-causes-python-to-crash-and-gives-an-error-may-have-been-in-progr
  283. env["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"
  284. try:
  285. session.run(*test_cmd, env=env)
  286. finally:
  287. # Always combine and generate the XML coverage report
  288. try:
  289. session.run("coverage", "combine")
  290. except CommandFailed:
  291. # Sometimes some of the coverage files are corrupt which would trigger a CommandFailed
  292. # exception
  293. pass
  294. # Generate report for salt code coverage
  295. session.run(
  296. "coverage",
  297. "xml",
  298. "-o",
  299. os.path.join("artifacts", "coverage", "salt.xml"),
  300. "--omit=tests/*",
  301. "--include=salt/*",
  302. )
  303. # Generate report for tests code coverage
  304. session.run(
  305. "coverage",
  306. "xml",
  307. "-o",
  308. os.path.join("artifacts", "coverage", "tests.xml"),
  309. "--omit=salt/*",
  310. "--include=tests/*",
  311. )
  312. # Move the coverage DB to artifacts/coverage in order for it to be archived by CI
  313. shutil.move(".coverage", os.path.join("artifacts", "coverage", ".coverage"))
  314. def _runtests(session):
  315. session.error(
  316. """\n\nruntests.py support has been removed from Salt. Please try `nox -e '{0}'` """
  317. """or `nox -e '{0}' -- --help` to know more about the supported CLI flags.\n"""
  318. "For more information, please check "
  319. "https://docs.saltstack.com/en/latest/topics/development/tests/index.html#running-the-tests\n..".format(
  320. session._runner.global_config.sessions[0].replace("runtests", "pytest")
  321. )
  322. )
  323. @nox.session(python=_PYTHON_VERSIONS, name="runtests-parametrized")
  324. @nox.parametrize("coverage", [False, True])
  325. @nox.parametrize("transport", ["zeromq", "tcp"])
  326. @nox.parametrize("crypto", [None, "m2crypto", "pycryptodome"])
  327. def runtests_parametrized(session, coverage, transport, crypto):
  328. """
  329. DO NOT CALL THIS NOX SESSION DIRECTLY
  330. """
  331. _runtests(session)
  332. @nox.session(python=_PYTHON_VERSIONS)
  333. @nox.parametrize("coverage", [False, True])
  334. def runtests(session, coverage):
  335. """
  336. runtests.py session with zeromq transport and default crypto
  337. """
  338. _runtests(session)
  339. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tcp")
  340. @nox.parametrize("coverage", [False, True])
  341. def runtests_tcp(session, coverage):
  342. """
  343. runtests.py session with TCP transport and default crypto
  344. """
  345. _runtests(session)
  346. @nox.session(python=_PYTHON_VERSIONS, name="runtests-zeromq")
  347. @nox.parametrize("coverage", [False, True])
  348. def runtests_zeromq(session, coverage):
  349. """
  350. runtests.py session with zeromq transport and default crypto
  351. """
  352. _runtests(session)
  353. @nox.session(python=_PYTHON_VERSIONS, name="runtests-m2crypto")
  354. @nox.parametrize("coverage", [False, True])
  355. def runtests_m2crypto(session, coverage):
  356. """
  357. runtests.py session with zeromq transport and m2crypto
  358. """
  359. _runtests(session)
  360. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tcp-m2crypto")
  361. @nox.parametrize("coverage", [False, True])
  362. def runtests_tcp_m2crypto(session, coverage):
  363. """
  364. runtests.py session with TCP transport and m2crypto
  365. """
  366. _runtests(session)
  367. @nox.session(python=_PYTHON_VERSIONS, name="runtests-zeromq-m2crypto")
  368. @nox.parametrize("coverage", [False, True])
  369. def runtests_zeromq_m2crypto(session, coverage):
  370. """
  371. runtests.py session with zeromq transport and m2crypto
  372. """
  373. _runtests(session)
  374. @nox.session(python=_PYTHON_VERSIONS, name="runtests-pycryptodome")
  375. @nox.parametrize("coverage", [False, True])
  376. def runtests_pycryptodome(session, coverage):
  377. """
  378. runtests.py session with zeromq transport and pycryptodome
  379. """
  380. _runtests(session)
  381. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tcp-pycryptodome")
  382. @nox.parametrize("coverage", [False, True])
  383. def runtests_tcp_pycryptodome(session, coverage):
  384. """
  385. runtests.py session with TCP transport and pycryptodome
  386. """
  387. _runtests(session)
  388. @nox.session(python=_PYTHON_VERSIONS, name="runtests-zeromq-pycryptodome")
  389. @nox.parametrize("coverage", [False, True])
  390. def runtests_zeromq_pycryptodome(session, coverage):
  391. """
  392. runtests.py session with zeromq transport and pycryptodome
  393. """
  394. _runtests(session)
  395. @nox.session(python=_PYTHON_VERSIONS, name="runtests-cloud")
  396. @nox.parametrize("coverage", [False, True])
  397. def runtests_cloud(session, coverage):
  398. """
  399. runtests.py cloud tests session
  400. """
  401. _runtests(session)
  402. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tornado")
  403. @nox.parametrize("coverage", [False, True])
  404. def runtests_tornado(session, coverage):
  405. """
  406. runtests.py tornado tests session
  407. """
  408. _runtests(session)
  409. @nox.session(python=_PYTHON_VERSIONS, name="pytest-parametrized")
  410. @nox.parametrize("coverage", [False, True])
  411. @nox.parametrize("transport", ["zeromq", "tcp"])
  412. @nox.parametrize("crypto", [None, "m2crypto", "pycryptodome"])
  413. def pytest_parametrized(session, coverage, transport, crypto):
  414. """
  415. DO NOT CALL THIS NOX SESSION DIRECTLY
  416. """
  417. # Install requirements
  418. _install_requirements(session, transport)
  419. if crypto:
  420. session.run(
  421. "pip",
  422. "uninstall",
  423. "-y",
  424. "m2crypto",
  425. "pycrypto",
  426. "pycryptodome",
  427. "pycryptodomex",
  428. silent=True,
  429. )
  430. install_command = [
  431. "--progress-bar=off",
  432. "--constraint",
  433. _get_pip_requirements_file(session, transport, crypto=True),
  434. ]
  435. install_command.append(crypto)
  436. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  437. cmd_args = [
  438. "--rootdir",
  439. REPO_ROOT,
  440. "--log-file={}".format(RUNTESTS_LOGFILE),
  441. "--log-file-level=debug",
  442. "--show-capture=no",
  443. "-ra",
  444. "-s",
  445. "--transport={}".format(transport),
  446. ] + session.posargs
  447. _pytest(session, coverage, cmd_args)
  448. @nox.session(python=_PYTHON_VERSIONS)
  449. @nox.parametrize("coverage", [False, True])
  450. def pytest(session, coverage):
  451. """
  452. pytest session with zeromq transport and default crypto
  453. """
  454. session.notify(
  455. find_session_runner(
  456. session,
  457. "pytest-parametrized-{}".format(session.python),
  458. coverage=coverage,
  459. crypto=None,
  460. transport="zeromq",
  461. )
  462. )
  463. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tcp")
  464. @nox.parametrize("coverage", [False, True])
  465. def pytest_tcp(session, coverage):
  466. """
  467. pytest session with TCP transport and default crypto
  468. """
  469. session.notify(
  470. find_session_runner(
  471. session,
  472. "pytest-parametrized-{}".format(session.python),
  473. coverage=coverage,
  474. crypto=None,
  475. transport="tcp",
  476. )
  477. )
  478. @nox.session(python=_PYTHON_VERSIONS, name="pytest-zeromq")
  479. @nox.parametrize("coverage", [False, True])
  480. def pytest_zeromq(session, coverage):
  481. """
  482. pytest session with zeromq transport and default crypto
  483. """
  484. session.notify(
  485. find_session_runner(
  486. session,
  487. "pytest-parametrized-{}".format(session.python),
  488. coverage=coverage,
  489. crypto=None,
  490. transport="zeromq",
  491. )
  492. )
  493. @nox.session(python=_PYTHON_VERSIONS, name="pytest-m2crypto")
  494. @nox.parametrize("coverage", [False, True])
  495. def pytest_m2crypto(session, coverage):
  496. """
  497. pytest session with zeromq transport and m2crypto
  498. """
  499. session.notify(
  500. find_session_runner(
  501. session,
  502. "pytest-parametrized-{}".format(session.python),
  503. coverage=coverage,
  504. crypto="m2crypto",
  505. transport="zeromq",
  506. )
  507. )
  508. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tcp-m2crypto")
  509. @nox.parametrize("coverage", [False, True])
  510. def pytest_tcp_m2crypto(session, coverage):
  511. """
  512. pytest session with TCP transport and m2crypto
  513. """
  514. session.notify(
  515. find_session_runner(
  516. session,
  517. "pytest-parametrized-{}".format(session.python),
  518. coverage=coverage,
  519. crypto="m2crypto",
  520. transport="tcp",
  521. )
  522. )
  523. @nox.session(python=_PYTHON_VERSIONS, name="pytest-zeromq-m2crypto")
  524. @nox.parametrize("coverage", [False, True])
  525. def pytest_zeromq_m2crypto(session, coverage):
  526. """
  527. pytest session with zeromq transport and m2crypto
  528. """
  529. session.notify(
  530. find_session_runner(
  531. session,
  532. "pytest-parametrized-{}".format(session.python),
  533. coverage=coverage,
  534. crypto="m2crypto",
  535. transport="zeromq",
  536. )
  537. )
  538. @nox.session(python=_PYTHON_VERSIONS, name="pytest-pycryptodome")
  539. @nox.parametrize("coverage", [False, True])
  540. def pytest_pycryptodome(session, coverage):
  541. """
  542. pytest session with zeromq transport and pycryptodome
  543. """
  544. session.notify(
  545. find_session_runner(
  546. session,
  547. "pytest-parametrized-{}".format(session.python),
  548. coverage=coverage,
  549. crypto="pycryptodome",
  550. transport="zeromq",
  551. )
  552. )
  553. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tcp-pycryptodome")
  554. @nox.parametrize("coverage", [False, True])
  555. def pytest_tcp_pycryptodome(session, coverage):
  556. """
  557. pytest session with TCP transport and pycryptodome
  558. """
  559. session.notify(
  560. find_session_runner(
  561. session,
  562. "pytest-parametrized-{}".format(session.python),
  563. coverage=coverage,
  564. crypto="pycryptodome",
  565. transport="tcp",
  566. )
  567. )
  568. @nox.session(python=_PYTHON_VERSIONS, name="pytest-zeromq-pycryptodome")
  569. @nox.parametrize("coverage", [False, True])
  570. def pytest_zeromq_pycryptodome(session, coverage):
  571. """
  572. pytest session with zeromq transport and pycryptodome
  573. """
  574. session.notify(
  575. find_session_runner(
  576. session,
  577. "pytest-parametrized-{}".format(session.python),
  578. coverage=coverage,
  579. crypto="pycryptodome",
  580. transport="zeromq",
  581. )
  582. )
  583. @nox.session(python=_PYTHON_VERSIONS, name="pytest-cloud")
  584. @nox.parametrize("coverage", [False, True])
  585. def pytest_cloud(session, coverage):
  586. """
  587. pytest cloud tests session
  588. """
  589. # Install requirements
  590. _install_requirements(session, "zeromq")
  591. requirements_file = os.path.join(
  592. "requirements", "static", _get_pydir(session), "cloud.txt"
  593. )
  594. install_command = ["--progress-bar=off", "-r", requirements_file]
  595. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  596. cmd_args = [
  597. "--rootdir",
  598. REPO_ROOT,
  599. "--log-file={}".format(RUNTESTS_LOGFILE),
  600. "--log-file-level=debug",
  601. "--show-capture=no",
  602. "-ra",
  603. "-s",
  604. "--run-expensive",
  605. "-k",
  606. "cloud",
  607. ] + session.posargs
  608. _pytest(session, coverage, cmd_args)
  609. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tornado")
  610. @nox.parametrize("coverage", [False, True])
  611. def pytest_tornado(session, coverage):
  612. """
  613. pytest tornado tests session
  614. """
  615. # Install requirements
  616. _install_requirements(session, "zeromq")
  617. session.install("--progress-bar=off", "tornado==5.0.2", silent=PIP_INSTALL_SILENT)
  618. session.install("--progress-bar=off", "pyzmq==17.0.0", silent=PIP_INSTALL_SILENT)
  619. cmd_args = [
  620. "--rootdir",
  621. REPO_ROOT,
  622. "--log-file={}".format(RUNTESTS_LOGFILE),
  623. "--log-file-level=debug",
  624. "--show-capture=no",
  625. "-ra",
  626. "-s",
  627. ] + session.posargs
  628. _pytest(session, coverage, cmd_args)
  629. def _pytest(session, coverage, cmd_args):
  630. # Create required artifacts directories
  631. _create_ci_directories()
  632. env = None
  633. if IS_DARWIN:
  634. # Don't nuke our multiprocessing efforts objc!
  635. # https://stackoverflow.com/questions/50168647/multiprocessing-causes-python-to-crash-and-gives-an-error-may-have-been-in-progr
  636. env = {"OBJC_DISABLE_INITIALIZE_FORK_SAFETY": "YES"}
  637. if CI_RUN:
  638. # We'll print out the collected tests on CI runs.
  639. # This will show a full list of what tests are going to run, in the right order, which, in case
  640. # of a test suite hang, helps us pinpoint which test is hanging
  641. session.run(
  642. "python", "-m", "pytest", *(cmd_args + ["--collect-only", "-qqq"]), env=env
  643. )
  644. try:
  645. if coverage is True:
  646. _run_with_coverage(
  647. session,
  648. "python",
  649. "-m",
  650. "coverage",
  651. "run",
  652. "-m",
  653. "pytest",
  654. "--showlocals",
  655. *cmd_args
  656. )
  657. else:
  658. session.run("python", "-m", "pytest", *cmd_args, env=env)
  659. except CommandFailed: # pylint: disable=try-except-raise
  660. # Not rerunning failed tests for now
  661. raise
  662. # pylint: disable=unreachable
  663. # Re-run failed tests
  664. session.log("Re-running failed tests")
  665. for idx, parg in enumerate(cmd_args):
  666. if parg.startswith("--junitxml="):
  667. cmd_args[idx] = parg.replace(".xml", "-rerun-failed.xml")
  668. cmd_args.append("--lf")
  669. if coverage is True:
  670. _run_with_coverage(
  671. session,
  672. "python",
  673. "-m",
  674. "coverage",
  675. "run",
  676. "-m",
  677. "pytest",
  678. "--showlocals",
  679. *cmd_args
  680. )
  681. else:
  682. session.run("python", "-m", "pytest", *cmd_args, env=env)
  683. # pylint: enable=unreachable
  684. class Tee:
  685. """
  686. Python class to mimic linux tee behaviour
  687. """
  688. def __init__(self, first, second):
  689. self._first = first
  690. self._second = second
  691. def write(self, b):
  692. wrote = self._first.write(b)
  693. self._first.flush()
  694. self._second.write(b)
  695. self._second.flush()
  696. def fileno(self):
  697. return self._first.fileno()
  698. def _lint(session, rcfile, flags, paths, tee_output=True):
  699. _install_requirements(session, "zeromq")
  700. requirements_file = os.path.join(
  701. "requirements", "static", _get_pydir(session), "lint.txt"
  702. )
  703. install_command = ["--progress-bar=off", "-r", requirements_file]
  704. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  705. if tee_output:
  706. session.run("pylint", "--version")
  707. pylint_report_path = os.environ.get("PYLINT_REPORT")
  708. cmd_args = ["pylint", "--rcfile={}".format(rcfile)] + list(flags) + list(paths)
  709. cmd_kwargs = {"env": {"PYTHONUNBUFFERED": "1"}}
  710. if tee_output:
  711. stdout = tempfile.TemporaryFile(mode="w+b")
  712. cmd_kwargs["stdout"] = Tee(stdout, sys.__stdout__)
  713. lint_failed = False
  714. try:
  715. session.run(*cmd_args, **cmd_kwargs)
  716. except CommandFailed:
  717. lint_failed = True
  718. raise
  719. finally:
  720. if tee_output:
  721. stdout.seek(0)
  722. contents = stdout.read()
  723. if contents:
  724. if IS_PY3:
  725. contents = contents.decode("utf-8")
  726. else:
  727. contents = contents.encode("utf-8")
  728. sys.stdout.write(contents)
  729. sys.stdout.flush()
  730. if pylint_report_path:
  731. # Write report
  732. with open(pylint_report_path, "w") as wfh:
  733. wfh.write(contents)
  734. session.log("Report file written to %r", pylint_report_path)
  735. stdout.close()
  736. def _lint_pre_commit(session, rcfile, flags, paths):
  737. if "VIRTUAL_ENV" not in os.environ:
  738. session.error(
  739. "This should be running from within a virtualenv and "
  740. "'VIRTUAL_ENV' was not found as an environment variable."
  741. )
  742. if "pre-commit" not in os.environ["VIRTUAL_ENV"]:
  743. session.error(
  744. "This should be running from within a pre-commit virtualenv and "
  745. "'VIRTUAL_ENV'({}) does not appear to be a pre-commit virtualenv.".format(
  746. os.environ["VIRTUAL_ENV"]
  747. )
  748. )
  749. from nox.virtualenv import VirtualEnv
  750. # Let's patch nox to make it run inside the pre-commit virtualenv
  751. try:
  752. session._runner.venv = VirtualEnv( # pylint: disable=unexpected-keyword-arg
  753. os.environ["VIRTUAL_ENV"],
  754. interpreter=session._runner.func.python,
  755. reuse_existing=True,
  756. venv=True,
  757. )
  758. except TypeError:
  759. # This is still nox-py2
  760. session._runner.venv = VirtualEnv(
  761. os.environ["VIRTUAL_ENV"],
  762. interpreter=session._runner.func.python,
  763. reuse_existing=True,
  764. )
  765. _lint(session, rcfile, flags, paths, tee_output=False)
  766. @nox.session(python="3")
  767. def lint(session):
  768. """
  769. Run PyLint against Salt and it's test suite. Set PYLINT_REPORT to a path to capture output.
  770. """
  771. session.notify("lint-salt-{}".format(session.python))
  772. session.notify("lint-tests-{}".format(session.python))
  773. @nox.session(python="3", name="lint-salt")
  774. def lint_salt(session):
  775. """
  776. Run PyLint against Salt. Set PYLINT_REPORT to a path to capture output.
  777. """
  778. flags = ["--disable=I"]
  779. if session.posargs:
  780. paths = session.posargs
  781. else:
  782. paths = ["setup.py", "noxfile.py", "salt/", "tasks/"]
  783. _lint(session, ".pylintrc", flags, paths)
  784. @nox.session(python="3", name="lint-tests")
  785. def lint_tests(session):
  786. """
  787. Run PyLint against Salt and it's test suite. Set PYLINT_REPORT to a path to capture output.
  788. """
  789. flags = ["--disable=I"]
  790. if session.posargs:
  791. paths = session.posargs
  792. else:
  793. paths = ["tests/"]
  794. _lint(session, ".pylintrc", flags, paths)
  795. @nox.session(python=False, name="lint-salt-pre-commit")
  796. def lint_salt_pre_commit(session):
  797. """
  798. Run PyLint against Salt. Set PYLINT_REPORT to a path to capture output.
  799. """
  800. flags = ["--disable=I"]
  801. if session.posargs:
  802. paths = session.posargs
  803. else:
  804. paths = ["setup.py", "noxfile.py", "salt/"]
  805. _lint_pre_commit(session, ".pylintrc", flags, paths)
  806. @nox.session(python=False, name="lint-tests-pre-commit")
  807. def lint_tests_pre_commit(session):
  808. """
  809. Run PyLint against Salt and it's test suite. Set PYLINT_REPORT to a path to capture output.
  810. """
  811. flags = ["--disable=I"]
  812. if session.posargs:
  813. paths = session.posargs
  814. else:
  815. paths = ["tests/"]
  816. _lint_pre_commit(session, ".pylintrc", flags, paths)
  817. @nox.session(python="3")
  818. @nox.parametrize("update", [False, True])
  819. @nox.parametrize("compress", [False, True])
  820. def docs(session, compress, update):
  821. """
  822. Build Salt's Documentation
  823. """
  824. session.notify("docs-html-{}(compress={})".format(session.python, compress))
  825. session.notify(
  826. find_session_runner(
  827. session,
  828. "docs-man-{}".format(session.python),
  829. compress=compress,
  830. update=update,
  831. )
  832. )
  833. @nox.session(name="docs-html", python="3")
  834. @nox.parametrize("compress", [False, True])
  835. def docs_html(session, compress):
  836. """
  837. Build Salt's HTML Documentation
  838. """
  839. pydir = _get_pydir(session)
  840. requirements_file = os.path.join(
  841. "requirements", "static", _get_pydir(session), "docs.txt"
  842. )
  843. install_command = ["--progress-bar=off", "-r", requirements_file]
  844. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  845. os.chdir("doc/")
  846. session.run("make", "clean", external=True)
  847. session.run("make", "html", "SPHINXOPTS=-W", external=True)
  848. if compress:
  849. session.run("tar", "-cJvf", "html-archive.tar.xz", "_build/html", external=True)
  850. os.chdir("..")
  851. @nox.session(name="docs-man", python="3")
  852. @nox.parametrize("update", [False, True])
  853. @nox.parametrize("compress", [False, True])
  854. def docs_man(session, compress, update):
  855. """
  856. Build Salt's Manpages Documentation
  857. """
  858. pydir = _get_pydir(session)
  859. requirements_file = os.path.join(
  860. "requirements", "static", _get_pydir(session), "docs.txt"
  861. )
  862. install_command = ["--progress-bar=off", "-r", requirements_file]
  863. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  864. os.chdir("doc/")
  865. session.run("make", "clean", external=True)
  866. session.run("make", "man", "SPHINXOPTS=-W", external=True)
  867. if update:
  868. session.run("rm", "-rf", "man/", external=True)
  869. session.run("cp", "-Rp", "_build/man", "man/", external=True)
  870. if compress:
  871. session.run("tar", "-cJvf", "man-archive.tar.xz", "_build/man", external=True)
  872. os.chdir("..")
  873. def _invoke(session):
  874. """
  875. Run invoke tasks
  876. """
  877. requirements_file = os.path.join(
  878. "requirements", "static", _get_pydir(session), "invoke.txt"
  879. )
  880. install_command = ["--progress-bar=off", "-r", requirements_file]
  881. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  882. cmd = ["inv"]
  883. files = []
  884. # Unfortunately, invoke doesn't support the nargs functionality like argpase does.
  885. # Let's make it behave properly
  886. for idx, posarg in enumerate(session.posargs):
  887. if idx == 0:
  888. cmd.append(posarg)
  889. continue
  890. if posarg.startswith("--"):
  891. cmd.append(posarg)
  892. continue
  893. files.append(posarg)
  894. if files:
  895. cmd.append("--files={}".format(" ".join(files)))
  896. session.run(*cmd)
  897. @nox.session(name="invoke", python="3")
  898. def invoke(session):
  899. """
  900. Run an invoke target
  901. """
  902. _invoke(session)
  903. @nox.session(name="invoke-pre-commit", python="3")
  904. def invoke_pre_commit(session):
  905. """
  906. DO NOT CALL THIS NOX SESSION DIRECTLY
  907. This session is called from a pre-commit hook
  908. """
  909. if "VIRTUAL_ENV" not in os.environ:
  910. session.error(
  911. "This should be running from within a virtualenv and "
  912. "'VIRTUAL_ENV' was not found as an environment variable."
  913. )
  914. if "pre-commit" not in os.environ["VIRTUAL_ENV"]:
  915. session.error(
  916. "This should be running from within a pre-commit virtualenv and "
  917. "'VIRTUAL_ENV'({}) does not appear to be a pre-commit virtualenv.".format(
  918. os.environ["VIRTUAL_ENV"]
  919. )
  920. )
  921. from nox.virtualenv import VirtualEnv
  922. # Let's patch nox to make it run inside the pre-commit virtualenv
  923. try:
  924. session._runner.venv = VirtualEnv( # pylint: disable=unexpected-keyword-arg
  925. os.environ["VIRTUAL_ENV"],
  926. interpreter=session._runner.func.python,
  927. reuse_existing=True,
  928. venv=True,
  929. )
  930. except TypeError:
  931. # This is still nox-py2
  932. session._runner.venv = VirtualEnv(
  933. os.environ["VIRTUAL_ENV"],
  934. interpreter=session._runner.func.python,
  935. reuse_existing=True,
  936. )
  937. _invoke(session)
  938. @nox.session(name="changelog", python="3")
  939. @nox.parametrize("draft", [False, True])
  940. def changelog(session, draft):
  941. """
  942. Generate salt's changelog
  943. """
  944. requirements_file = os.path.join(
  945. "requirements", "static", _get_pydir(session), "changelog.txt"
  946. )
  947. install_command = ["--progress-bar=off", "-r", requirements_file]
  948. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  949. town_cmd = ["towncrier", "--version={}".format(session.posargs[0])]
  950. if draft:
  951. town_cmd.append("--draft")
  952. session.run(*town_cmd)