noxfile.py 40 KB

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