noxfile.py 31 KB

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