noxfile.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  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. # Install requirements
  234. requirements_file = _get_pip_requirements_file(session, transport)
  235. install_command = [
  236. "--progress-bar=off",
  237. "-r",
  238. requirements_file,
  239. ]
  240. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  241. if extra_requirements:
  242. install_command = [
  243. "--progress-bar=off",
  244. ]
  245. install_command += list(extra_requirements)
  246. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  247. if EXTRA_REQUIREMENTS_INSTALL:
  248. session.log(
  249. "Installing the following extra requirements because the EXTRA_REQUIREMENTS_INSTALL environment variable "
  250. "was set: %s",
  251. EXTRA_REQUIREMENTS_INSTALL,
  252. )
  253. # We pass --constraint in this step because in case any of these extra dependencies has a requirement
  254. # we're already using, we want to maintain the locked version
  255. install_command = ["--progress-bar=off", "--constraint", requirements_file]
  256. install_command += EXTRA_REQUIREMENTS_INSTALL.split()
  257. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  258. def _run_with_coverage(session, *test_cmd):
  259. if SKIP_REQUIREMENTS_INSTALL is False:
  260. session.install(
  261. "--progress-bar=off", "coverage==5.2", silent=PIP_INSTALL_SILENT
  262. )
  263. session.run("coverage", "erase")
  264. python_path_env_var = os.environ.get("PYTHONPATH") or None
  265. if python_path_env_var is None:
  266. python_path_env_var = SITECUSTOMIZE_DIR
  267. else:
  268. python_path_entries = python_path_env_var.split(os.pathsep)
  269. if SITECUSTOMIZE_DIR in python_path_entries:
  270. python_path_entries.remove(SITECUSTOMIZE_DIR)
  271. python_path_entries.insert(0, SITECUSTOMIZE_DIR)
  272. python_path_env_var = os.pathsep.join(python_path_entries)
  273. env = {
  274. # The updated python path so that sitecustomize is importable
  275. "PYTHONPATH": python_path_env_var,
  276. # The full path to the .coverage data file. Makes sure we always write
  277. # them to the same directory
  278. "COVERAGE_FILE": os.path.abspath(os.path.join(REPO_ROOT, ".coverage")),
  279. # Instruct sub processes to also run under coverage
  280. "COVERAGE_PROCESS_START": os.path.join(REPO_ROOT, ".coveragerc"),
  281. }
  282. if IS_DARWIN:
  283. # Don't nuke our multiprocessing efforts objc!
  284. # https://stackoverflow.com/questions/50168647/multiprocessing-causes-python-to-crash-and-gives-an-error-may-have-been-in-progr
  285. env["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"
  286. try:
  287. session.run(*test_cmd, env=env)
  288. finally:
  289. # Always combine and generate the XML coverage report
  290. try:
  291. session.run("coverage", "combine")
  292. except CommandFailed:
  293. # Sometimes some of the coverage files are corrupt which would trigger a CommandFailed
  294. # exception
  295. pass
  296. # Generate report for salt code coverage
  297. session.run(
  298. "coverage",
  299. "xml",
  300. "-o",
  301. os.path.join("artifacts", "coverage", "salt.xml"),
  302. "--omit=tests/*",
  303. "--include=salt/*",
  304. )
  305. # Generate report for tests code coverage
  306. session.run(
  307. "coverage",
  308. "xml",
  309. "-o",
  310. os.path.join("artifacts", "coverage", "tests.xml"),
  311. "--omit=salt/*",
  312. "--include=tests/*",
  313. )
  314. # Move the coverage DB to artifacts/coverage in order for it to be archived by CI
  315. shutil.move(".coverage", os.path.join("artifacts", "coverage", ".coverage"))
  316. def _runtests(session, coverage, cmd_args):
  317. # Create required artifacts directories
  318. _create_ci_directories()
  319. try:
  320. if coverage is True:
  321. _run_with_coverage(
  322. session,
  323. "coverage",
  324. "run",
  325. os.path.join("tests", "runtests.py"),
  326. *cmd_args
  327. )
  328. else:
  329. cmd_args = ["python", os.path.join("tests", "runtests.py")] + list(cmd_args)
  330. env = None
  331. if IS_DARWIN:
  332. # Don't nuke our multiprocessing efforts objc!
  333. # https://stackoverflow.com/questions/50168647/multiprocessing-causes-python-to-crash-and-gives-an-error-may-have-been-in-progr
  334. env = {"OBJC_DISABLE_INITIALIZE_FORK_SAFETY": "YES"}
  335. session.run(*cmd_args, env=env)
  336. except CommandFailed: # pylint: disable=try-except-raise
  337. # Disabling re-running failed tests for the time being
  338. raise
  339. # pylint: disable=unreachable
  340. names_file_path = os.path.join("artifacts", "failed-tests.txt")
  341. session.log("Re-running failed tests if possible")
  342. session.install(
  343. "--progress-bar=off", "xunitparser==1.3.3", silent=PIP_INSTALL_SILENT
  344. )
  345. session.run(
  346. "python",
  347. os.path.join(
  348. "tests", "support", "generate-names-file-from-failed-test-reports.py"
  349. ),
  350. names_file_path,
  351. )
  352. if not os.path.exists(names_file_path):
  353. session.log(
  354. "Failed tests file(%s) was not found. Not rerunning failed tests.",
  355. names_file_path,
  356. )
  357. # raise the original exception
  358. raise
  359. with open(names_file_path) as rfh:
  360. contents = rfh.read().strip()
  361. if not contents:
  362. session.log(
  363. "The failed tests file(%s) is empty. Not rerunning failed tests.",
  364. names_file_path,
  365. )
  366. # raise the original exception
  367. raise
  368. failed_tests_count = len(contents.splitlines())
  369. if failed_tests_count > 500:
  370. # 500 test failures?! Something else must have gone wrong, don't even bother
  371. session.error(
  372. "Total failed tests({}) > 500. No point on re-running the failed tests".format(
  373. failed_tests_count
  374. )
  375. )
  376. for idx, flag in enumerate(cmd_args[:]):
  377. if "--names-file=" in flag:
  378. cmd_args.pop(idx)
  379. break
  380. elif flag == "--names-file":
  381. cmd_args.pop(idx) # pop --names-file
  382. cmd_args.pop(idx) # pop the actual names file
  383. break
  384. cmd_args.append("--names-file={}".format(names_file_path))
  385. if coverage is True:
  386. _run_with_coverage(
  387. session, "coverage", "run", "-m", "tests.runtests", *cmd_args
  388. )
  389. else:
  390. session.run("python", os.path.join("tests", "runtests.py"), *cmd_args)
  391. # pylint: enable=unreachable
  392. @nox.session(python=_PYTHON_VERSIONS, name="runtests-parametrized")
  393. @nox.parametrize("coverage", [False, True])
  394. @nox.parametrize("transport", ["zeromq", "tcp"])
  395. @nox.parametrize("crypto", [None, "m2crypto", "pycryptodome"])
  396. def runtests_parametrized(session, coverage, transport, crypto):
  397. """
  398. DO NOT CALL THIS NOX SESSION DIRECTLY
  399. """
  400. # Install requirements
  401. _install_requirements(session, transport, "unittest-xml-reporting==2.5.2")
  402. if crypto:
  403. session.run(
  404. "pip",
  405. "uninstall",
  406. "-y",
  407. "m2crypto",
  408. "pycrypto",
  409. "pycryptodome",
  410. "pycryptodomex",
  411. silent=True,
  412. )
  413. install_command = [
  414. "--progress-bar=off",
  415. "--constraint",
  416. _get_pip_requirements_file(session, transport, crypto=True),
  417. ]
  418. install_command.append(crypto)
  419. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  420. cmd_args = [
  421. "--tests-logfile={}".format(RUNTESTS_LOGFILE),
  422. "--transport={}".format(transport),
  423. ] + session.posargs
  424. _runtests(session, coverage, cmd_args)
  425. @nox.session(python=_PYTHON_VERSIONS)
  426. @nox.parametrize("coverage", [False, True])
  427. def runtests(session, coverage):
  428. """
  429. runtests.py session with zeromq transport and default crypto
  430. """
  431. session.notify(
  432. find_session_runner(
  433. session,
  434. "runtests-parametrized-{}".format(session.python),
  435. coverage=coverage,
  436. crypto=None,
  437. transport="zeromq",
  438. )
  439. )
  440. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tcp")
  441. @nox.parametrize("coverage", [False, True])
  442. def runtests_tcp(session, coverage):
  443. """
  444. runtests.py session with TCP transport and default crypto
  445. """
  446. session.notify(
  447. find_session_runner(
  448. session,
  449. "runtests-parametrized-{}".format(session.python),
  450. coverage=coverage,
  451. crypto=None,
  452. transport="tcp",
  453. )
  454. )
  455. @nox.session(python=_PYTHON_VERSIONS, name="runtests-zeromq")
  456. @nox.parametrize("coverage", [False, True])
  457. def runtests_zeromq(session, coverage):
  458. """
  459. runtests.py session with zeromq transport and default crypto
  460. """
  461. session.notify(
  462. find_session_runner(
  463. session,
  464. "runtests-parametrized-{}".format(session.python),
  465. coverage=coverage,
  466. crypto=None,
  467. transport="zeromq",
  468. )
  469. )
  470. @nox.session(python=_PYTHON_VERSIONS, name="runtests-m2crypto")
  471. @nox.parametrize("coverage", [False, True])
  472. def runtests_m2crypto(session, coverage):
  473. """
  474. runtests.py session with zeromq transport and m2crypto
  475. """
  476. session.notify(
  477. find_session_runner(
  478. session,
  479. "runtests-parametrized-{}".format(session.python),
  480. coverage=coverage,
  481. crypto="m2crypto",
  482. transport="zeromq",
  483. )
  484. )
  485. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tcp-m2crypto")
  486. @nox.parametrize("coverage", [False, True])
  487. def runtests_tcp_m2crypto(session, coverage):
  488. """
  489. runtests.py session with TCP transport and m2crypto
  490. """
  491. session.notify(
  492. find_session_runner(
  493. session,
  494. "runtests-parametrized-{}".format(session.python),
  495. coverage=coverage,
  496. crypto="m2crypto",
  497. transport="tco",
  498. )
  499. )
  500. @nox.session(python=_PYTHON_VERSIONS, name="runtests-zeromq-m2crypto")
  501. @nox.parametrize("coverage", [False, True])
  502. def runtests_zeromq_m2crypto(session, coverage):
  503. """
  504. runtests.py session with zeromq transport and m2crypto
  505. """
  506. session.notify(
  507. find_session_runner(
  508. session,
  509. "runtests-parametrized-{}".format(session.python),
  510. coverage=coverage,
  511. crypto="m2crypto",
  512. transport="zeromq",
  513. )
  514. )
  515. @nox.session(python=_PYTHON_VERSIONS, name="runtests-pycryptodome")
  516. @nox.parametrize("coverage", [False, True])
  517. def runtests_pycryptodome(session, coverage):
  518. """
  519. runtests.py session with zeromq transport and pycryptodome
  520. """
  521. session.notify(
  522. find_session_runner(
  523. session,
  524. "runtests-parametrized-{}".format(session.python),
  525. coverage=coverage,
  526. crypto="pycryptodome",
  527. transport="zeromq",
  528. )
  529. )
  530. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tcp-pycryptodome")
  531. @nox.parametrize("coverage", [False, True])
  532. def runtests_tcp_pycryptodome(session, coverage):
  533. """
  534. runtests.py session with TCP transport and pycryptodome
  535. """
  536. session.notify(
  537. find_session_runner(
  538. session,
  539. "runtests-parametrized-{}".format(session.python),
  540. coverage=coverage,
  541. crypto="pycryptodome",
  542. transport="tcp",
  543. )
  544. )
  545. @nox.session(python=_PYTHON_VERSIONS, name="runtests-zeromq-pycryptodome")
  546. @nox.parametrize("coverage", [False, True])
  547. def runtests_zeromq_pycryptodome(session, coverage):
  548. """
  549. runtests.py session with zeromq transport and pycryptodome
  550. """
  551. session.notify(
  552. find_session_runner(
  553. session,
  554. "runtests-parametrized-{}".format(session.python),
  555. coverage=coverage,
  556. crypto="pycryptodome",
  557. transport="zeromq",
  558. )
  559. )
  560. @nox.session(python=_PYTHON_VERSIONS, name="runtests-cloud")
  561. @nox.parametrize("coverage", [False, True])
  562. def runtests_cloud(session, coverage):
  563. """
  564. runtests.py cloud tests session
  565. """
  566. # Install requirements
  567. _install_requirements(session, "zeromq", "unittest-xml-reporting==2.2.1")
  568. requirements_file = os.path.join(
  569. "requirements", "static", _get_pydir(session), "cloud.txt"
  570. )
  571. install_command = ["--progress-bar=off", "-r", requirements_file]
  572. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  573. cmd_args = [
  574. "--tests-logfile={}".format(RUNTESTS_LOGFILE),
  575. "--cloud-provider-tests",
  576. ] + session.posargs
  577. _runtests(session, coverage, cmd_args)
  578. @nox.session(python=_PYTHON_VERSIONS, name="runtests-tornado")
  579. @nox.parametrize("coverage", [False, True])
  580. def runtests_tornado(session, coverage):
  581. """
  582. runtests.py tornado tests session
  583. """
  584. # Install requirements
  585. _install_requirements(session, "zeromq", "unittest-xml-reporting==2.2.1")
  586. session.install("--progress-bar=off", "tornado==5.0.2", silent=PIP_INSTALL_SILENT)
  587. session.install("--progress-bar=off", "pyzmq==17.0.0", silent=PIP_INSTALL_SILENT)
  588. cmd_args = ["--tests-logfile={}".format(RUNTESTS_LOGFILE)] + session.posargs
  589. _runtests(session, coverage, cmd_args)
  590. @nox.session(python=_PYTHON_VERSIONS, name="pytest-parametrized")
  591. @nox.parametrize("coverage", [False, True])
  592. @nox.parametrize("transport", ["zeromq", "tcp"])
  593. @nox.parametrize("crypto", [None, "m2crypto", "pycryptodome"])
  594. def pytest_parametrized(session, coverage, transport, crypto):
  595. """
  596. DO NOT CALL THIS NOX SESSION DIRECTLY
  597. """
  598. # Install requirements
  599. _install_requirements(session, transport)
  600. if crypto:
  601. session.run(
  602. "pip",
  603. "uninstall",
  604. "-y",
  605. "m2crypto",
  606. "pycrypto",
  607. "pycryptodome",
  608. "pycryptodomex",
  609. silent=True,
  610. )
  611. install_command = [
  612. "--progress-bar=off",
  613. "--constraint",
  614. _get_pip_requirements_file(session, transport, crypto=True),
  615. ]
  616. install_command.append(crypto)
  617. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  618. cmd_args = [
  619. "--rootdir",
  620. REPO_ROOT,
  621. "--log-file={}".format(RUNTESTS_LOGFILE),
  622. "--log-file-level=debug",
  623. "--show-capture=no",
  624. "-ra",
  625. "-s",
  626. "--transport={}".format(transport),
  627. ] + session.posargs
  628. _pytest(session, coverage, cmd_args)
  629. @nox.session(python=_PYTHON_VERSIONS)
  630. @nox.parametrize("coverage", [False, True])
  631. def pytest(session, coverage):
  632. """
  633. pytest session with zeromq transport and default crypto
  634. """
  635. session.notify(
  636. find_session_runner(
  637. session,
  638. "pytest-parametrized-{}".format(session.python),
  639. coverage=coverage,
  640. crypto=None,
  641. transport="zeromq",
  642. )
  643. )
  644. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tcp")
  645. @nox.parametrize("coverage", [False, True])
  646. def pytest_tcp(session, coverage):
  647. """
  648. pytest session with TCP transport and default crypto
  649. """
  650. session.notify(
  651. find_session_runner(
  652. session,
  653. "pytest-parametrized-{}".format(session.python),
  654. coverage=coverage,
  655. crypto=None,
  656. transport="tcp",
  657. )
  658. )
  659. @nox.session(python=_PYTHON_VERSIONS, name="pytest-zeromq")
  660. @nox.parametrize("coverage", [False, True])
  661. def pytest_zeromq(session, coverage):
  662. """
  663. pytest session with zeromq transport and default crypto
  664. """
  665. session.notify(
  666. find_session_runner(
  667. session,
  668. "pytest-parametrized-{}".format(session.python),
  669. coverage=coverage,
  670. crypto=None,
  671. transport="zeromq",
  672. )
  673. )
  674. @nox.session(python=_PYTHON_VERSIONS, name="pytest-m2crypto")
  675. @nox.parametrize("coverage", [False, True])
  676. def pytest_m2crypto(session, coverage):
  677. """
  678. pytest session with zeromq transport and m2crypto
  679. """
  680. session.notify(
  681. find_session_runner(
  682. session,
  683. "pytest-parametrized-{}".format(session.python),
  684. coverage=coverage,
  685. crypto="m2crypto",
  686. transport="zeromq",
  687. )
  688. )
  689. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tcp-m2crypto")
  690. @nox.parametrize("coverage", [False, True])
  691. def pytest_tcp_m2crypto(session, coverage):
  692. """
  693. pytest session with TCP transport and m2crypto
  694. """
  695. session.notify(
  696. find_session_runner(
  697. session,
  698. "pytest-parametrized-{}".format(session.python),
  699. coverage=coverage,
  700. crypto="m2crypto",
  701. transport="tcp",
  702. )
  703. )
  704. @nox.session(python=_PYTHON_VERSIONS, name="pytest-zeromq-m2crypto")
  705. @nox.parametrize("coverage", [False, True])
  706. def pytest_zeromq_m2crypto(session, coverage):
  707. """
  708. pytest session with zeromq transport and m2crypto
  709. """
  710. session.notify(
  711. find_session_runner(
  712. session,
  713. "pytest-parametrized-{}".format(session.python),
  714. coverage=coverage,
  715. crypto="m2crypto",
  716. transport="zeromq",
  717. )
  718. )
  719. @nox.session(python=_PYTHON_VERSIONS, name="pytest-pycryptodome")
  720. @nox.parametrize("coverage", [False, True])
  721. def pytest_pycryptodome(session, coverage):
  722. """
  723. pytest session with zeromq transport and pycryptodome
  724. """
  725. session.notify(
  726. find_session_runner(
  727. session,
  728. "pytest-parametrized-{}".format(session.python),
  729. coverage=coverage,
  730. crypto="pycryptodome",
  731. transport="zeromq",
  732. )
  733. )
  734. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tcp-pycryptodome")
  735. @nox.parametrize("coverage", [False, True])
  736. def pytest_tcp_pycryptodome(session, coverage):
  737. """
  738. pytest session with TCP transport and pycryptodome
  739. """
  740. session.notify(
  741. find_session_runner(
  742. session,
  743. "pytest-parametrized-{}".format(session.python),
  744. coverage=coverage,
  745. crypto="pycryptodome",
  746. transport="tcp",
  747. )
  748. )
  749. @nox.session(python=_PYTHON_VERSIONS, name="pytest-zeromq-pycryptodome")
  750. @nox.parametrize("coverage", [False, True])
  751. def pytest_zeromq_pycryptodome(session, coverage):
  752. """
  753. pytest session with zeromq transport and pycryptodome
  754. """
  755. session.notify(
  756. find_session_runner(
  757. session,
  758. "pytest-parametrized-{}".format(session.python),
  759. coverage=coverage,
  760. crypto="pycryptodome",
  761. transport="zeromq",
  762. )
  763. )
  764. @nox.session(python=_PYTHON_VERSIONS, name="pytest-cloud")
  765. @nox.parametrize("coverage", [False, True])
  766. def pytest_cloud(session, coverage):
  767. """
  768. pytest cloud tests session
  769. """
  770. # Install requirements
  771. _install_requirements(session, "zeromq")
  772. requirements_file = os.path.join(
  773. "requirements", "static", _get_pydir(session), "cloud.txt"
  774. )
  775. install_command = ["--progress-bar=off", "-r", requirements_file]
  776. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  777. cmd_args = [
  778. "--rootdir",
  779. REPO_ROOT,
  780. "--log-file={}".format(RUNTESTS_LOGFILE),
  781. "--log-file-level=debug",
  782. "--show-capture=no",
  783. "-ra",
  784. "-s",
  785. "--run-expensive",
  786. "-k",
  787. "cloud",
  788. ] + session.posargs
  789. _pytest(session, coverage, cmd_args)
  790. @nox.session(python=_PYTHON_VERSIONS, name="pytest-tornado")
  791. @nox.parametrize("coverage", [False, True])
  792. def pytest_tornado(session, coverage):
  793. """
  794. pytest tornado tests session
  795. """
  796. # Install requirements
  797. _install_requirements(session, "zeromq")
  798. session.install("--progress-bar=off", "tornado==5.0.2", silent=PIP_INSTALL_SILENT)
  799. session.install("--progress-bar=off", "pyzmq==17.0.0", silent=PIP_INSTALL_SILENT)
  800. cmd_args = [
  801. "--rootdir",
  802. REPO_ROOT,
  803. "--log-file={}".format(RUNTESTS_LOGFILE),
  804. "--log-file-level=debug",
  805. "--show-capture=no",
  806. "-ra",
  807. "-s",
  808. ] + session.posargs
  809. _pytest(session, coverage, cmd_args)
  810. def _pytest(session, coverage, cmd_args):
  811. # Create required artifacts directories
  812. _create_ci_directories()
  813. session.run(
  814. "pip", "uninstall", "-y", "pytest-salt", silent=True,
  815. )
  816. env = None
  817. if IS_DARWIN:
  818. # Don't nuke our multiprocessing efforts objc!
  819. # https://stackoverflow.com/questions/50168647/multiprocessing-causes-python-to-crash-and-gives-an-error-may-have-been-in-progr
  820. env = {"OBJC_DISABLE_INITIALIZE_FORK_SAFETY": "YES"}
  821. if CI_RUN:
  822. # We'll print out the collected tests on CI runs.
  823. # This will show a full list of what tests are going to run, in the right order, which, in case
  824. # of a test suite hang, helps us pinpoint which test is hanging
  825. session.run(
  826. "python", "-m", "pytest", *(cmd_args + ["--collect-only", "-qqq"]), env=env
  827. )
  828. try:
  829. if coverage is True:
  830. _run_with_coverage(
  831. session, "python", "-m", "coverage", "run", "-m", "pytest", *cmd_args
  832. )
  833. else:
  834. session.run("python", "-m", "pytest", *cmd_args, env=env)
  835. except CommandFailed: # pylint: disable=try-except-raise
  836. # Not rerunning failed tests for now
  837. raise
  838. # pylint: disable=unreachable
  839. # Re-run failed tests
  840. session.log("Re-running failed tests")
  841. for idx, parg in enumerate(cmd_args):
  842. if parg.startswith("--junitxml="):
  843. cmd_args[idx] = parg.replace(".xml", "-rerun-failed.xml")
  844. cmd_args.append("--lf")
  845. if coverage is True:
  846. _run_with_coverage(
  847. session,
  848. "python",
  849. "-m",
  850. "coverage",
  851. "run",
  852. "-m",
  853. "pytest",
  854. "--showlocals",
  855. *cmd_args
  856. )
  857. else:
  858. session.run("python", "-m", "pytest", *cmd_args, env=env)
  859. # pylint: enable=unreachable
  860. class Tee:
  861. """
  862. Python class to mimic linux tee behaviour
  863. """
  864. def __init__(self, first, second):
  865. self._first = first
  866. self._second = second
  867. def write(self, b):
  868. wrote = self._first.write(b)
  869. self._first.flush()
  870. self._second.write(b)
  871. self._second.flush()
  872. def fileno(self):
  873. return self._first.fileno()
  874. def _lint(session, rcfile, flags, paths, tee_output=True):
  875. _install_requirements(session, "zeromq")
  876. requirements_file = os.path.join(
  877. "requirements", "static", _get_pydir(session), "lint.txt"
  878. )
  879. install_command = ["--progress-bar=off", "-r", requirements_file]
  880. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  881. if tee_output:
  882. session.run("pylint", "--version")
  883. pylint_report_path = os.environ.get("PYLINT_REPORT")
  884. cmd_args = ["pylint", "--rcfile={}".format(rcfile)] + list(flags) + list(paths)
  885. cmd_kwargs = {"env": {"PYTHONUNBUFFERED": "1"}}
  886. if tee_output:
  887. stdout = tempfile.TemporaryFile(mode="w+b")
  888. cmd_kwargs["stdout"] = Tee(stdout, sys.__stdout__)
  889. lint_failed = False
  890. try:
  891. session.run(*cmd_args, **cmd_kwargs)
  892. except CommandFailed:
  893. lint_failed = True
  894. raise
  895. finally:
  896. if tee_output:
  897. stdout.seek(0)
  898. contents = stdout.read()
  899. if contents:
  900. if IS_PY3:
  901. contents = contents.decode("utf-8")
  902. else:
  903. contents = contents.encode("utf-8")
  904. sys.stdout.write(contents)
  905. sys.stdout.flush()
  906. if pylint_report_path:
  907. # Write report
  908. with open(pylint_report_path, "w") as wfh:
  909. wfh.write(contents)
  910. session.log("Report file written to %r", pylint_report_path)
  911. stdout.close()
  912. def _lint_pre_commit(session, rcfile, flags, paths):
  913. if "VIRTUAL_ENV" not in os.environ:
  914. session.error(
  915. "This should be running from within a virtualenv and "
  916. "'VIRTUAL_ENV' was not found as an environment variable."
  917. )
  918. if "pre-commit" not in os.environ["VIRTUAL_ENV"]:
  919. session.error(
  920. "This should be running from within a pre-commit virtualenv and "
  921. "'VIRTUAL_ENV'({}) does not appear to be a pre-commit virtualenv.".format(
  922. os.environ["VIRTUAL_ENV"]
  923. )
  924. )
  925. from nox.virtualenv import VirtualEnv
  926. # Let's patch nox to make it run inside the pre-commit virtualenv
  927. try:
  928. session._runner.venv = VirtualEnv( # pylint: disable=unexpected-keyword-arg
  929. os.environ["VIRTUAL_ENV"],
  930. interpreter=session._runner.func.python,
  931. reuse_existing=True,
  932. venv=True,
  933. )
  934. except TypeError:
  935. # This is still nox-py2
  936. session._runner.venv = VirtualEnv(
  937. os.environ["VIRTUAL_ENV"],
  938. interpreter=session._runner.func.python,
  939. reuse_existing=True,
  940. )
  941. _lint(session, rcfile, flags, paths, tee_output=False)
  942. @nox.session(python="3")
  943. def lint(session):
  944. """
  945. Run PyLint against Salt and it's test suite. Set PYLINT_REPORT to a path to capture output.
  946. """
  947. session.notify("lint-salt-{}".format(session.python))
  948. session.notify("lint-tests-{}".format(session.python))
  949. @nox.session(python="3", name="lint-salt")
  950. def lint_salt(session):
  951. """
  952. Run PyLint against Salt. Set PYLINT_REPORT to a path to capture output.
  953. """
  954. flags = ["--disable=I"]
  955. if session.posargs:
  956. paths = session.posargs
  957. else:
  958. paths = ["setup.py", "noxfile.py", "salt/", "tasks/"]
  959. _lint(session, ".pylintrc", flags, paths)
  960. @nox.session(python="3", name="lint-tests")
  961. def lint_tests(session):
  962. """
  963. Run PyLint against Salt and it's test suite. Set PYLINT_REPORT to a path to capture output.
  964. """
  965. flags = ["--disable=I"]
  966. if session.posargs:
  967. paths = session.posargs
  968. else:
  969. paths = ["tests/"]
  970. _lint(session, ".pylintrc", flags, paths)
  971. @nox.session(python=False, name="lint-salt-pre-commit")
  972. def lint_salt_pre_commit(session):
  973. """
  974. Run PyLint against Salt. Set PYLINT_REPORT to a path to capture output.
  975. """
  976. flags = ["--disable=I"]
  977. if session.posargs:
  978. paths = session.posargs
  979. else:
  980. paths = ["setup.py", "noxfile.py", "salt/"]
  981. _lint_pre_commit(session, ".pylintrc", flags, paths)
  982. @nox.session(python=False, name="lint-tests-pre-commit")
  983. def lint_tests_pre_commit(session):
  984. """
  985. Run PyLint against Salt and it's test suite. Set PYLINT_REPORT to a path to capture output.
  986. """
  987. flags = ["--disable=I"]
  988. if session.posargs:
  989. paths = session.posargs
  990. else:
  991. paths = ["tests/"]
  992. _lint_pre_commit(session, ".pylintrc", flags, paths)
  993. @nox.session(python="3")
  994. @nox.parametrize("update", [False, True])
  995. @nox.parametrize("compress", [False, True])
  996. def docs(session, compress, update):
  997. """
  998. Build Salt's Documentation
  999. """
  1000. session.notify("docs-html-{}(compress={})".format(session.python, compress))
  1001. session.notify(
  1002. find_session_runner(
  1003. session,
  1004. "docs-man-{}".format(session.python),
  1005. compress=compress,
  1006. update=update,
  1007. )
  1008. )
  1009. @nox.session(name="docs-html", python="3")
  1010. @nox.parametrize("compress", [False, True])
  1011. def docs_html(session, compress):
  1012. """
  1013. Build Salt's HTML Documentation
  1014. """
  1015. pydir = _get_pydir(session)
  1016. requirements_file = os.path.join(
  1017. "requirements", "static", _get_pydir(session), "docs.txt"
  1018. )
  1019. install_command = ["--progress-bar=off", "-r", requirements_file]
  1020. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  1021. os.chdir("doc/")
  1022. session.run("make", "clean", external=True)
  1023. session.run("make", "html", "SPHINXOPTS=-W", external=True)
  1024. if compress:
  1025. session.run("tar", "-cJvf", "html-archive.tar.xz", "_build/html", external=True)
  1026. os.chdir("..")
  1027. @nox.session(name="docs-man", python="3")
  1028. @nox.parametrize("update", [False, True])
  1029. @nox.parametrize("compress", [False, True])
  1030. def docs_man(session, compress, update):
  1031. """
  1032. Build Salt's Manpages Documentation
  1033. """
  1034. pydir = _get_pydir(session)
  1035. requirements_file = os.path.join(
  1036. "requirements", "static", _get_pydir(session), "docs.txt"
  1037. )
  1038. install_command = ["--progress-bar=off", "-r", requirements_file]
  1039. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  1040. os.chdir("doc/")
  1041. session.run("make", "clean", external=True)
  1042. session.run("make", "man", "SPHINXOPTS=-W", external=True)
  1043. if update:
  1044. session.run("rm", "-rf", "man/", external=True)
  1045. session.run("cp", "-Rp", "_build/man", "man/", external=True)
  1046. if compress:
  1047. session.run("tar", "-cJvf", "man-archive.tar.xz", "_build/man", external=True)
  1048. os.chdir("..")
  1049. def _invoke(session):
  1050. """
  1051. Run invoke tasks
  1052. """
  1053. requirements_file = os.path.join(
  1054. "requirements", "static", _get_pydir(session), "invoke.txt"
  1055. )
  1056. install_command = ["--progress-bar=off", "-r", requirements_file]
  1057. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  1058. cmd = ["inv"]
  1059. files = []
  1060. # Unfortunately, invoke doesn't support the nargs functionality like argpase does.
  1061. # Let's make it behave properly
  1062. for idx, posarg in enumerate(session.posargs):
  1063. if idx == 0:
  1064. cmd.append(posarg)
  1065. continue
  1066. if posarg.startswith("--"):
  1067. cmd.append(posarg)
  1068. continue
  1069. files.append(posarg)
  1070. if files:
  1071. cmd.append("--files={}".format(" ".join(files)))
  1072. session.run(*cmd)
  1073. @nox.session(name="invoke", python="3")
  1074. def invoke(session):
  1075. """
  1076. Run an invoke target
  1077. """
  1078. _invoke(session)
  1079. @nox.session(name="invoke-pre-commit", python="3")
  1080. def invoke_pre_commit(session):
  1081. """
  1082. DO NOT CALL THIS NOX SESSION DIRECTLY
  1083. This session is called from a pre-commit hook
  1084. """
  1085. if "VIRTUAL_ENV" not in os.environ:
  1086. session.error(
  1087. "This should be running from within a virtualenv and "
  1088. "'VIRTUAL_ENV' was not found as an environment variable."
  1089. )
  1090. if "pre-commit" not in os.environ["VIRTUAL_ENV"]:
  1091. session.error(
  1092. "This should be running from within a pre-commit virtualenv and "
  1093. "'VIRTUAL_ENV'({}) does not appear to be a pre-commit virtualenv.".format(
  1094. os.environ["VIRTUAL_ENV"]
  1095. )
  1096. )
  1097. from nox.virtualenv import VirtualEnv
  1098. # Let's patch nox to make it run inside the pre-commit virtualenv
  1099. try:
  1100. session._runner.venv = VirtualEnv( # pylint: disable=unexpected-keyword-arg
  1101. os.environ["VIRTUAL_ENV"],
  1102. interpreter=session._runner.func.python,
  1103. reuse_existing=True,
  1104. venv=True,
  1105. )
  1106. except TypeError:
  1107. # This is still nox-py2
  1108. session._runner.venv = VirtualEnv(
  1109. os.environ["VIRTUAL_ENV"],
  1110. interpreter=session._runner.func.python,
  1111. reuse_existing=True,
  1112. )
  1113. _invoke(session)
  1114. @nox.session(name="changelog", python="3")
  1115. @nox.parametrize("draft", [False, True])
  1116. def changelog(session, draft):
  1117. """
  1118. Generate salt's changelog
  1119. """
  1120. requirements_file = os.path.join(
  1121. "requirements", "static", _get_pydir(session), "changelog.txt"
  1122. )
  1123. install_command = ["--progress-bar=off", "-r", requirements_file]
  1124. session.install(*install_command, silent=PIP_INSTALL_SILENT)
  1125. town_cmd = ["towncrier", "--version={}".format(session.posargs[0])]
  1126. if draft:
  1127. town_cmd.append("--draft")
  1128. session.run(*town_cmd)