1
0

noxfile.py 31 KB

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