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