pytest-salt-2019.6.13/0000755000175000017500000000000013500170424015122 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/.pylintrc0000644000175000017500000003221313401741236016775 0ustar vampasvampas00000000000000[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Pickle collected data for later comparisons. persistent=yes # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins=saltpylint.pep8, saltpylint.pep263, saltpylint.strings, saltpylint.fileperms, saltpylint.smartup, # Use multiple processes to speed up Pylint. jobs=1 # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code extension-pkg-whitelist= # Fileperms Lint Plugin Settings fileperms-default=0o644 fileperms-ignore-paths=setup.py [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED confidence= # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" #disable= disable=R, I0011, I0012, I0013, E1101, E1103, C0102, C0103, C0111, C0203, C0204, C0301, C0302, C0330, W0110, W0122, W0142, W0201, W0212, W0404, W0511, W0603, W0612, W0613, W0621, W0622, W0631, W0704, W1202, W1307, F0220, F0401, E8501, E8116, E8121, E8122, E8123, E8124, E8125, E8126, E8127, E8128, E8129, E8131, E8265, E8266, E8402, E8731, locally-disabled, repr-flag-used-in-string, un-indexed-curly-braces-error, un-indexed-curly-braces-warning # Disabled: # R* [refactoring suggestions & reports] # I0011 (locally-disabling) # I0012 (locally-enabling) # I0013 (file-ignored) # E1101 (no-member) [pylint isn't smart enough] # E1103 (maybe-no-member) # C0102 (blacklisted-name) [because it activates C0103 too] # C0103 (invalid-name) # C0111 (missing-docstring) # C0203 (bad-mcs-method-argument) # C0204 (bad-mcs-classmethod-argument) # C0301 (line-too-long) # C0302 (too-many-lines) # C0330 (bad-continuation) # W0110 (deprecated-lambda) # W0122 (exec-statement) # W0142 (star-args) # W0201 (attribute-defined-outside-init) [done in several places in the codebase] # W0212 (protected-access) # W0404 (reimported) [done intentionally for legit reasons] # W0511 (fixme) [several outstanding instances currently in the codebase] # W0603 (global-statement) # W0612 (unused-variable) [unused return values] # W0613 (unused-argument) # W0621 (redefined-outer-name) # W0622 (redefined-builtin) [many parameter names shadow builtins] # W0631 (undefined-loop-variable) [~3 instances, seem to be okay] # W0704 (pointless-except) [misnomer; "ignores the exception" rather than "pointless"] # F0220 (unresolved-interface) # F0401 (import-error) # W1202 (logging-format-interpolation) Use % formatting in logging functions but pass the % parameters as arguments # W1307 (invalid-format-index) Using invalid lookup key '%s' in format specifier "0['%s']" # # E8116 PEP8 E116: unexpected indentation (comment) # E812* All PEP8 E12* # E8265 PEP8 E265 - block comment should start with "# " # E8266 PEP8 E266 - too many leading '#' for block comment # E8501 PEP8 line too long # E8402 module level import not at top of file # E8731 do not assign a lambda expression, use a def # # E1322(repr-flag-used-in-string) [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=yes # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details #msg-template= [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format logging-modules=logging [SPELLING] # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the name of dummy variables (i.e. expectedly # not used). dummy-variables-rgx=_$|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins=__opts__,__virtual__,__salt_system_encoding__ # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_,_cb [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO [BASIC] # List of builtins function names that should not be used, separated by a comma bad-functions=map,filter,input # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_,log,pytest_plugins,__opts__ # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Include a hint for the correct naming format with invalid-name include-naming-hint=no # Regular expression matching correct function names function-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for function names function-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct variable names variable-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for variable names variable-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct constant names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Naming hint for constant names const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression matching correct attribute names attr-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for attribute names attr-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct argument names argument-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for argument names argument-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct class attribute names class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,60}|(__.*__))$ # Naming hint for class attribute names class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,60}|(__.*__))$ # Regular expression matching correct inline iteration names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Naming hint for inline iteration names inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ # Regular expression matching correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Naming hint for class names class-name-hint=[A-Z_][a-zA-Z0-9]+$ # Regular expression matching correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Naming hint for module names module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression matching correct method names method-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for method names method-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=__.*__ # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 [FORMAT] # Maximum number of characters on a single line. max-line-length=120 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no # List of optional constructs for which whitespace checking is disabled no-space-check=trailing-comma,dict-separator # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format=LF [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis ignored-modules= # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes= # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members= [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=regsub,TERMIOS,Bastion,rexec # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branches=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict,_fields,_replace,_source,_make [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception pytest-salt-2019.6.13/setup.py0000644000175000017500000000515213423632164016647 0ustar vampasvampas00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, with_statement import os import sys import codecs from setuptools import setup, find_packages import versioneer # Change to source's directory prior to running any command try: SETUP_DIRNAME = os.path.dirname(__file__) except NameError: # We're most likely being frozen and __file__ triggered this NameError # Let's work around that SETUP_DIRNAME = os.path.dirname(sys.argv[0]) if SETUP_DIRNAME != '': os.chdir(SETUP_DIRNAME) def read(fname): ''' Read a file from the directory where setup.py resides ''' file_path = os.path.join(SETUP_DIRNAME, fname) with codecs.open(file_path, encoding='utf-8') as rfh: return rfh.read() setup( name='pytest-salt', version=versioneer.get_version(), author='Pedro Algarvio', author_email='pedro@algarvio.me', maintainer='Pedro Algarvio', maintainer_email='pedro@algarvio.me', license='Apache Software License 2.0', url='https://github.com/saltstack/pytest-salt', description='Pytest Salt Plugin', long_description=read('README.rst'), packages=find_packages(), cmdclass=versioneer.get_cmdclass(), install_requires=[ 'pytest >= 2.8.1', 'pytest-tempdir', 'pytest-helpers-namespace', #'Salt', 'psutil >= 4.2.0', ], dependency_links=[ 'git+https://github.com/saltstack/salt.git@2016.3#egg=Salt' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Operating System :: OS Independent', 'License :: OSI Approved :: Apache Software License', ], entry_points={ 'pytest11': [ 'salt = pytestsalt', 'salt.config = pytestsalt.fixtures.config', 'salt.daemons = pytestsalt.fixtures.daemons', 'salt.dirs = pytestsalt.fixtures.dirs', 'salt.ports = pytestsalt.fixtures.ports', 'salt.log = pytestsalt.fixtures.log', 'salt.stats = pytestsalt.fixtures.stats' ], 'salt.loader': [ 'engines_dirs = pytestsalt.salt.loader:engines_dirs', 'log_handlers_dirs = pytestsalt.salt.loader:log_handlers_dirs' ] }, ) pytest-salt-2019.6.13/tox.ini0000644000175000017500000000042512667420712016451 0ustar vampasvampas00000000000000# For more information about tox, see https://tox.readthedocs.org/en/latest/ [tox] #envlist = py27,py33,py34,py35 envlist = py27 [testenv] deps = pytest /home/vampas/projects/SaltStack/salt/develop/dist/salt-2015.8.0-590-g3b5d967.tar.gz commands = py.test {posargs:tests} pytest-salt-2019.6.13/README.rst0000644000175000017500000000043513060555555016630 0ustar vampasvampas00000000000000PyTest Salt Plugin ================== This plugin will allow the Salt Daemons to be used in tests. This plugin is currently being used in Salt's test suite for the develop branch, however, this is still considered beta software. Please do submit bug reports for any issues you find. pytest-salt-2019.6.13/tests/0000755000175000017500000000000013500170424016264 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/tests/test_salt_master.py0000644000175000017500000000072413401206133022213 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: Copyright 2015 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. test_salt_master.py ~~~~~~~~~~~~~~~~~~~ Test the pytest salt plugin salt master ''' # Import python libs from __future__ import absolute_import def test_salt_master_running(salt_master): assert salt_master.is_alive() pytest-salt-2019.6.13/tests/test_salt_call.py0000644000175000017500000000164013401206133021631 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: Copyright 2015 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. test_salt_minion.py ~~~~~~~~~~~~~~~~~~~ Test the pytest salt plugin salt minion ''' # Import python libs from __future__ import absolute_import # Import pytest libs import pytest def test_ping(salt_call): assert salt_call.run_sync('test.ping', timeout=10).exitcode == 0 @pytest.mark.gen_test def test_ping_async(salt_call): result = yield salt_call.run('test.ping', timeout=10) assert result.exitcode == 0 def test_sync(salt_call): assert salt_call.run_sync('saltutil.sync_all', timeout=10).exitcode == 0 @pytest.mark.gen_test def test_sync_async(salt_call): result = yield salt_call.run('saltutil.sync_all', timeout=10) assert result.exitcode == 0 pytest-salt-2019.6.13/tests/conftest.py0000644000175000017500000000075413401206133020466 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- # Import python libs import logging if not hasattr(logging, 'TRACE'): logging.TRACE = 5 logging.addLevelName(logging.TRACE, 'TRACE') if not hasattr(logging, 'GARBAGE'): logging.GARBAGE = 1 logging.addLevelName(logging.GARBAGE, 'GARBAGE') pytest_plugins = 'pytester', 'tornado' def pytest_configure(config): config._inicache['log_format'] = '%(asctime)s,%(msecs)04.0f [%(name)-5s:%(lineno)-4d][%(processName)-8s][%(levelname)-8s] %(message)s' pytest-salt-2019.6.13/tests/test_salt_minion.py0000644000175000017500000000072413401206133022211 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: Copyright 2015 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. test_salt_minion.py ~~~~~~~~~~~~~~~~~~~ Test the pytest salt plugin salt minion ''' # Import python libs from __future__ import absolute_import def test_salt_minion_running(salt_minion): assert salt_minion.is_alive() pytest-salt-2019.6.13/pytest_salt.egg-info/0000755000175000017500000000000013500170424021167 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/pytest_salt.egg-info/requires.txt0000644000175000017500000000010413500170424023562 0ustar vampasvampas00000000000000pytest>=2.8.1 pytest-tempdir pytest-helpers-namespace psutil>=4.2.0 pytest-salt-2019.6.13/pytest_salt.egg-info/SOURCES.txt0000644000175000017500000000204113500170424023050 0ustar vampasvampas00000000000000.gitignore .pylintrc .testing.pylintrc LICENSE MANIFEST.in README.rst setup.cfg setup.py tox.ini versioneer.py pytest_salt.egg-info/PKG-INFO pytest_salt.egg-info/SOURCES.txt pytest_salt.egg-info/dependency_links.txt pytest_salt.egg-info/entry_points.txt pytest_salt.egg-info/requires.txt pytest_salt.egg-info/top_level.txt pytestsalt/__init__.py pytestsalt/_version.py pytestsalt/fixtures/__init__.py pytestsalt/fixtures/config.py pytestsalt/fixtures/daemons.py pytestsalt/fixtures/dirs.py pytestsalt/fixtures/log.py pytestsalt/fixtures/ports.py pytestsalt/fixtures/stats.py pytestsalt/salt/__init__.py pytestsalt/salt/loader.py pytestsalt/salt/engines/__init__.py pytestsalt/salt/engines/pytest_engine.py pytestsalt/salt/log_handlers/__init__.py pytestsalt/salt/log_handlers/pytest_log_handler.py pytestsalt/utils/__init__.py pytestsalt/utils/cli_scripts.py pytestsalt/utils/compat.py pytestsalt/utils/log_server_asyncio.py pytestsalt/utils/log_server_tornado.py tests/conftest.py tests/test_salt_call.py tests/test_salt_master.py tests/test_salt_minion.pypytest-salt-2019.6.13/pytest_salt.egg-info/PKG-INFO0000644000175000017500000000227613500170424022273 0ustar vampasvampas00000000000000Metadata-Version: 1.2 Name: pytest-salt Version: 2019.6.13 Summary: Pytest Salt Plugin Home-page: https://github.com/saltstack/pytest-salt Author: Pedro Algarvio Author-email: pedro@algarvio.me Maintainer: Pedro Algarvio Maintainer-email: pedro@algarvio.me License: Apache Software License 2.0 Description: PyTest Salt Plugin ================== This plugin will allow the Salt Daemons to be used in tests. This plugin is currently being used in Salt's test suite for the develop branch, however, this is still considered beta software. Please do submit bug reports for any issues you find. Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Testing Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: Apache Software License pytest-salt-2019.6.13/pytest_salt.egg-info/entry_points.txt0000644000175000017500000000060713500170424024470 0ustar vampasvampas00000000000000[pytest11] salt = pytestsalt salt.config = pytestsalt.fixtures.config salt.daemons = pytestsalt.fixtures.daemons salt.dirs = pytestsalt.fixtures.dirs salt.log = pytestsalt.fixtures.log salt.ports = pytestsalt.fixtures.ports salt.stats = pytestsalt.fixtures.stats [salt.loader] engines_dirs = pytestsalt.salt.loader:engines_dirs log_handlers_dirs = pytestsalt.salt.loader:log_handlers_dirs pytest-salt-2019.6.13/pytest_salt.egg-info/top_level.txt0000644000175000017500000000001313500170424023713 0ustar vampasvampas00000000000000pytestsalt pytest-salt-2019.6.13/pytest_salt.egg-info/dependency_links.txt0000644000175000017500000000007213500170424025245 0ustar vampasvampas00000000000000git+https://github.com/saltstack/salt.git@2016.3#egg=Salt pytest-salt-2019.6.13/setup.cfg0000644000175000017500000000037213500170424016745 0ustar vampasvampas00000000000000[versioneer] vcs = git style = pep440-branch-based versionfile_source = pytestsalt/_version.py versionfile_build = pytestsalt/_version.py tag_prefix = v parentdir_prefix = pytest-salt- [wheel] universal = true [egg_info] tag_build = tag_date = 0 pytest-salt-2019.6.13/pytestsalt/0000755000175000017500000000000013500170424017336 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/pytestsalt/utils/0000755000175000017500000000000013500170424020476 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/pytestsalt/utils/compat.py0000644000175000017500000000105513467034234022346 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.utils.compat ~~~~~~~~~~~~~~~~~~~~~~~ Imports compatability layer ''' try: # Salt > 2017.1.1 # pylint: disable=invalid-name import salt.utils.files fopen = salt.utils.files.fopen except AttributeError: # Salt <= 2017.1.1 # pylint: disable=invalid-name fopen = salt.utils.fopen try: # Salt >= 2018.3.0 # pylint: disable=invalid-name from salt.utils.path import which except ImportError: # Salt < 2018.3.0 # pylint: disable=invalid-name from salt.utils import which pytest-salt-2019.6.13/pytestsalt/utils/cli_scripts.py0000644000175000017500000001244213500166035023374 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.utils.cli_scripts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Code to generate Salt CLI scripts for test runs ''' # Import Python Libs from __future__ import absolute_import, unicode_literals import os import stat import logging import textwrap log = logging.getLogger(__name__) ROOT_DIR = os.path.dirname(os.path.dirname(__file__)) SCRIPT_TEMPLATES = { 'salt': textwrap.dedent( ''' from salt.scripts import salt_main if __name__ == '__main__': salt_main() ''' ), 'salt-api': textwrap.dedent( ''' import salt.cli def main(): sapi = salt.cli.SaltAPI() sapi.start() if __name__ == '__main__': main()' ''' ), 'common': textwrap.dedent( ''' from salt.scripts import salt_{0} import salt.utils.platform def main(): if salt.utils.platform.is_windows(): import os.path import py_compile cfile = os.path.splitext(__file__)[0] + '.pyc' if not os.path.exists(cfile): py_compile.compile(__file__, cfile) salt_{0}() if __name__ == '__main__': main() ''' ), 'coverage': textwrap.dedent( ''' # Setup coverage environment variables COVERAGE_FILE = os.path.join(CODE_DIR, '.coverage') COVERAGE_PROCESS_START = os.path.join(CODE_DIR, '.coveragerc') os.environ[str('COVERAGE_FILE')] = str(COVERAGE_FILE) os.environ[str('COVERAGE_PROCESS_START')] = str(COVERAGE_PROCESS_START) ''' ), 'sitecustomize': textwrap.dedent( ''' # Allow sitecustomize.py to be importable for test coverage purposes SITECUSTOMIZE_DIR = r'{sitecustomize_dir}' PYTHONPATH = os.environ.get('PYTHONPATH') or None if PYTHONPATH is None: PYTHONPATH_ENV_VAR = SITECUSTOMIZE_DIR else: PYTHON_PATH_ENTRIES = PYTHONPATH.split(os.pathsep) if SITECUSTOMIZE_DIR in PYTHON_PATH_ENTRIES: PYTHON_PATH_ENTRIES.remove(SITECUSTOMIZE_DIR) PYTHON_PATH_ENTRIES.insert(0, SITECUSTOMIZE_DIR) PYTHONPATH_ENV_VAR = os.pathsep.join(PYTHON_PATH_ENTRIES) os.environ[str('PYTHONPATH')] = str(PYTHONPATH_ENV_VAR) if SITECUSTOMIZE_DIR in sys.path: sys.path.remove(SITECUSTOMIZE_DIR) sys.path.insert(0, SITECUSTOMIZE_DIR) ''' ) } def generate_script(bin_dir, script_name, executable, code_dir, extra_code=None, inject_coverage=False, inject_sitecustomize=False): ''' Generate script ''' # Late import import pytestsalt.utils.compat as compat if not os.path.isdir(bin_dir): os.makedirs(bin_dir) cli_script_name = 'cli_{}.py'.format(script_name.replace('-', '_')) script_path = os.path.join(bin_dir, cli_script_name) if not os.path.isfile(script_path): log.info('Generating %s', script_path) with compat.fopen(script_path, 'w') as sfh: script_template = SCRIPT_TEMPLATES.get(script_name, None) if script_template is None: script_template = SCRIPT_TEMPLATES.get('common', None) if script_template is None: raise RuntimeError( 'Pytest Salt\'s does not know how to handle the {} script'.format( script_name ) ) if len(executable) > 128: # Too long for a shebang, let's use /usr/bin/env and hope # the right python is picked up executable = '/usr/bin/env python' script_contents = textwrap.dedent( ''' #!{executable} from __future__ import absolute_import import os import sys CODE_DIR = r'{code_dir}' if CODE_DIR in sys.path: sys.path.remove(CODE_DIR) sys.path.insert(0, CODE_DIR) '''.format( executable=executable, code_dir=code_dir, ) ) if extra_code: script_contents += '\n' + extra_code + '\n' if inject_coverage: script_contents += '\n' + SCRIPT_TEMPLATES['coverage'] + '\n' if inject_sitecustomize: script_contents += '\n{}\n'.format( SCRIPT_TEMPLATES['sitecustomize'].format( sitecustomize_dir=os.path.join( ROOT_DIR, 'salt', 'coverage' ) ) ) script_contents += '\n' + script_template.format(script_name.replace('salt-', '')) sfh.write(script_contents.strip()) log.debug( 'Wrote the following contents to temp script %s:\n%s', script_path, script_contents ) fst = os.stat(script_path) os.chmod(script_path, fst.st_mode | stat.S_IEXEC) log.info('Returning script path %r', script_path) return script_path pytest-salt-2019.6.13/pytestsalt/utils/log_server_asyncio.py0000644000175000017500000000447013420325415024754 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.log_server_asyncio ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AsyncIO Log Server Fixture ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import asyncio import logging import threading # Import 3rd-party libs import msgpack log = logging.getLogger(__name__) def log_server_asyncio(log_server_port): ''' Starts a log server. ''' async def read_child_processes_log_records(reader, writer): unpacker = msgpack.Unpacker(raw=False) while True: try: wire_bytes = await reader.read(1024) if not wire_bytes: break try: unpacker.feed(wire_bytes) except msgpack.exceptions.BufferFull: # Start over loosing some data?! unpacker = msgpack.Unpacker(raw=False) unpacker.feed(wire_bytes) for record_dict in unpacker: record = logging.makeLogRecord(record_dict) logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except log.exception(exc) def process_logs(port): loop = asyncio.new_event_loop() try: coro = asyncio.start_server(read_child_processes_log_records, host='localhost', port=port, loop=loop) server = loop.run_until_complete(coro) except OSError as err: if err.errno != errno.EADDRNOTAVAIL: # If not address not available, in case localhost cannot be resolved raise coro = asyncio.start_server(read_child_processes_log_records, host='127.0.0.1', port=port, loop=loop) server = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass server.close() loop.run_until_complete(server.wait_closed()) loop.close() process_queue_thread = threading.Thread(target=process_logs, args=(log_server_port,)) process_queue_thread.daemon = True process_queue_thread.start() pytest-salt-2019.6.13/pytestsalt/utils/log_server_tornado.py0000644000175000017500000000370213425105021024744 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.log_server_tornado ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tornado Log Server Fixture ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import threading # Import 3rd-party libs import msgpack from tornado import gen from tornado.ioloop import IOLoop from tornado.tcpserver import TCPServer from tornado.iostream import StreamClosedError log = logging.getLogger(__name__) class LogServer(TCPServer): @gen.coroutine def handle_stream(self, stream, address): unpacker = msgpack.Unpacker(raw=False) while True: try: wire_bytes = yield stream.read_bytes(1024, partial=True) if not wire_bytes: break try: unpacker.feed(wire_bytes) except msgpack.exceptions.BufferFull: # Start over loosing some data?! unpacker = msgpack.Unpacker(raw=False) unpacker.feed(wire_bytes) for record_dict in unpacker: record = logging.makeLogRecord(record_dict) logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit, StreamClosedError): break except Exception as exc: # pylint: disable=broad-except log.exception(exc) def log_server_tornado(log_server_port): ''' Starts a log server. ''' def process_logs(port): server = LogServer() server.listen(port, address='127.0.0.1') try: IOLoop.current().start() except KeyboardInterrupt: pass server.stop() process_queue_thread = threading.Thread(target=process_logs, args=(log_server_port,)) process_queue_thread.daemon = True process_queue_thread.start() pytest-salt-2019.6.13/pytestsalt/utils/__init__.py0000644000175000017500000010557213423632164022631 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.utils ~~~~~~~~~~~~~~~~ Some pytest fixtures used in pytest-salt ''' # Import Python libs from __future__ import absolute_import import os import re import sys import json import time import errno import atexit import signal import socket import logging import subprocess import threading from operator import itemgetter from collections import namedtuple # Import 3rd party libs import pytest import psutil try: import setproctitle HAS_SETPROCTITLE = True except ImportError: HAS_SETPROCTITLE = False log = logging.getLogger(__name__) if sys.platform.startswith('win'): SIGINT = SIGTERM = signal.CTRL_BREAK_EVENT # pylint: disable=no-member else: SIGINT = signal.SIGINT SIGTERM = signal.SIGTERM def set_proc_title(title): if HAS_SETPROCTITLE is False: return setproctitle.setproctitle('[{}] - {}'.format(title, setproctitle.getproctitle())) def get_unused_localhost_port(): ''' Return a random unused port on localhost ''' usock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) usock.bind(('127.0.0.1', 0)) port = usock.getsockname()[1] usock.close() return port def collect_child_processes(pid): ''' Try to collect any started child processes of the provided pid ''' # Let's get the child processes of the started subprocess try: parent = psutil.Process(pid) children = parent.children(recursive=True) except psutil.NoSuchProcess: children = [] return children def _terminate_process_list(process_list, kill=False, slow_stop=False): for process in process_list[:]: # Iterate over copy of the list if not psutil.pid_exists(process.pid): process_list.remove(process) continue try: if not kill and process.status() == psutil.STATUS_ZOMBIE: # Zombie processes will exit once child processes also exit continue try: cmdline = process.cmdline() except psutil.AccessDenied: # OSX is more restrictive about the above information cmdline = None if not cmdline: cmdline = process.as_dict() if kill: log.info('Killing process(%s): %s', process.pid, cmdline) process.kill() else: log.info('Terminating process(%s): %s', process.pid, cmdline) try: if slow_stop: # Allow coverage data to be written down to disk process.send_signal(SIGTERM) try: process.wait(2) except psutil.TimeoutExpired: if psutil.pid_exists(process.pid): continue else: process.terminate() except OSError as exc: if exc.errno not in (errno.ESRCH, errno.EACCES): raise if not psutil.pid_exists(process.pid): process_list.remove(process) except psutil.NoSuchProcess: process_list.remove(process) def terminate_process_list(process_list, kill=False, slow_stop=False): def on_process_terminated(proc): log.info('Process %s terminated with exit code: %s', getattr(proc, '_cmdline', proc), proc.returncode) # Try to terminate processes with the provided kill and slow_stop parameters log.info('Terminating process list. 1st step. kill: %s, slow stop: %s', kill, slow_stop) # Cache the cmdline since that will be inaccessible once the process is terminated for proc in process_list: try: cmdline = proc.cmdline() except (psutil.NoSuchProcess, psutil.AccessDenied): # OSX is more restrictive about the above information cmdline = None if not cmdline: try: cmdline = proc except (psutil.NoSuchProcess, psutil.AccessDenied): cmdline = ''.format(proc) proc._cmdline = cmdline _terminate_process_list(process_list, kill=kill, slow_stop=slow_stop) psutil.wait_procs(process_list, timeout=15, callback=on_process_terminated) if process_list: # If there's still processes to be terminated, retry and kill them if slow_stop is False log.info('Terminating process list. 2nd step. kill: %s, slow stop: %s', slow_stop is False, slow_stop) _terminate_process_list(process_list, kill=slow_stop is False, slow_stop=slow_stop) psutil.wait_procs(process_list, timeout=10, callback=on_process_terminated) if process_list: # If there's still processes to be terminated, just kill them, no slow stopping now log.info('Terminating process list. 3rd step. kill: True, slow stop: False') _terminate_process_list(process_list, kill=True, slow_stop=False) psutil.wait_procs(process_list, timeout=5, callback=on_process_terminated) if process_list: # In there's still processes to be terminated, log a warning about it log.warning('Some processes failed to properly terminate: %s', process_list) def terminate_process(pid=None, process=None, children=None, kill_children=False, slow_stop=False): ''' Try to terminate/kill the started processe ''' children = children or [] process_list = [] # Always kill children if kill the parent process. kill_children = True if slow_stop is False else kill_children if pid and not process: try: process = psutil.Process(pid) process_list.append(process) except psutil.NoSuchProcess: # Process is already gone process = None if kill_children: if process: if not children: children = collect_child_processes(process.pid) else: # Let's collect children again since there might be new ones children.extend(collect_child_processes(pid)) if children: process_list.extend(children) if process_list: if process: log.info('Stopping process %s and respective children: %s', process, children) else: log.info('Terminating process list: %s', process_list) terminate_process_list(process_list, kill=slow_stop is False, slow_stop=slow_stop) def start_daemon(request, daemon_name=None, daemon_id=None, daemon_log_prefix=None, daemon_cli_script_name=None, daemon_config=None, daemon_config_dir=None, daemon_class=None, bin_dir_path=None, fail_hard=False, start_timeout=10, slow_stop=True, environ=None, cwd=None, max_attempts=3, **kwargs): ''' Returns a running salt daemon ''' if fail_hard: fail_method = pytest.fail else: fail_method = pytest.xfail log.info('[%s] Starting pytest %s(%s)', daemon_name, daemon_log_prefix, daemon_id) attempts = 0 process = None while attempts <= max_attempts: # pylint: disable=too-many-nested-blocks attempts += 1 process = daemon_class(request, daemon_config, daemon_config_dir, bin_dir_path, daemon_log_prefix, cli_script_name=daemon_cli_script_name, slow_stop=slow_stop, environ=environ, cwd=cwd, **kwargs) process.start() if process.is_alive(): try: connectable = process.wait_until_running(timeout=start_timeout) if connectable is False: connectable = process.wait_until_running(timeout=start_timeout/2) if connectable is False: process.terminate() if attempts >= max_attempts: fail_method( 'The pytest {}({}) has failed to confirm running status ' 'after {} attempts'.format(daemon_name, daemon_id, attempts)) continue except Exception as exc: # pylint: disable=broad-except log.exception('[%s] %s', daemon_log_prefix, exc, exc_info=True) terminate_process(process.pid, kill_children=True, slow_stop=slow_stop) if attempts >= max_attempts: fail_method(str(exc)) continue log.info( '[%s] The pytest %s(%s) is running and accepting commands ' 'after %d attempts', daemon_log_prefix, daemon_name, daemon_id, attempts ) def stop_daemon(): log.info('[%s] Stopping pytest %s(%s)', daemon_log_prefix, daemon_name, daemon_id) terminate_process(process.pid, kill_children=True, slow_stop=slow_stop) log.info('[%s] pytest %s(%s) stopped', daemon_log_prefix, daemon_name, daemon_id) request.addfinalizer(stop_daemon) return process else: terminate_process(process.pid, kill_children=True, slow_stop=slow_stop) continue else: # pylint: disable=useless-else-on-loop # Wrong, we have a return, its not useless if process is not None: terminate_process(process.pid, kill_children=True, slow_stop=slow_stop) fail_method( 'The pytest {}({}) has failed to start after {} attempts'.format( daemon_name, daemon_id, attempts-1 ) ) class SaltScriptBase(object): ''' Base class for Salt CLI scripts ''' cli_display_name = None def __init__(self, request, config, config_dir, bin_dir_path, log_prefix, cli_script_name=None, slow_stop=False, environ=None, cwd=None): self.request = request self.config = config if not isinstance(config_dir, str): config_dir = config_dir.realpath().strpath self.config_dir = config_dir self.bin_dir_path = bin_dir_path self.log_prefix = log_prefix if cli_script_name is None: raise RuntimeError('Please provide a value for the cli_script_name keyword argument') self.cli_script_name = cli_script_name if self.cli_display_name is None: self.cli_display_name = '{}({})'.format(self.__class__.__name__, self.cli_script_name) self.slow_stop = slow_stop self.environ = environ or os.environ.copy() self.cwd = cwd or os.getcwd() self._terminal = self._children = None def get_script_path(self, script_name): ''' Returns the path to the script to run ''' script_path = os.path.join(self.bin_dir_path, script_name) if not os.path.exists(script_path): pytest.fail('The CLI script {!r} does not exist'.format(script_path)) return script_path def get_base_script_args(self): ''' Returns any additional arguments to pass to the CLI script ''' return ['-c', self.config_dir] def get_script_args(self): # pylint: disable=no-self-use ''' Returns any additional arguments to pass to the CLI script ''' return [] def init_terminal(self, cmdline, **kwargs): ''' Instantiate a terminal with the passed cmdline and kwargs and return it. Additionaly, it sets a reference to it in self._terminal and also collects an initial listing of child processes which will be used when terminating the terminal ''' # Late import import salt.utils.nb_popen as nb_popen self._terminal = nb_popen.NonBlockingPopen(cmdline, **kwargs) self._children = collect_child_processes(self._terminal.pid) atexit.register(self.terminate) return self._terminal def terminate(self): ''' Terminate the started daemon ''' if self._terminal is None: return # Lets log and kill any child processes which salt left behind if self._terminal.stdout: self._terminal.stdout.close() if self._terminal.stderr: self._terminal.stderr.close() terminate_process(pid=self._terminal.pid, children=self._children, kill_children=True, slow_stop=self.slow_stop) class SaltDaemonScriptBase(SaltScriptBase): ''' Base class for Salt Daemon CLI scripts ''' def __init__(self, *args, **kwargs): self._process_cli_output_in_thread = kwargs.pop('process_cli_output_in_thread', True) event_listener_config_dir = kwargs.pop('event_listener_config_dir', None) if event_listener_config_dir and not isinstance(event_listener_config_dir, str): event_listener_config_dir = event_listener_config_dir.realpath().strpath self.event_listener_config_dir = event_listener_config_dir super(SaltDaemonScriptBase, self).__init__(*args, **kwargs) self._running = threading.Event() self._connectable = threading.Event() def is_alive(self): ''' Returns true if the process is alive ''' return self._running.is_set() def get_check_ports(self): # pylint: disable=no-self-use ''' Return a list of ports to check against to ensure the daemon is running ''' return [] def get_check_events(self): # pylint: disable=no-self-use ''' Return a list of event tags to check against to ensure the daemon is running ''' return [] def get_salt_run_fixture(self): if self.request.scope == 'session': try: return self.request.getfixturevalue('session_salt_run') except AttributeError: return self.request.getfuncargvalue('session_salt_run') try: return self.request.getfixturevalue('salt_run') except AttributeError: return self.request.getfuncargvalue('salt_run') def start(self): ''' Start the daemon subprocess ''' # Late import log.info('[%s][%s] Starting DAEMON in CWD: %s', self.log_prefix, self.cli_display_name, self.cwd) proc_args = [ self.get_script_path(self.cli_script_name) ] + self.get_base_script_args() + self.get_script_args() if sys.platform.startswith('win'): # Windows needs the python executable to come first proc_args.insert(0, sys.executable) log.info('[%s][%s] Running \'%s\'...', self.log_prefix, self.cli_display_name, ' '.join(proc_args)) self.init_terminal(proc_args, env=self.environ, cwd=self.cwd) self._running.set() if self._process_cli_output_in_thread: process_output_thread = threading.Thread(target=self._process_output_in_thread) process_output_thread.daemon = True process_output_thread.start() return True def _process_output_in_thread(self): ''' The actual, coroutine aware, start method ''' try: while self._running.is_set() and self._terminal.poll() is None: # We're not actually interested in processing the output, just consume it if self._terminal.stdout is not None: self._terminal.recv() if self._terminal.stderr is not None: self._terminal.recv_err() time.sleep(0.125) if self._terminal.poll() is not None: self._running.clear() except (SystemExit, KeyboardInterrupt): self._running.clear() finally: if self._terminal.stdout: self._terminal.stdout.close() if self._terminal.stderr: self._terminal.stderr.close() @property def pid(self): terminal = getattr(self, '_terminal', None) if not terminal: return return terminal.pid def terminate(self): ''' Terminate the started daemon ''' # Let's get the child processes of the started subprocess self._running.clear() self._connectable.clear() time.sleep(0.0125) super(SaltDaemonScriptBase, self).terminate() def wait_until_running(self, timeout=None): ''' Blocking call to wait for the daemon to start listening ''' # Late import import salt.ext.six as six if self._connectable.is_set(): return True expire = time.time() + timeout check_ports = self.get_check_ports() if check_ports: log.debug( '[%s][%s] Checking the following ports to assure running status: %s', self.log_prefix, self.cli_display_name, check_ports ) check_events = self.get_check_events() if check_events: log.debug( '[%s][%s] Checking the following event tags to assure running status: %s', self.log_prefix, self.cli_display_name, check_events ) log.debug('Wait until running expire: %s Timeout: %s Current Time: %s', expire, timeout, time.time()) event_listener = EventListener( self.event_listener_config_dir or self.config_dir, self.log_prefix ) try: while True: if self._running.is_set() is False: # No longer running, break log.warning('No longer running!') break if time.time() > expire: # Timeout, break log.debug('Expired at %s(was set to %s)', time.time(), expire) break if not check_ports and not check_events: self._connectable.set() break if check_events: for tag in event_listener.wait_for_events(check_events, timeout=timeout - 0.5): check_events.remove(tag) if not check_events: stop_sending_events_file = self.config.get('pytest_stop_sending_events_file') if stop_sending_events_file and os.path.exists(stop_sending_events_file): log.warning('Removing pytest_stop_sending_events_file: %s', stop_sending_events_file) os.unlink(stop_sending_events_file) for port in set(check_ports): if isinstance(port, int): log.debug('[%s][%s] Checking connectable status on port: %s', self.log_prefix, self.cli_display_name, port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn = sock.connect_ex(('localhost', port)) try: if conn == 0: log.debug('[%s][%s] Port %s is connectable!', self.log_prefix, self.cli_display_name, port) check_ports.remove(port) sock.shutdown(socket.SHUT_RDWR) except socket.error: continue finally: sock.close() del sock elif isinstance(port, six.string_types): salt_run = self.get_salt_run_fixture() minions_joined = salt_run.run('manage.joined') if minions_joined.exitcode == 0: if minions_joined.json and port in minions_joined.json: check_ports.remove(port) log.warning('Removed ID %r Still left: %r', port, check_ports) elif minions_joined.json is None: log.debug('salt-run manage.join did not return any valid JSON: %s', minions_joined) time.sleep(0.5) except KeyboardInterrupt: return self._connectable.is_set() finally: event_listener.terminate() if self._connectable.is_set(): log.debug('[%s][%s] All ports checked. Running!', self.log_prefix, self.cli_display_name) return self._connectable.is_set() class ShellResult(namedtuple('Result', ('exitcode', 'stdout', 'stderr', 'json'))): ''' This class serves the purpose of having a common result class which will hold the data from the bigret backend(despite the backend being used). This will allow filtering by access permissions and/or object ownership. ''' __slots__ = () def __new__(cls, exitcode, stdout, stderr, json): return super(ShellResult, cls).__new__(cls, exitcode, stdout, stderr, json) # These are copied from the namedtuple verbose output in order to quiet down PyLint exitcode = property(itemgetter(0), doc='Alias for field number 0') stdout = property(itemgetter(1), doc='Alias for field number 1') stderr = property(itemgetter(2), doc='Alias for field number 2') json = property(itemgetter(3), doc='Alias for field number 3') def __eq__(self, other): ''' Allow comparison against the parsed JSON or the output ''' if self.json: return self.json == other return self.stdout == other class SaltCliScriptBase(SaltScriptBase): ''' Base class which runs Salt's non daemon CLI scripts ''' DEFAULT_TIMEOUT = 25 def __init__(self, *args, **kwargs): self.default_timeout = kwargs.pop('default_timeout', self.DEFAULT_TIMEOUT) super(SaltCliScriptBase, self).__init__(*args, **kwargs) def get_base_script_args(self): return SaltScriptBase.get_base_script_args(self) + ['--out=json'] def get_minion_tgt(self, **kwargs): return kwargs.pop('minion_tgt', None) def run(self, *args, **kwargs): ''' Run the given command synchronously ''' # Late import import salt.ext.six as six timeout = kwargs.get('timeout', self.default_timeout) if 'fail_hard' in kwargs: # Explicit fail_hard passed fail_hard = kwargs.pop('fail_hard') else: # Get the value of the _salt_fail_hard fixture try: fail_hard = self.request.getfixturevalue('_salt_fail_hard') except AttributeError: fail_hard = self.request.getfuncargvalue('_salt_fail_hard') if fail_hard is True: fail_method = pytest.fail else: fail_method = pytest.xfail log.info('The fail hard setting for %s is: %s', self.cli_script_name, fail_hard) minion_tgt = self.get_minion_tgt(**kwargs) timeout_expire = time.time() + kwargs.pop('timeout', self.default_timeout) environ = self.environ.copy() environ['PYTEST_LOG_PREFIX'] = '[{}] '.format(self.log_prefix) environ['PYTHONUNBUFFERED'] = '1' proc_args = [ self.get_script_path(self.cli_script_name) ] + self.get_base_script_args() + self.get_script_args() if sys.platform.startswith('win'): # Windows needs the python executable to come first proc_args.insert(0, sys.executable) if minion_tgt is not None: proc_args.append(minion_tgt) proc_args.extend(list(args)) for key in kwargs: proc_args.append('{}={}'.format(key, kwargs[key])) log.info('[%s][%s] Running \'%s\' in CWD: %s ...', self.log_prefix, self.cli_display_name, ' '.join(proc_args), self.cwd) terminal = self.init_terminal(proc_args, cwd=self.cwd, env=environ, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Consume the output stdout = six.b('') stderr = six.b('') try: while True: # We're not actually interested in processing the output, just consume it if terminal.stdout is not None: try: out = terminal.recv(4096) except IOError: out = six.b('') if out: stdout += out if terminal.stderr is not None: try: err = terminal.recv_err(4096) except IOError: err = '' if err: stderr += err if out is None and err is None: break if timeout_expire < time.time(): self.terminate() fail_method( '[{}][{}] Failed to run: args: {!r}; kwargs: {!r}; Error: {}'.format( self.log_prefix, self.cli_display_name, args, kwargs, '[{}][{}] Timed out after {} seconds!'.format(self.log_prefix, self.cli_display_name, timeout) ) ) except (SystemExit, KeyboardInterrupt): pass finally: self.terminate() if six.PY3: # pylint: disable=undefined-variable stdout = stdout.decode(__salt_system_encoding__) stderr = stderr.decode(__salt_system_encoding__) # pylint: enable=undefined-variable exitcode = terminal.returncode stdout, stderr, json_out = self.process_output(minion_tgt, stdout, stderr, cli_cmd=proc_args) return ShellResult(exitcode, stdout, stderr, json_out) def process_output(self, tgt, stdout, stderr, cli_cmd=None): if stdout: try: json_out = json.loads(stdout) except ValueError: log.debug('[%s][%s] Failed to load JSON from the following output:\n%r', self.log_prefix, self.cli_display_name, stdout) json_out = None else: json_out = None return stdout, stderr, json_out class SaltRunEventListener(SaltCliScriptBase): ''' Class which runs 'salt-run state.event *' to match agaist a provided set of event tags ''' EVENT_MATCH_RE = re.compile(r'^(?P[\w/-]+)(?:[\s]+)(?P[\S\W]+)$') def get_base_script_args(self): return SaltScriptBase.get_base_script_args(self) def get_script_args(self): # pylint: disable=no-self-use ''' Returns any additional arguments to pass to the CLI script ''' return ['state.event'] def run(self, tags=(), timeout=10): # pylint: disable=arguments-differ ''' Run the given command synchronously ''' log.info('%s checking for tags: %s', self.__class__.__name__, tags) # Late import import salt.ext.six as six exitcode = 0 timeout_expire = time.time() + timeout environ = self.environ.copy() environ['PYTEST_LOG_PREFIX'] = '{}[EventListen]'.format(self.log_prefix) environ['PYTHONUNBUFFERED'] = '1' proc_args = [ self.get_script_path(self.cli_script_name) ] + self.get_base_script_args() + self.get_script_args() if sys.platform.startswith('win'): # Windows needs the python executable to come first proc_args.insert(0, sys.executable) log.info('[%s][%s] Running \'%s\' in CWD: %s...', self.log_prefix, self.cli_display_name, ' '.join(proc_args), self.cwd) to_match_events = set(tags) matched_events = {} terminal = self.init_terminal(proc_args, cwd=self.cwd, env=environ, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Consume the output stdout = six.b('') stderr = six.b('') process_output = six.b('') events_processed = 0 try: while True: time.sleep(0.5) if terminal.stdout is not None: try: out = terminal.recv(4096) except IOError: out = six.b('') if out: stdout += out process_output += out if terminal.stderr is not None: try: err = terminal.recv_err(4096) except IOError: err = '' if err: stderr += err if out is None and err is None: if to_match_events: exitcode = 1 log.warning('[%s][%s] Premature exit?! Failed to find all of the required event tags. ' 'Total events processed: %s', self.log_prefix, self.cli_display_name, events_processed) break if process_output: lines = process_output.split(b'}\n') if lines[-1] != b'': process_output = lines.pop() else: process_output = six.b('') lines.pop() for line in lines: match = self.EVENT_MATCH_RE.match(line.decode(__salt_system_encoding__)) # pylint: disable=undefined-variable if match: events_processed += 1 tag, data = match.groups() if tag in to_match_events: matched_events[tag] = json.loads(data + '}') to_match_events.remove(tag) log.info('[%s][%s] Events processed so far: %d', self.log_prefix, self.cli_display_name, events_processed) if not to_match_events: log.debug('[%s][%s] ALL EVENT TAGS FOUND!!!', self.log_prefix, self.cli_display_name) break if timeout_expire < time.time(): log.warning('[%s][%s] Failed to find all of the required event tags. Total events processed: %s', self.log_prefix, self.cli_display_name, events_processed) exitcode = 1 break except (SystemExit, KeyboardInterrupt): pass finally: self.terminate() if six.PY3: # pylint: disable=undefined-variable stdout = stdout.decode(__salt_system_encoding__) stderr = stderr.decode(__salt_system_encoding__) # pylint: enable=undefined-variable if to_match_events: stop_sending_events_file = self.config.get('pytest_stop_sending_events_file') if stop_sending_events_file and os.path.exists(stop_sending_events_file): log.warning('Removing pytest_stop_sending_events_file: %s', stop_sending_events_file) os.unlink(stop_sending_events_file) json_out = { 'matched': matched_events, 'unmatched': to_match_events } return ShellResult(exitcode, stdout, stderr, json_out) class EventListener: DEFAULT_TIMEOUT = 60 def __init__(self, config_dir, log_prefix): # Late import self.config_dir = config_dir self.log_prefix = '[{}][PyTestEventListener]'.format(log_prefix) self._listener = None def wait_for_events(self, check_events, timeout=None): if timeout is None: timeout = self.DEFAULT_TIMEOUT log.info('%s waiting %s seconds for events: %s', self.log_prefix, timeout, check_events) matched_events = set() events_to_match = set(check_events) events_processed = 0 max_timeout = time.time() + timeout while True: if not events_to_match: log.info('%s ALL EVENT TAGS FOUND!!!', self.log_prefix) return matched_events if time.time() > max_timeout: log.warning( '%s Failed to find all of the required event tags. ' 'Total events processed: %s', self.log_prefix, events_processed ) return matched_events event = self.listener.get_event(full=True, auto_reconnect=True) if event is None: continue tag = event['tag'] log.warning('Got event: %s', event) if tag in events_to_match: matched_events.add(tag) events_to_match.remove(tag) events_processed += 1 log.info('%s Events processed so far: %d', self.log_prefix, events_processed) def terminate(self): listener = self.listener self._listener = None listener.destroy() @property def listener(self): if self._listener is None: # Late import import salt.config import salt.utils.event opts = salt.config.master_config(os.path.join(self.config_dir, 'master')) self._listener = salt.utils.event.get_event('master', opts=opts, listen=True) return self._listener @pytest.mark.trylast def pytest_configure(config): pytest.helpers.utils.register(get_unused_localhost_port) pytest-salt-2019.6.13/pytestsalt/salt/0000755000175000017500000000000013500170424020301 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/pytestsalt/salt/engines/0000755000175000017500000000000013500170424021731 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/pytestsalt/salt/engines/__init__.py0000644000175000017500000000003013401206133024030 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- pytest-salt-2019.6.13/pytestsalt/salt/engines/pytest_engine.py0000644000175000017500000001005413420325415025163 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.engines.pytest_engine ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Simple salt engine which will setup a socket to accept connections allowing us to know when a daemon is up and running ''' # Import python libs from __future__ import absolute_import, print_function import os import sys import errno import socket import logging # Import salt libs import salt.utils.event try: import salt.utils.asynchronous HAS_SALT_ASYNC = True except ImportError: HAS_SALT_ASYNC = False # Import 3rd-party libs from tornado import gen from tornado import ioloop from tornado import iostream from tornado import netutil log = logging.getLogger(__name__) __virtualname__ = 'pytest' def __virtual__(): return 'pytest_engine_port' in __opts__ # pylint: disable=undefined-variable def start(): pytest_engine = PyTestEngine(__opts__) # pylint: disable=undefined-variable pytest_engine.start() class PyTestEngine(object): def __init__(self, opts): self.opts = opts self.id = opts['id'] self.role = opts['__role'] self.sock_dir = opts['sock_dir'] self.port = int(opts['pytest_engine_port']) self.tcp_server_sock = None self.stop_sending_events_file = opts.get('pytest_stop_sending_events_file') def start(self): self.io_loop = ioloop.IOLoop() self.io_loop.make_current() self.io_loop.add_callback(self._start) self.io_loop.start() @gen.coroutine def _start(self): log.info('Starting Pytest Engine(role=%s, id=%s) on port %s', self.role, self.id, self.port) self.tcp_server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.tcp_server_sock.setblocking(0) # bind the socket to localhost on the config provided port self.tcp_server_sock.bind(('localhost', self.port)) # become a server socket self.tcp_server_sock.listen(5) if HAS_SALT_ASYNC: with salt.utils.asynchronous.current_ioloop(self.io_loop): netutil.add_accept_handler(self.tcp_server_sock, self.handle_connection) else: netutil.add_accept_handler(self.tcp_server_sock, self.handle_connection) if self.role == 'master': yield self.fire_master_started_event() def handle_connection(self, connection, address): log.warning('Accepted connection from %s. Role: %s ID: %s', address, self.role, self.id) # We just need to know that the daemon running the engine is alive... try: connection.shutdown(socket.SHUT_RDWR) # pylint: disable=no-member connection.close() except socket.error as exc: if not sys.platform.startswith('darwin'): raise try: if exc.errno != errno.ENOTCONN: raise except AttributeError: # This is not macOS !? pass @gen.coroutine def fire_master_started_event(self): master_start_event_tag = 'salt/master/{}/start'.format(self.id) log.info('Firing salt-%s started event. Tag: %s', self.role, master_start_event_tag) event_bus = salt.utils.event.get_master_event(self.opts, self.sock_dir, listen=False) load = {'id': self.id, 'tag': master_start_event_tag, 'data': {}} # 30 seconds should be more than enough to fire these events every second in order # for pytest-salt to pickup that the master is running timeout = 30 while True: if self.stop_sending_events_file and not os.path.exists(self.stop_sending_events_file): log.info('The stop sending events file "marker" is done. Stop sending events...') break timeout -= 1 try: event_bus.fire_event(load, master_start_event_tag, timeout=500) if timeout <= 0: break yield gen.sleep(1) except iostream.StreamClosedError: break pytest-salt-2019.6.13/pytestsalt/salt/log_handlers/0000755000175000017500000000000013500170424022742 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/pytestsalt/salt/log_handlers/pytest_log_handler.py0000644000175000017500000001071313465251715027221 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.salt.log_handlers.pytest_log_handler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Salt External Logging Handler ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import threading import logging from multiprocessing import Queue # Import 3rd-party libs import msgpack # Import Salt libs import salt.log.setup # pylint: disable=no-member,invalid-name try: import salt.utils.stringutils to_unicode = salt.utils.stringutils.to_unicode except ImportError: import salt.utils to_unicode = salt.utils.to_unicode try: import salt.utils.platform is_darwin = salt.utils.platform.is_darwin except ImportError: import salt.utils is_darwin = salt.utils.is_darwin # pylint: enable=no-member,invalid-name __virtualname__ = 'pytest_log_handler' log = logging.getLogger(__name__) def __virtual__(): if 'pytest_log_port' not in __opts__: return False, "'pytest_log_port' not in options" return True def setup_handlers(): host_addr = __opts__.get('pytest_log_host') if not host_addr: import subprocess if __opts__['pytest_windows_guest'] is True: proc = subprocess.Popen('ipconfig', stdout=subprocess.PIPE) for line in proc.stdout.read().strip().encode(__salt_system_encoding__).splitlines(): if 'Default Gateway' in line: parts = line.split() host_addr = parts[-1] break else: proc = subprocess.Popen( "netstat -rn | grep -E '^0.0.0.0|default' | awk '{ print $2 }'", shell=True, stdout=subprocess.PIPE ) host_addr = proc.stdout.read().strip().encode(__salt_system_encoding__) host_port = __opts__['pytest_log_port'] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((host_addr, host_port)) except socket.error as exc: # Don't even bother if we can't connect log.warning('Cannot connect back to log server: %s', exc) return finally: sock.close() if is_darwin(): # The maximum for the multiprocessing queue on MacOS is 32767, so if we running on MacOS # then we use that maximum. queue_size = 32767 else: # One million log messages is more than enough to queue. # Above that value, if `process_queue` can't process fast enough, # start dropping. This will contain a memory leak in case `process_queue` # can't process fast enough of in case it can't deliver the log records at all. queue_size = 10000000 queue = Queue(queue_size) handler = salt.log.setup.SaltLogQueueHandler(queue) level = salt.log.setup.LOG_LEVELS[(__opts__.get('pytest_log_level') or 'error').lower()] handler.setLevel(level) pytest_log_prefix = os.environ.get('PYTEST_LOG_PREFIX') or __opts__['pytest_log_prefix'] process_queue_thread = threading.Thread(target=process_queue, args=(host_addr, host_port, pytest_log_prefix, queue)) process_queue_thread.daemon = True process_queue_thread.start() return handler def process_queue(host, port, prefix, queue): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((host, port)) except socket.error: sock.close() return log.warning('Sending log records to Remote log server') while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just send every log. Filtering will happen on the main process # logging handlers record_dict = record.__dict__ record_dict['msg'] = '[{}] {}'.format(to_unicode(prefix), to_unicode(record_dict['msg'])) sock.sendall(msgpack.dumps(record_dict, encoding='utf-8')) except (IOError, EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except log.warning( 'An exception occurred in the pytest salt logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) pytest-salt-2019.6.13/pytestsalt/salt/log_handlers/__init__.py0000644000175000017500000000003013401206133025041 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- pytest-salt-2019.6.13/pytestsalt/salt/__init__.py0000644000175000017500000000003013401206133022400 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- pytest-salt-2019.6.13/pytestsalt/salt/loader.py0000644000175000017500000000053513401206133022121 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.salt.loader ~~~~~~~~~~~~~~~~~~~~~~ Salt loader support ''' # Import python libs import os THIS_MODULE_DIR = os.path.abspath(os.path.dirname(__file__)) def engines_dirs(): yield os.path.join(THIS_MODULE_DIR, 'engines') def log_handlers_dirs(): yield os.path.join(THIS_MODULE_DIR, 'log_handlers') pytest-salt-2019.6.13/pytestsalt/__init__.py0000644000175000017500000000116513413140722021453 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' PyTest Salt Plugin ''' # Import Python libs import re # Import pytest salt libs from pytestsalt._version import get_versions # Store the version attribute __version__ = get_versions()['version'] del get_versions # Define __version_info__ attribute VERSION_INFO_REGEX = re.compile( r'(?P[\d]{4})\.(?P[\d]{1,2})\.(?P[\d]{1,2})' r'(?:\.dev0\+(?P[\d]+)\.(?:.*))?' ) try: __version_info__ = tuple([int(p) for p in VERSION_INFO_REGEX.match(__version__).groups() if p]) except AttributeError: __version_info__ = (-1, -1, -1) finally: del VERSION_INFO_REGEX pytest-salt-2019.6.13/pytestsalt/fixtures/0000755000175000017500000000000013500170424021207 5ustar vampasvampas00000000000000pytest-salt-2019.6.13/pytestsalt/fixtures/log.py0000644000175000017500000000314113477153405022356 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.log ~~~~~~~~~~~~~~~~~~~~~~~ Log server fixture which creates a server that receives log records from external process to log them in the current process ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals #import sys import logging # Import pytest libs import pytest #if sys.version_info > (3, 5): # from pytestsalt.utils.log_server_asyncio import log_server_asyncio as salt_log_server #else: # from pytestsalt.utils.log_server_tornado import log_server_tornado as salt_log_server from pytestsalt.utils.log_server_tornado import log_server_tornado as salt_log_server log = logging.getLogger(__name__) @pytest.fixture(scope='session') def log_server_level(request): # If PyTest has no logging configured, default to ERROR level levels = [logging.ERROR] logging_plugin = request.config.pluginmanager.get_plugin('logging-plugin') try: level = logging_plugin.log_cli_handler.level if level is not None: levels.append(level) except AttributeError: # PyTest CLI logging not configured pass try: level = logging_plugin.log_file_level if level is not None: levels.append(level) except AttributeError: # PyTest Log File logging not configured pass level_str = logging.getLevelName(min(levels)) return level_str @pytest.fixture(scope='session') def log_server(salt_log_port): log.info('Starting log server') salt_log_server(salt_log_port) log.info('Log Server Started') # Run tests yield pytest-salt-2019.6.13/pytestsalt/fixtures/ports.py0000644000175000017500000002212213423632164022737 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.ports ~~~~~~~~~~~~~~~~~~~~~~~~~ Pytest salt plugin ports fixtures ''' # Import python libs from __future__ import absolute_import # Import 3rd-party libs import pytest # Import pytestsalt libs from pytestsalt.utils import get_unused_localhost_port @pytest.fixture def master_publish_port(): ''' Returns an unused localhost port for the master publish interface ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_publish_port(): ''' Returns an unused localhost port for the master publish interface ''' return get_unused_localhost_port() @pytest.fixture def master_return_port(): ''' Returns an unused localhost port for the master return interface ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_return_port(): ''' Returns an unused localhost port for the master return interface ''' return get_unused_localhost_port() @pytest.fixture def master_tcp_master_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_tcp_master_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_tcp_master_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_tcp_master_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_tcp_master_publish_pull(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_tcp_master_publish_pull(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_tcp_master_workers(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_tcp_master_workers(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_engine_port(): ''' Returns an unused localhost port for the pytest salt master engine ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_engine_port(): ''' Returns an unused localhost port for the pytest session salt master engine ''' return get_unused_localhost_port() @pytest.fixture def master_of_masters_publish_port(): ''' Returns an unused localhost port for the master publish interface ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_of_masters_publish_port(): ''' Returns an unused localhost port for the master publish interface ''' return get_unused_localhost_port() @pytest.fixture def master_of_masters_return_port(): ''' Returns an unused localhost port for the master return interface ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_of_masters_return_port(): ''' Returns an unused localhost port for the master return interface ''' return get_unused_localhost_port() @pytest.fixture def master_of_masters_master_tcp_master_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_of_masters_master_tcp_master_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_of_masters_master_tcp_master_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_of_masters_master_tcp_master_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_of_masters_master_tcp_master_publish_pull(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_of_masters_master_tcp_master_publish_pull(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_of_masters_master_tcp_master_workers(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_of_masters_master_tcp_master_workers(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def master_of_masters_engine_port(): ''' Returns an unused localhost port for the pytest salt master engine ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_master_of_masters_engine_port(): ''' Returns an unused localhost port for the pytest session salt master engine ''' return get_unused_localhost_port() @pytest.fixture def minion_tcp_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_minion_tcp_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def minion_tcp_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_minion_tcp_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def proxy_tcp_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_proxy_tcp_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def proxy_tcp_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_proxy_tcp_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def minion_engine_port(): ''' Returns an unused localhost port for the pytest salt minion engine ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_minion_engine_port(): ''' Returns an unused localhost port for the pytest session salt minion engine ''' return get_unused_localhost_port() @pytest.fixture def secondary_minion_tcp_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_secondary_minion_tcp_pub_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def secondary_minion_tcp_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_secondary_minion_tcp_pull_port(): ''' Returns an unused localhost port ''' return get_unused_localhost_port() @pytest.fixture def secondary_minion_engine_port(): ''' Returns an unused localhost port for the pytest salt secondary minion engine ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_secondary_minion_engine_port(): ''' Returns an unused localhost port for the pytest session salt secondary minion engine ''' return get_unused_localhost_port() @pytest.fixture def proxy_engine_port(): ''' Returns an unused localhost port for the pytest salt proxy engine ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_proxy_engine_port(): ''' Returns an unused localhost port for the pytest session salt proxy engine ''' return get_unused_localhost_port() @pytest.fixture def syndic_engine_port(): ''' Returns an unused localhost port for the pytest salt syndic engine ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_syndic_engine_port(): ''' Returns an unused localhost port for the pytest session salt syndic engine ''' return get_unused_localhost_port() @pytest.fixture def sshd_port(): ''' Returns an unused localhost port to run an sshd server ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def session_sshd_port(): ''' Returns an unused localhost port to run a session scoped sshd server ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def log_server_port(): ''' Returns an unused localhost port for the pytest logging manager ''' return get_unused_localhost_port() @pytest.fixture(scope='session') def salt_log_port(log_server_port): ''' Returns the log_server_port fixture value for backwards compatibility ''' return log_server_port pytest-salt-2019.6.13/pytestsalt/fixtures/stats.py0000644000175000017500000000756313475514547022755 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.stats ~~~~~~~~~~~~~~~~~~~~~~~~~ Test session process stats fixtures ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import os import sys from collections import OrderedDict # Import 3rd-party libs import psutil # Import pytest libs import pytest from _pytest.terminal import TerminalReporter IS_WINDOWS = sys.platform.startswith('win') class SaltTerminalReporter(TerminalReporter): def __init__(self, config): TerminalReporter.__init__(self, config) @pytest.hookimpl(trylast=True) def pytest_sessionstart(self, session): TerminalReporter.pytest_sessionstart(self, session) self._session = session def pytest_runtest_logreport(self, report): TerminalReporter.pytest_runtest_logreport(self, report) if self.verbosity <= 0: return if report.when != 'call': return if self.config.getoption('--sys-stats') is False: return if self.verbosity > 1: self.ensure_newline() self.section('Processes Statistics', sep='-', bold=True) left_padding = len(max(['System'] + list(self._session.stats_processes), key=len)) template = ' ...{} {} - CPU: {:6.2f} % MEM: {:6.2f} %' if not IS_WINDOWS: template += ' SWAP: {:6.2f} %' template += '\n' self.write( template.format( '.' * (left_padding - len('System')), 'System', psutil.cpu_percent(), psutil.virtual_memory().percent, psutil.swap_memory().percent ) ) for name, psproc in self._session.stats_processes.items(): with psproc.oneshot(): cpu = psproc.cpu_percent() mem = psproc.memory_percent('vms') dots = '.' * (left_padding - len(name)) if not IS_WINDOWS: swap = psproc.memory_percent('swap') formatted = template.format(dots, name, cpu, mem, swap) else: formatted = template.format(dots, name, cpu, mem) self.write(formatted) def _get_progress_information_message(self): msg = TerminalReporter._get_progress_information_message(self) if self.verbosity <= 0: return msg if self.config.getoption('--sys-stats') is False: return msg if self.verbosity == 1: msg = ' [CPU:{}%] [MEM:{}%]{}'.format(psutil.cpu_percent(), psutil.virtual_memory().percent, msg) return msg def pytest_sessionstart(session): session.stats_processes = OrderedDict(( ('Test Suite Run', psutil.Process(os.getpid())), )) def pytest_addoption(parser): ''' register argparse-style options and ini-style config values. ''' output_options_group = parser.getgroup('Output Options') output_options_group.addoption( '--sys-stats', default=False, action='store_true', help='Print System CPU and MEM statistics after each test execution.' ) @pytest.mark.trylast def pytest_configure(config): ''' called after command line options have been parsed and all plugins and initial conftest files been loaded. ''' # Register our terminal reporter if not getattr(config, 'slaveinput', None): standard_reporter = config.pluginmanager.getplugin('terminalreporter') salt_reporter = SaltTerminalReporter(standard_reporter.config) config.pluginmanager.unregister(standard_reporter) config.pluginmanager.register(salt_reporter, 'terminalreporter') pytest-salt-2019.6.13/pytestsalt/fixtures/__init__.py0000644000175000017500000000013613401206133023315 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures ~~~~~~~~~~~~~~~~~~~ pytest salt fixtures ''' pytest-salt-2019.6.13/pytestsalt/fixtures/dirs.py0000644000175000017500000004625513423632164022546 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.dirs ~~~~~~~~~~~~~~~~~~~~~~~~ pytest salt directories related fixtures ''' # pylint: disable=redefined-outer-name # Import Python libs from __future__ import absolute_import import logging import os import stat # Import 3rd-party libs import pytest # Import pytest-salt libs import pytestsalt.salt.engines import pytestsalt.salt.log_handlers log = logging.getLogger(__name__) ROOT_DIR = 'root' MOM_ROOT_DIR = 'mom-root' SECONDARY_ROOT_DIR = 'secondary-root' SESSION_ROOT_DIR = 'session-root' SESSION_MOM_ROOT_DIR = 'session-mom-root' SESSION_SECONDARY_ROOT_DIR = 'session-secondary-root' @pytest.fixture def root_dir(tempdir): ''' Return the function scoped salt root dir ''' return tempdir.mkdir(ROOT_DIR) @pytest.fixture(scope='session') def session_root_dir(tempdir): ''' Return the session scoped salt root dir ''' return tempdir.mkdir(SESSION_ROOT_DIR) @pytest.fixture def master_of_masters_root_dir(tempdir): ''' Return the function scoped salt master of masters root dir ''' return tempdir.mkdir(MOM_ROOT_DIR) @pytest.fixture(scope='session') def session_master_of_masters_root_dir(tempdir): ''' Return the session scoped salt master of masters root dir ''' return tempdir.mkdir(SESSION_MOM_ROOT_DIR) @pytest.fixture def secondary_root_dir(tempdir): ''' Return the function scoped salt secondary root dir ''' return tempdir.mkdir(SECONDARY_ROOT_DIR) @pytest.fixture(scope='session') def session_secondary_root_dir(tempdir): ''' Return the session scoped salt secondary root dir ''' return tempdir.mkdir(SESSION_SECONDARY_ROOT_DIR) @pytest.fixture def conf_dir(root_dir): ''' Fixture which returns the salt configuration directory path. Creates the directory if it does not yet exist. ''' dirname = root_dir.join('conf') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_conf_dir(session_root_dir): ''' Fixture which returns the salt configuration directory path. Creates the directory if it does not yet exist. ''' dirname = session_root_dir.join('conf') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_conf_dir(master_of_masters_conf_dir): ''' Fixture which returns the salt configuration directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_root_dir.join('conf') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_conf_dir(session_master_of_masters_root_dir): ''' Fixture which returns the salt configuration directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_root_dir.join('conf') dirname.ensure(dir=True) return dirname @pytest.fixture def secondary_conf_dir(secondary_root_dir): ''' Fixture which returns the salt secondary configuration directory path. Creates the directory if it does not yet exist. ''' dirname = secondary_root_dir.join('conf') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_secondary_conf_dir(session_secondary_root_dir): ''' Fixture which returns the salt secondary configuration directory path. Creates the directory if it does not yet exist. ''' dirname = session_secondary_root_dir.join('conf') dirname.ensure(dir=True) return dirname @pytest.fixture def syndic_conf_dir(root_dir): ''' Fixture which returns the salt syndic configuration directory path. Creates the directory if it does not yet exist. Even though the salt syndic will read from both the master and minion configuration files, we'll store copies on this directory for complete separation, ie, to don't include syndic config options in either of the master and minion configuration files. ''' dirname = root_dir.join('syndic-conf') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_syndic_conf_dir(session_root_dir): ''' Fixture which returns the salt syndic configuration directory path. Creates the directory if it does not yet exist. Even though the salt syndic will read from both the master and minion configuration files, we'll store copies on this directory for complete separation, ie, to don't include syndic config options in either of the master and minion configuration files. ''' dirname = session_root_dir.join('syndic-conf') dirname.ensure(dir=True) return dirname @pytest.fixture def master_config_includes_dir(conf_dir): ''' Fixture which returns the salt master configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = conf_dir.join('master.d') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_config_includes_dir(session_conf_dir): ''' Fixture which returns the salt master configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = session_conf_dir.join('master.d') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_config_includes_dir(master_of_masters_conf_dir): ''' Fixture which returns the salt master configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_conf_dir.join('master.d') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_config_includes_dir(session_master_of_masters_conf_dir): ''' Fixture which returns the salt master configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_conf_dir.join('master.d') dirname.ensure(dir=True) return dirname @pytest.fixture def minion_config_includes_dir(conf_dir): ''' Fixture which returns the salt minion configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = conf_dir.join('minion.d') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_minion_config_includes_dir(session_conf_dir): ''' Fixture which returns the salt minion configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = session_conf_dir.join('minion.d') dirname.ensure(dir=True) return dirname @pytest.fixture def secondary_minion_config_includes_dir(secondary_conf_dir): ''' Fixture which returns the salt secondary minion configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = secondary_conf_dir.join('minion.d') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_secondary_minion_config_includes_dir(session_secondary_conf_dir): ''' Fixture which returns the salt secondary minion configuration includes directory path. Creates the directory if it does not yet exist. ''' dirname = session_secondary_conf_dir.join('minion.d') dirname.ensure(dir=True) return dirname @pytest.fixture def integration_files_dir(root_dir): ''' Fixture which returns the salt integration files directory path. Creates the directory if it does not yet exist. ''' dirname = root_dir.join('integration-files') dirname.ensure(dir=True) return dirname @pytest.fixture def state_tree_root_dir(integration_files_dir): ''' Fixture which returns the salt state tree root directory path. Creates the directory if it does not yet exist. ''' dirname = integration_files_dir.join('state-tree') dirname.ensure(dir=True) return dirname @pytest.fixture def pillar_tree_root_dir(integration_files_dir): ''' Fixture which returns the salt pillar tree root directory path. Creates the directory if it does not yet exist. ''' dirname = integration_files_dir.join('pillar-tree') dirname.ensure(dir=True) return dirname @pytest.fixture def base_env_state_tree_root_dir(state_tree_root_dir): ''' Fixture which returns the salt base environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = state_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture def prod_env_state_tree_root_dir(state_tree_root_dir): ''' Fixture which returns the salt prod environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = state_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture def base_env_pillar_tree_root_dir(pillar_tree_root_dir): ''' Fixture which returns the salt base environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = pillar_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture def prod_env_pillar_tree_root_dir(pillar_tree_root_dir): ''' Fixture which returns the salt prod environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = pillar_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_integration_files_dir(master_of_masters_root_dir): ''' Fixture which returns the salt integration files directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_root_dir.join('integration-files') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_state_tree_root_dir(master_of_masters_integration_files_dir): ''' Fixture which returns the salt state tree root directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_integration_files_dir.join('state-tree') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_pillar_tree_root_dir(master_of_masters_integration_files_dir): ''' Fixture which returns the salt pillar tree root directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_integration_files_dir.join('pillar-tree') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_base_env_state_tree_root_dir(master_of_masters_state_tree_root_dir): ''' Fixture which returns the salt base environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_state_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_prod_env_state_tree_root_dir(master_of_masters_state_tree_root_dir): ''' Fixture which returns the salt prod environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_state_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_base_env_pillar_tree_root_dir(master_of_masters_pillar_tree_root_dir): ''' Fixture which returns the salt base environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_pillar_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture def master_of_masters_prod_env_pillar_tree_root_dir(master_of_masters_pillar_tree_root_dir): ''' Fixture which returns the salt prod environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = master_of_masters_pillar_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_integration_files_dir(session_root_dir): ''' Fixture which returns the salt integration files directory path. Creates the directory if it does not yet exist. ''' dirname = session_root_dir.join('integration-files') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_state_tree_root_dir(session_integration_files_dir): ''' Fixture which returns the salt state tree root directory path. Creates the directory if it does not yet exist. ''' dirname = session_integration_files_dir.join('state-tree') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_pillar_tree_root_dir(session_integration_files_dir): ''' Fixture which returns the salt pillar tree root directory path. Creates the directory if it does not yet exist. ''' dirname = session_integration_files_dir.join('pillar-tree') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_base_env_state_tree_root_dir(session_state_tree_root_dir): ''' Fixture which returns the salt base environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_state_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_prod_env_state_tree_root_dir(session_state_tree_root_dir): ''' Fixture which returns the salt prod environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_state_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_base_env_pillar_tree_root_dir(session_pillar_tree_root_dir): ''' Fixture which returns the salt base environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_pillar_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_prod_env_pillar_tree_root_dir(session_pillar_tree_root_dir): ''' Fixture which returns the salt prod environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_pillar_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_integration_files_dir(session_master_of_masters_root_dir): ''' Fixture which returns the salt integration files directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_root_dir.join('integration-files') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_state_tree_root_dir(session_master_of_masters_integration_files_dir): ''' Fixture which returns the salt state tree root directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_integration_files_dir.join('state-tree') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_pillar_tree_root_dir(session_master_of_masters_integration_files_dir): ''' Fixture which returns the salt pillar tree root directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_integration_files_dir.join('pillar-tree') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_base_env_state_tree_root_dir(session_master_of_masters_state_tree_root_dir): ''' Fixture which returns the salt base environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_state_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_prod_env_state_tree_root_dir(session_master_of_masters_state_tree_root_dir): ''' Fixture which returns the salt prod environment state tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_state_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_base_env_pillar_tree_root_dir(session_master_of_masters_pillar_tree_root_dir): ''' Fixture which returns the salt base environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_master_of_masters_pillar_tree_root_dir.join('base') dirname.ensure(dir=True) return dirname @pytest.fixture(scope='session') def session_master_of_masters_prod_env_pillar_tree_root_dir(session_master_of_masters_pillar_tree_root_dir): ''' Fixture which returns the salt prod environment pillar tree directory path. Creates the directory if it does not yet exist. ''' dirname = session_pillar_tree_root_dir.join('prod') dirname.ensure(dir=True) return dirname @pytest.fixture def sshd_config_dir(tempdir): ''' Return the path to a configuration directory for the sshd server ''' config_dir = tempdir.join('sshd') config_dir.ensure(dir=True) return config_dir @pytest.fixture(scope='session') def session_sshd_config_dir(tempdir): ''' Return the path to a configuration directory for a session scoped sshd server ''' config_dir = tempdir.join('session-sshd') config_dir.ensure(dir=True) return config_dir @pytest.fixture def sshd_priv_dir(): ''' Create the privdir for starting sshd on systems that do not have an sshd daemon already running ''' if not os.path.isdir('/var/run/sshd'): os.mkdir('/var/run/sshd/') os.chmod('/var/run/sshd/', stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) yield os.rmdir('/var/run/sshd') @pytest.fixture(scope='session') def session_sshd_priv_dir(): ''' Create the privdir for starting sshd on systems that do not have an sshd daemon already running ''' if not os.path.isdir('/var/run/sshd'): os.mkdir('/var/run/sshd/') os.chmod('/var/run/sshd/', stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) yield os.rmdir('/var/run/sshd') @pytest.fixture def ssh_config_dir(tempdir): ''' Return the path to a configuration directory for the ssh client ''' config_dir = tempdir.join('ssh-client') config_dir.ensure(dir=True) return config_dir @pytest.fixture(scope='session') def session_ssh_config_dir(tempdir): ''' Return the path to a configuration directory for a session scoped ssh client ''' config_dir = tempdir.join('session-ssh-client') config_dir.ensure(dir=True) return config_dir @pytest.fixture(scope='session') def log_handlers_dir(): ''' Return the directory name for the pytest-salt log handlers directory ''' return os.path.dirname(pytestsalt.salt.log_handlers.__file__) @pytest.fixture(scope='session') def engines_dir(): ''' Return the directory name for the pytest-salt engines directory ''' return os.path.dirname(pytestsalt.salt.engines.__file__) pytest-salt-2019.6.13/pytestsalt/fixtures/config.py0000644000175000017500000020552613500136554023046 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.config ~~~~~~~~~~~~~~~~~~~~~~~~~~ pytest salt configuration related fixtures ''' # pylint: disable=redefined-outer-name,too-many-arguments,too-many-locals # Import python libs from __future__ import absolute_import, print_function import os import sys import copy import pprint import logging import subprocess # Import 3rd-party libs import pytest IS_WINDOWS = sys.platform.startswith('win') if IS_WINDOWS: import win32api # pylint: disable=import-error else: import pwd DEFAULT_MOM_ID = 'pytest-salt-mom' DEFAULT_MASTER_ID = 'pytest-salt-master' DEFAULT_MINION_ID = 'pytest-salt-minion' DEFAULT_SYNDIC_ID = 'pytest-salt-syndic' DEFAULT_SECONDARY_MINION_ID = 'pytest-salt-sec-minion' DEFAULT_PROXY_MINION_ID = 'pytest-salt-proxy' DEFAULT_SESSION_MOM_ID = 'pytest-session-salt-mom' DEFAULT_SESSION_MASTER_ID = 'pytest-session-salt-master' DEFAULT_SESSION_MINION_ID = 'pytest-session-salt-minion' DEFAULT_SESSION_SYNDIC_ID = 'pytest-session-salt-syndic' DEFAULT_SESSION_SECONDARY_MINION_ID = 'pytest-session-salt-sec-minion' DEFAULT_SESSION_PROXY_MINION_ID = 'pytest-session-salt-proxy' log = logging.getLogger(__name__) class Counter(object): # pylint: disable=too-few-public-methods ''' Simple counter class which increases count on every call to it's instance ''' def __init__(self): self.counter = 0 def __call__(self): try: return self.counter finally: self.counter += 1 def pytest_addoption(parser): ''' Add pytest salt plugin daemons related options ''' saltparser = parser.getgroup('Salt Plugin Options') saltparser.addoption( '--cli-bin-dir', default=None, help=('Path to the bin directory where the salt CLI scripts can be ' 'found. Defaults to the directory name of the python executable ' 'running py.test') ) saltparser.addoption( '--salt-fail-hard', default=None, action='store_true', help=('If a salt daemon fails to start, the test is marked as XFailed. ' 'If this flag is passed, then a test failure is raised instead of XFail.') ) parser.addini( 'cli_bin_dir', default=None, help=('Path to the bin directory where the salt CLI scripts can be ' 'found. Defaults to the directory name of the python executable ' 'running py.test') ) parser.addini( 'salt_fail_hard', default=None, type='bool', help=('If a salt daemon fails to start, the test is marked as XFailed. ' 'If this flag is set, then a test failure is raised instead of XFail.') ) @pytest.hookimpl(trylast=True) def pytest_report_header(config, startdir): ''' return a string to be displayed as header info for terminal reporting. ''' # Store a reference to where the base directory of the project is config.startdir = startdir @pytest.fixture(scope='session') def python_executable_path(): ''' return the python executable path ''' return sys.executable @pytest.fixture(scope='session') def cli_bin_dir(request, python_executable_path): ''' Return the path to the CLI script directory to use ''' # Default to the directory of the current python executable return os.path.dirname(python_executable_path) @pytest.fixture(scope='session') def _cli_bin_dir(request, cli_bin_dir): ''' Return the path to the CLI script directory to use ''' path = request.config.getoption('cli_bin_dir') if path is not None: # We were passed --cli-bin-dir as a CLI option return os.path.expanduser(path) # The path was not passed as a CLI option path = request.config.getini('cli_bin_dir') if path: # We were passed cli_bin_dir as a INI option return os.path.expanduser(path) return cli_bin_dir @pytest.fixture(scope='session') def salt_fail_hard(request): ''' Return the salt fail hard value ''' return False @pytest.fixture(scope='session') def _salt_fail_hard(request, salt_fail_hard): ''' Return the salt fail hard value ''' fail_hard = request.config.getoption('salt_fail_hard') if fail_hard is not None: # We were passed --salt-fail-hard as a CLI option return fail_hard # The salt fail hard was not passed as a CLI option fail_hard = request.config.getini('salt_fail_hard') if fail_hard != []: # We were passed salt_fail_hard as a INI option return fail_hard return salt_fail_hard @pytest.fixture(scope='session') def running_username(): ''' Returns the current username ''' if IS_WINDOWS: return win32api.GetUserName() return pwd.getpwuid(os.getuid()).pw_name @pytest.fixture(scope='session') def salt_master_id_counter(): ''' Fixture which return a number to include in the master ID. Every call to this fixture increases the counter. ''' return Counter() @pytest.fixture(scope='session') def salt_master_of_masters_id_counter(): ''' Fixture which return a number to include in the master ID. Every call to this fixture increases the counter. ''' return Counter() @pytest.fixture(scope='session') def salt_minion_id_counter(): ''' Fixture which return a number to include in the minion ID. Every call to this fixture increases the counter. ''' return Counter() @pytest.fixture(scope='session') def salt_syndic_id_counter(): ''' Fixture which return a number to include in the syndic ID. Every call to this fixture increases the counter. ''' return Counter() @pytest.fixture(scope='session') def salt_proxy_id_counter(): ''' Fixture which return a number to include in the minion proxy ID. Every call to this fixture increases the counter. ''' return Counter() @pytest.fixture(scope='session') def cli_master_script_name(): ''' Return the CLI script basename ''' return 'salt-master' @pytest.fixture(scope='session') def cli_minion_script_name(): ''' Return the CLI script basename ''' return 'salt-minion' @pytest.fixture(scope='session') def cli_proxy_script_name(): ''' Return the CLI script basename ''' return 'salt-proxy' @pytest.fixture(scope='session') def cli_salt_script_name(): ''' Return the CLI script basename ''' return 'salt' @pytest.fixture(scope='session') def cli_run_script_name(): ''' Return the CLI script basename ''' return 'salt-run' @pytest.fixture(scope='session') def cli_key_script_name(): ''' Return the CLI script basename ''' return 'salt-key' @pytest.fixture(scope='session') def cli_call_script_name(): ''' Return the CLI script basename ''' return 'salt-call' @pytest.fixture(scope='session') def cli_syndic_script_name(): ''' Return the CLI script basename ''' return 'salt-syndic' @pytest.fixture(scope='session') def cli_ssh_script_name(): ''' Return the CLI script basename ''' return 'salt-ssh' @pytest.fixture def master_of_masters_id(salt_master_of_masters_id_counter): ''' Returns the master of masters id ''' return DEFAULT_MOM_ID + '-{}'.format(salt_master_of_masters_id_counter()) @pytest.fixture def master_id(salt_master_id_counter): ''' Returns the master id ''' return DEFAULT_MASTER_ID + '-{}'.format(salt_master_id_counter()) @pytest.fixture def minion_id(salt_minion_id_counter): ''' Returns the minion id ''' return DEFAULT_MINION_ID + '-{}'.format(salt_minion_id_counter()) @pytest.fixture def secondary_minion_id(salt_minion_id_counter): ''' Returns the secondary minion id ''' return DEFAULT_SECONDARY_MINION_ID + '-{}'.format(salt_minion_id_counter()) @pytest.fixture def syndic_id(salt_syndic_id_counter): ''' Returns the syndic id ''' return DEFAULT_SYNDIC_ID + '-{}'.format(salt_syndic_id_counter()) @pytest.fixture def proxy_id(salt_proxy_id_counter): ''' Returns the proxy minion id ''' return DEFAULT_PROXY_MINION_ID + '-{}'.format(salt_proxy_id_counter()) @pytest.fixture(scope='session') def session_master_of_masters_id(salt_master_of_masters_id_counter): ''' Returns the master of masters id ''' return DEFAULT_SESSION_MOM_ID + '-{}'.format(salt_master_of_masters_id_counter()) @pytest.fixture(scope='session') def session_master_id(salt_master_id_counter): ''' Returns the session scoped master id ''' return DEFAULT_SESSION_MASTER_ID + '-{}'.format(salt_master_id_counter()) @pytest.fixture(scope='session') def session_minion_id(salt_minion_id_counter): ''' Returns the session scoped minion id ''' return DEFAULT_SESSION_MINION_ID + '-{}'.format(salt_minion_id_counter()) @pytest.fixture(scope='session') def session_secondary_minion_id(salt_minion_id_counter): ''' Returns the session scoped secondary minion id ''' return DEFAULT_SESSION_SECONDARY_MINION_ID + '-{}'.format(salt_minion_id_counter()) @pytest.fixture(scope='session') def session_syndic_id(salt_syndic_id_counter): ''' Returns the session scoped syndic id ''' return DEFAULT_SESSION_SYNDIC_ID + '-{}'.format(salt_syndic_id_counter()) @pytest.fixture(scope='session') def session_proxy_id(salt_proxy_id_counter): ''' Returns the session scoped minion id ''' return DEFAULT_SESSION_PROXY_MINION_ID + '-{}'.format(salt_proxy_id_counter()) @pytest.fixture def master_config_file(conf_dir): ''' Returns the path to the salt master configuration file ''' return conf_dir.join('master').realpath().strpath @pytest.fixture def master_of_masters_config_file(master_of_masters_conf_dir): ''' Returns the path to the salt master configuration file ''' return master_of_masters_conf_dir.join('master').realpath().strpath @pytest.fixture def minion_config_file(conf_dir): ''' Returns the path to the salt minion configuration file ''' return conf_dir.join('minion').realpath().strpath @pytest.fixture def secondary_minion_config_file(secondary_conf_dir): ''' Returns the path to the salt secondary minion configuration file ''' return secondary_conf_dir.join('minion').realpath().strpath @pytest.fixture def proxy_config_file(conf_dir): ''' Returns the path to the salt minion configuration file ''' return conf_dir.join('proxy').realpath().strpath @pytest.fixture def master_config_overrides(): ''' This fixture should be implemented to overwrite default salt master configuration options. It will be applied over the loaded default options ''' @pytest.fixture def master_of_masters_config_overrides(): ''' This fixture should be implemented to overwrite default salt master configuration options. It will be applied over the loaded default options ''' @pytest.fixture def minion_config_overrides(): ''' This fixture should be implemented to overwrite default salt minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture def secondary_minion_config_overrides(): ''' This fixture should be implemented to overwrite default secondary salt minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture def syndic_config_overrides(): ''' This fixture should be implemented to overwrite default salt syndic minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture def proxy_config_overrides(): ''' This fixture should be implemented to overwrite default salt proxy minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_master_config_file(session_conf_dir): ''' Returns the path to the salt master configuration file ''' return session_conf_dir.join('master').realpath().strpath @pytest.fixture(scope='session') def session_master_of_masters_config_file(session_master_of_masters_conf_dir): ''' Returns the path to the salt master configuration file ''' return session_master_of_masters_conf_dir.join('master').realpath().strpath @pytest.fixture(scope='session') def session_minion_config_file(session_conf_dir): ''' Returns the path to the salt minion configuration file ''' return session_conf_dir.join('minion').realpath().strpath @pytest.fixture(scope='session') def session_secondary_minion_config_file(session_secondary_conf_dir): ''' Returns the path to the salt secondary minion configuration file ''' return session_secondary_conf_dir.join('minion').realpath().strpath @pytest.fixture(scope='session') def session_proxy_config_file(session_conf_dir): ''' Returns the path to the salt proxy configuration file ''' return session_conf_dir.join('proxy').realpath().strpath @pytest.fixture(scope='session') def session_master_config_overrides(): ''' This fixture should be implemented to overwrite default salt master configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_master_of_masters_config_overrides(): ''' This fixture should be implemented to overwrite default salt master configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_minion_config_overrides(): ''' This fixture should be implemented to overwrite default salt minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_secondary_minion_config_overrides(): ''' This fixture should be implemented to overwrite default secondary salt minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_syndic_config_overrides(): ''' This fixture should be implemented to overwrite default salt syndic minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_proxy_config_overrides(): ''' This fixture should be implemented to overwrite default salt proxy minion configuration options. It will be applied over the loaded default options ''' @pytest.fixture def master_log_prefix(master_id): return 'salt-master/{}'.format(master_id) @pytest.fixture(scope='session') def session_master_log_prefix(session_master_id): return 'salt-master/{}'.format(session_master_id) @pytest.fixture def master_of_masters_log_prefix(master_of_masters_id): return 'salt-master/{}'.format(master_of_masters_id) @pytest.fixture(scope='session') def session_master_of_masters_log_prefix(session_master_of_masters_id): return 'salt-master/{}'.format(session_master_of_masters_id) @pytest.fixture def minion_log_prefix(minion_id): return 'salt-minion/{}'.format(minion_id) @pytest.fixture(scope='session') def session_minion_log_prefix(session_minion_id): return 'salt-minion/{}'.format(session_minion_id) @pytest.fixture def proxy_log_prefix(minion_id): return 'salt-proxy/{}'.format(minion_id) @pytest.fixture(scope='session') def session_proxy_log_prefix(session_minion_id): return 'salt-proxy/{}'.format(session_minion_id) @pytest.fixture def secondary_minion_log_prefix(secondary_minion_id): return 'salt-minion/{}'.format(secondary_minion_id) @pytest.fixture(scope='session') def session_secondary_minion_log_prefix(session_secondary_minion_id): return 'salt-minion/{}'.format(session_secondary_minion_id) @pytest.fixture def syndic_log_prefix(syndic_id): return 'salt-syndic/{}'.format(syndic_id) @pytest.fixture(scope='session') def session_syndic_log_prefix(session_syndic_id): return 'salt-syndic/{}'.format(session_syndic_id) @pytest.fixture def salt_log_prefix(minion_id): return 'salt/{}'.format(minion_id) @pytest.fixture(scope='session') def session_salt_log_prefix(session_minion_id): return 'salt/{}'.format(session_minion_id) @pytest.fixture def salt_call_log_prefix(master_id): return 'salt-call/{}'.format(master_id) @pytest.fixture(scope='session') def session_salt_call_log_prefix(session_master_id): return 'salt-call/{}'.format(session_master_id) @pytest.fixture def salt_key_log_prefix(master_id): return 'salt-key/{}'.format(master_id) @pytest.fixture(scope='session') def session_salt_key_log_prefix(session_master_id): return 'salt-key/{}'.format(session_master_id) @pytest.fixture def salt_run_log_prefix(master_id): return 'salt-run/{}'.format(master_id) @pytest.fixture(scope='session') def session_salt_run_log_prefix(session_master_id): return 'salt-run/{}'.format(session_master_id) def apply_master_config(default_options, root_dir, config_file, publish_port, return_port, engine_port, config_overrides, master_id, base_env_state_tree_root_dirs, prod_env_state_tree_root_dirs, base_env_pillar_tree_root_dirs, prod_env_pillar_tree_root_dirs, running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, master_log_prefix, tcp_master_pub_port, tcp_master_pull_port, tcp_master_publish_pull, tcp_master_workers, direct_overrides=None): ''' This fixture will return the salt master configuration options after being overridden with any options passed from ``master_config_overrides`` ''' import pytestsalt.utils.compat as compat import salt.config import salt.utils import salt.utils.dictupdate as dictupdate import salt.utils.verify as salt_verify import salt.utils.yaml as yamlserialize _default_options = { 'id': master_id, 'interface': '127.0.0.1', 'root_dir': root_dir.strpath, 'publish_port': publish_port, 'ret_port': return_port, 'tcp_master_pub_port': tcp_master_pub_port, 'tcp_master_pull_port': tcp_master_pull_port, 'tcp_master_publish_pull': tcp_master_publish_pull, 'tcp_master_workers': tcp_master_workers, 'worker_threads': 3, 'pidfile': 'run/master.pid', 'pki_dir': 'pki', 'cachedir': 'cache', 'timeout': 3, 'sock_dir': '.salt-unix', 'open_mode': True, 'syndic_master': 'localhost', 'fileserver_list_cache_time': 0, 'fileserver_backend': ['roots'], 'pillar_opts': False, 'peer': { '.*': [ 'test.*' ] }, 'log_file': 'logs/master.log', 'log_level_logfile': 'debug', 'key_logfile': 'logs/key.log', 'token_dir': 'tokens', 'token_file': root_dir.join('ksfjhdgiuebfgnkefvsikhfjdgvkjahcsidk').strpath, 'file_buffer_size': 8192, 'user': running_username, 'log_fmt_console': "[%(levelname)-8s][%(name)-5s:%(lineno)-4d] %(message)s", 'log_fmt_logfile': "[%(asctime)s,%(msecs)03.0f][%(name)-5s:%(lineno)-4d][%(levelname)-8s] %(message)s", 'file_roots': { 'base': base_env_state_tree_root_dirs, 'prod': prod_env_state_tree_root_dirs, }, 'pillar_roots': { 'base': base_env_pillar_tree_root_dirs, 'prod': prod_env_pillar_tree_root_dirs, }, 'hash_type': 'sha256' } for varname in ('sock_dir',): # These are settings which are tested against and provided by Salt's test suite, so, # let's not override them if provided if varname in default_options: _default_options.pop(varname) # Merge in the initial default options with the internal _default_options dictupdate.update(default_options, _default_options, merge_lists=True) if config_overrides: # Merge in the default options with the master_config_overrides dictupdate.update(default_options, config_overrides, merge_lists=True) default_options.setdefault('engines', []) if 'pytest' not in default_options['engines']: default_options['engines'].append('pytest') if 'engines_dirs' not in default_options: default_options['engines_dirs'] = [] default_options['engines_dirs'].insert(0, engines_dir) default_options['pytest_engine_port'] = engine_port if 'log_handlers_dirs' not in default_options: default_options['log_handlers_dirs'] = [] default_options['log_handlers_dirs'].insert(0, log_handlers_dir) default_options['pytest_log_host'] = 'localhost' default_options['pytest_log_port'] = log_server_port default_options['pytest_log_level'] = log_server_level default_options['pytest_log_prefix'] = master_log_prefix if direct_overrides is not None: # We've been passed some direct override configuration. # Apply it! dictupdate.update(default_options, direct_overrides, merge_lists=True) log.info('Writing to configuration file %s. Configuration:\n%s', config_file, pprint.pformat(default_options)) # Write down the computed configuration into the config file with compat.fopen(config_file, 'w') as wfh: yamlserialize.safe_dump(default_options, wfh, default_flow_style=False) # Make sure to load the config file as a salt-master starting from CLI options = salt.config.master_config(config_file) # verify env to make sure all required directories are created and have the # right permissions verify_env_entries = [ os.path.join(options['pki_dir'], 'minions'), os.path.join(options['pki_dir'], 'minions_pre'), os.path.join(options['pki_dir'], 'minions_rejected'), os.path.join(options['pki_dir'], 'accepted'), os.path.join(options['pki_dir'], 'rejected'), os.path.join(options['pki_dir'], 'pending'), os.path.dirname(options['log_file']), options['token_dir'], #options['extension_modules'], options['sock_dir'], ] verify_env_entries += base_env_state_tree_root_dirs verify_env_entries += prod_env_state_tree_root_dirs verify_env_entries += base_env_pillar_tree_root_dirs verify_env_entries += prod_env_pillar_tree_root_dirs if default_options.get('transport', None) == 'raet': verify_env_entries.extend([ os.path.join(options['cachedir'], 'raet'), ]) else: verify_env_entries.extend([ os.path.join(options['cachedir'], 'jobs'), ]) try: salt_verify.verify_env( # pylint: disable=unexpected-keyword-arg verify_env_entries, running_username, sensitive_dirs=[options['pki_dir']] ) except TypeError: salt_verify.verify_env( verify_env_entries, running_username, pki_dir=options['pki_dir'] ) return options @pytest.fixture def master_default_options(): return {} @pytest.fixture def master_config(root_dir, master_default_options, master_config_file, master_publish_port, master_return_port, master_engine_port, master_config_overrides, master_id, base_env_state_tree_root_dir, prod_env_state_tree_root_dir, base_env_pillar_tree_root_dir, prod_env_pillar_tree_root_dir, running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, master_log_prefix, master_tcp_master_pub_port, master_tcp_master_pull_port, master_tcp_master_publish_pull, master_tcp_master_workers): ''' This fixture will return the salt master configuration options after being overridden with any options passed from ``master_config_overrides`` ''' return apply_master_config(master_default_options, root_dir, master_config_file, master_publish_port, master_return_port, master_engine_port, master_config_overrides, master_id, [base_env_state_tree_root_dir.strpath], [prod_env_state_tree_root_dir.strpath], [base_env_pillar_tree_root_dir.strpath], [prod_env_pillar_tree_root_dir.strpath], running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, master_log_prefix, master_tcp_master_pub_port, master_tcp_master_pull_port, master_tcp_master_publish_pull, master_tcp_master_workers) @pytest.fixture(scope='session') def session_master_default_options(): return {} @pytest.fixture(scope='session') def session_master_config(session_root_dir, session_master_default_options, session_master_config_file, session_master_publish_port, session_master_return_port, session_master_engine_port, session_master_config_overrides, session_master_id, session_base_env_state_tree_root_dir, session_prod_env_state_tree_root_dir, session_base_env_pillar_tree_root_dir, session_prod_env_pillar_tree_root_dir, running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, session_master_log_prefix, session_master_tcp_master_pub_port, session_master_tcp_master_pull_port, session_master_tcp_master_publish_pull, session_master_tcp_master_workers): ''' This fixture will return the salt master configuration options after being overridden with any options passed from ``session_master_config_overrides`` ''' return apply_master_config(session_master_default_options, session_root_dir, session_master_config_file, session_master_publish_port, session_master_return_port, session_master_engine_port, session_master_config_overrides, session_master_id, [session_base_env_state_tree_root_dir.strpath], [session_prod_env_state_tree_root_dir.strpath], [session_base_env_pillar_tree_root_dir.strpath], [session_prod_env_pillar_tree_root_dir.strpath], running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, session_master_log_prefix, session_master_tcp_master_pub_port, session_master_tcp_master_pull_port, session_master_tcp_master_publish_pull, session_master_tcp_master_workers) @pytest.fixture(scope='session') def master_of_masters_default_options(): return {} @pytest.fixture def master_of_masters_config(master_of_masters_root_dir, master_of_masters_config_file, master_of_masters_default_options, master_of_masters_publish_port, master_of_masters_return_port, master_of_masters_engine_port, master_of_masters_config_overrides, master_of_masters_id, master_of_masters_base_env_state_tree_root_dir, master_of_masters_prod_env_state_tree_root_dir, master_of_masters_base_env_pillar_tree_root_dir, master_of_masters_prod_env_pillar_tree_root_dir, running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, master_of_masters_log_prefix, master_of_masters_master_tcp_master_pub_port, master_of_masters_master_tcp_master_pull_port, master_of_masters_master_tcp_master_publish_pull, master_of_masters_master_tcp_master_workers): ''' This fixture will return the salt master configuration options after being overridden with any options passed from ``master_config_overrides`` ''' direct_overrides = { 'order_masters': True, } return apply_master_config(master_of_masters_default_options, master_of_masters_root_dir, master_of_masters_config_file, master_of_masters_publish_port, master_of_masters_return_port, master_of_masters_engine_port, master_of_masters_config_overrides, master_of_masters_id, [master_of_masters_base_env_state_tree_root_dir.strpath], [master_of_masters_prod_env_state_tree_root_dir.strpath], [master_of_masters_base_env_pillar_tree_root_dir.strpath], [master_of_masters_prod_env_pillar_tree_root_dir.strpath], running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, master_of_masters_log_prefix, master_of_masters_master_tcp_master_pub_port, master_of_masters_master_tcp_master_pull_port, master_of_masters_master_tcp_master_publish_pull, master_of_masters_master_tcp_master_workers, direct_overrides=direct_overrides) @pytest.fixture(scope='session') def session_master_of_masters_default_options(): return {} @pytest.fixture(scope='session') def session_master_of_masters_config(session_master_of_masters_root_dir, session_master_of_masters_config_file, session_master_of_masters_publish_port, session_master_of_masters_return_port, session_master_of_masters_engine_port, session_master_of_masters_default_options, session_master_of_masters_config_overrides, session_master_of_masters_id, session_base_env_state_tree_root_dir, session_prod_env_state_tree_root_dir, session_base_env_pillar_tree_root_dir, session_prod_env_pillar_tree_root_dir, running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, session_master_of_masters_log_prefix, session_master_of_masters_master_tcp_master_pub_port, session_master_of_masters_master_tcp_master_pull_port, session_master_of_masters_master_tcp_master_publish_pull, session_master_of_masters_master_tcp_master_workers): ''' This fixture will return the salt master configuration options after being overridden with any options passed from ``session_master_config_overrides`` ''' direct_overrides = { 'order_masters': True, } return apply_master_config(session_master_of_masters_default_options, session_master_of_masters_root_dir, session_master_of_masters_config_file, session_master_of_masters_publish_port, session_master_of_masters_return_port, session_master_of_masters_engine_port, session_master_of_masters_config_overrides, session_master_of_masters_id, [session_base_env_state_tree_root_dir.strpath], [session_prod_env_state_tree_root_dir.strpath], [session_base_env_pillar_tree_root_dir.strpath], [session_prod_env_pillar_tree_root_dir.strpath], running_username, log_server_port, log_server_level, engines_dir, log_handlers_dir, session_master_of_masters_log_prefix, session_master_of_masters_master_tcp_master_pub_port, session_master_of_masters_master_tcp_master_pull_port, session_master_of_masters_master_tcp_master_publish_pull, session_master_of_masters_master_tcp_master_workers, direct_overrides=direct_overrides) def apply_minion_config(default_options, root_dir, config_file, return_port, config_overrides, minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, minion_log_prefix, tcp_pub_port, tcp_pull_port, direct_overrides=None): ''' This fixture will return the salt minion configuration options after being overridden with any options passed from ``config_overrides`` ''' import pytestsalt.utils.compat as compat import salt.config import salt.utils import salt.utils.dictupdate as dictupdate import salt.utils.verify as salt_verify import salt.utils.yaml as yamlserialize _default_options = { 'root_dir': root_dir.strpath, 'interface': '127.0.0.1', 'master': '127.0.0.1', 'master_port': return_port, 'tcp_pub_port': tcp_pub_port, 'tcp_pull_port': tcp_pull_port, 'id': minion_id, 'pidfile': 'run/minion.pid', 'pki_dir': 'pki', 'cachedir': 'cache', 'sock_dir': '.salt-unix', 'log_file': 'logs/minion.log', 'log_level_logfile': 'debug', 'loop_interval': 0.05, 'open_mode': True, 'user': running_username, #'multiprocessing': False, 'log_fmt_console': "[%(levelname)-8s][%(name)-5s:%(lineno)-4d] %(message)s", 'log_fmt_logfile': "[%(asctime)s,%(msecs)03.0f][%(name)-5s:%(lineno)-4d][%(levelname)-8s] %(message)s", 'hash_type': 'sha256' } for varname in ('sock_dir',): # These are settings which are tested against and provided by Salt's test suite, so, # let's not override them if provided if varname in default_options: _default_options.pop(varname) # Merge in the initial default options with the internal _default_options dictupdate.update(default_options, _default_options, merge_lists=True) if config_overrides: # Merge in the default options with the minion_config_overrides dictupdate.update(default_options, config_overrides, merge_lists=True) if 'log_handlers_dirs' not in default_options: default_options['log_handlers_dirs'] = [] default_options['log_handlers_dirs'].insert(0, log_handlers_dir) default_options['pytest_log_host'] = 'localhost' default_options['pytest_log_port'] = log_server_port default_options['pytest_log_level'] = log_server_level default_options['pytest_log_prefix'] = minion_log_prefix if direct_overrides is not None: # We've been passed some direct override configuration. # Apply it! dictupdate.update(default_options, direct_overrides, merge_lists=True) log.info('Writing to configuration file %s. Configuration:\n%s', config_file, pprint.pformat(default_options)) # Write down the computed configuration into the config file with compat.fopen(config_file, 'w') as wfh: yamlserialize.safe_dump(default_options, wfh, default_flow_style=False) # Make sure to load the config file as a salt-master starting from CLI options = salt.config.minion_config(config_file) # verify env to make sure all required directories are created and have the # right permissions verify_env_entries = [ os.path.join(options['pki_dir'], 'minions'), os.path.join(options['pki_dir'], 'minions_pre'), os.path.join(options['pki_dir'], 'minions_rejected'), os.path.join(options['pki_dir'], 'accepted'), os.path.join(options['pki_dir'], 'rejected'), os.path.join(options['pki_dir'], 'pending'), os.path.dirname(options['log_file']), os.path.join(options['cachedir'], 'proc'), #options['extension_modules'], options['sock_dir'], ] try: # Salt > v2017.7.x salt_verify.verify_env( # pylint: disable=unexpected-keyword-arg verify_env_entries, running_username, sensitive_dirs=[options['pki_dir']] ) except TypeError: # Salt <= v2017.7.x salt_verify.verify_env( verify_env_entries, running_username, pki_dir=options['pki_dir'] ) return options def apply_proxy_config(default_options, root_dir, config_file, return_port, config_overrides, proxy_id, running_username, log_server_port, log_server_level, log_handlers_dir, proxy_log_prefix, tcp_pub_port, tcp_pull_port, direct_overrides=None): ''' This fixture will return the salt proxy configuration options after being overridden with any options passed from ``config_overrides`` ''' import pytestsalt.utils.compat as compat import salt.config import salt.utils import salt.utils.dictupdate as dictupdate import salt.utils.verify as salt_verify import salt.utils.yaml as yamlserialize _default_options = { 'root_dir': root_dir.strpath, 'interface': '127.0.0.1', 'master': '127.0.0.1', 'master_port': return_port, 'tcp_pub_port': tcp_pub_port, 'tcp_pull_port': tcp_pull_port, 'id': proxy_id, 'pidfile': 'run/proxy.pid', 'pki_dir': 'pki', 'cachedir': 'cache', 'sock_dir': '.salt-unix', 'log_file': 'logs/proxy.log', 'log_level_logfile': 'debug', 'loop_interval': 0.05, 'open_mode': True, 'user': running_username, 'log_fmt_console': "[%(levelname)-8s][%(name)-5s:%(lineno)-4d] %(message)s", 'log_fmt_logfile': "[%(asctime)s,%(msecs)03.0f][%(name)-5s:%(lineno)-4d][%(levelname)-8s] %(message)s", 'hash_type': 'sha256', 'add_proxymodule_to_opts': False, 'proxy': {'proxytype': 'dummy'} } for varname in ('sock_dir',): # These are settings which are tested against and provided by Salt's test suite, so, # let's not override them if provided if varname in default_options: _default_options.pop(varname) # Merge in the initial default options with the internal _default_options dictupdate.update(default_options, _default_options, merge_lists=True) if config_overrides: # Merge in the default options with the proxy_config_overrides dictupdate.update(default_options, config_overrides, merge_lists=True) if 'log_handlers_dirs' not in default_options: default_options['log_handlers_dirs'] = [] default_options['log_handlers_dirs'].insert(0, log_handlers_dir) default_options['pytest_log_host'] = 'localhost' default_options['pytest_log_port'] = log_server_port default_options['pytest_log_level'] = log_server_level default_options['pytest_log_prefix'] = proxy_log_prefix if direct_overrides is not None: # We've been passed some direct override configuration. # Apply it! dictupdate.update(default_options, direct_overrides, merge_lists=True) log.info('Writing to configuration file %s. Configuration:\n%s', config_file, pprint.pformat(default_options)) # Write down the computed configuration into the config file with compat.fopen(config_file, 'w') as wfh: yamlserialize.safe_dump(default_options, wfh, default_flow_style=False) # Make sure to load the config file as a salt-master starting from CLI options = salt.config.proxy_config(config_file) # verify env to make sure all required directories are created and have the # right permissions verify_env_entries = [ os.path.dirname(options['log_file']), options['sock_dir'], ] try: # Salt > v2017.7.x salt_verify.verify_env( # pylint: disable=unexpected-keyword-arg verify_env_entries, running_username, sensitive_dirs=[options['pki_dir']] ) except TypeError: # Salt <= v2017.7.x salt_verify.verify_env( verify_env_entries, running_username, pki_dir=options['pki_dir'] ) return options @pytest.fixture def minion_default_options(): return {} @pytest.fixture def minion_config(root_dir, minion_config_file, master_return_port, minion_default_options, minion_config_overrides, minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, minion_log_prefix, minion_tcp_pub_port, minion_tcp_pull_port): ''' This fixture will return the salt minion configuration options after being overrided with any options passed from ``minion_config_overrides`` ''' return apply_minion_config(minion_default_options, root_dir, minion_config_file, master_return_port, minion_config_overrides, minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, minion_log_prefix, minion_tcp_pub_port, minion_tcp_pull_port) @pytest.fixture(scope='session') def session_minion_default_options(): return {} @pytest.fixture(scope='session') def session_minion_config(session_root_dir, session_minion_config_file, session_master_return_port, session_minion_default_options, session_minion_config_overrides, session_minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, session_minion_log_prefix, session_minion_tcp_pub_port, session_minion_tcp_pull_port): ''' This fixture will return the session salt minion configuration options after being overrided with any options passed from ``session_minion_config_overrides`` ''' return apply_minion_config(session_minion_default_options, session_root_dir, session_minion_config_file, session_master_return_port, session_minion_config_overrides, session_minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, session_minion_log_prefix, session_minion_tcp_pub_port, session_minion_tcp_pull_port) @pytest.fixture def secondary_minion_default_options(): return {} @pytest.fixture def secondary_minion_config(secondary_root_dir, secondary_minion_config_file, master_return_port, secondary_minion_default_options, secondary_minion_config_overrides, secondary_minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, secondary_minion_log_prefix, secondary_minion_tcp_pub_port, secondary_minion_tcp_pull_port): ''' This fixture will return the secondary salt minion configuration options after being overrided with any options passed from ``secondary_minion_config_overrides`` ''' return apply_minion_config(secondary_minion_default_options, secondary_root_dir, secondary_minion_config_file, master_return_port, secondary_minion_config_overrides, secondary_minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, secondary_minion_log_prefix, secondary_minion_tcp_pub_port, secondary_minion_tcp_pull_port) @pytest.fixture(scope='session') def session_secondary_minion_default_options(): return {} @pytest.fixture(scope='session') def session_secondary_minion_config(session_secondary_root_dir, session_secondary_minion_config_file, session_master_return_port, session_secondary_minion_default_options, session_secondary_minion_config_overrides, session_secondary_minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, session_secondary_minion_log_prefix, session_secondary_minion_tcp_pub_port, session_secondary_minion_tcp_pull_port): ''' This fixture will return the session salt minion configuration options after being overrided with any options passed from ``session_secondary_minion_config_overrides`` ''' return apply_minion_config(session_secondary_minion_default_options, session_secondary_root_dir, session_secondary_minion_config_file, session_master_return_port, session_secondary_minion_config_overrides, session_secondary_minion_id, running_username, log_server_port, log_server_level, log_handlers_dir, session_secondary_minion_log_prefix, session_secondary_minion_tcp_pub_port, session_secondary_minion_tcp_pull_port) def apply_syndic_config(syndic_default_options, master_config_file, syndic_conf_dir, syndic_config_overrides, running_username, log_server_port, log_server_level, syndic_log_prefix, syndic_id, log_handlers_dir, root_dir): ''' This fixture will return the salt syndic configuration options after being overridden with any options passed from ``config_overrides`` ''' import pytestsalt.utils.compat as compat import salt.config import salt.utils import salt.utils.dictupdate as dictupdate import salt.utils.yaml as yamlserialize with compat.fopen(master_config_file) as rfh: master_config = yamlserialize.safe_load(rfh.read()) master_overrides = { 'syndic_master': 'localhost', 'syndic_master_port': master_config['ret_port'], 'syndic_pidfile': 'run/salt-syndic.pid', 'syndic_user': running_username, 'syndic_log_file': 'logs/syndic.log', } if syndic_default_options: # Override pytest salt overrides with any value comming in from syndic_default_options master_overrides.update(syndic_default_options) dictupdate.update(master_config, master_overrides, merge_lists=True) syndic_master_config_file = syndic_conf_dir.join('master').realpath().strpath # Write down the master computed configuration into the config file log.info('Writing to configuration file %s. Configuration:\n%s', syndic_master_config_file, pprint.pformat(master_config)) with compat.fopen(syndic_master_config_file, 'w') as wfh: yamlserialize.safe_dump(master_config, wfh, default_flow_style=False) syndic_config_file = syndic_conf_dir.join('minion').realpath().strpath direct_overrides = copy.deepcopy(master_overrides) direct_overrides.update({ 'id': syndic_id, }) apply_minion_config(syndic_default_options, root_dir, syndic_config_file, master_config['ret_port'], # master_return_port syndic_config_overrides, syndic_id, running_username, log_server_port, log_server_level, log_handlers_dir, syndic_log_prefix, None, # minion_tcp_pub_port, None, # minion_tcp_pull_port, direct_overrides=direct_overrides) return salt.config.syndic_config(syndic_master_config_file, syndic_config_file) @pytest.fixture def syndic_default_options(): return {} @pytest.fixture def syndic_config(master_config, master_config_file, syndic_conf_dir, syndic_default_options, syndic_config_overrides, running_username, log_server_port, log_server_level, syndic_log_prefix, syndic_id, log_handlers_dir, root_dir): ''' This fixture will return the salt syndic configuration options after being overridden with any options passed from ``syndic_config_overrides`` ''' return apply_syndic_config(syndic_default_options, master_config_file, syndic_conf_dir, syndic_config_overrides, running_username, log_server_port, log_server_level, syndic_log_prefix, syndic_id, log_handlers_dir, root_dir) @pytest.fixture(scope='session') def session_syndic_default_options(): return {} @pytest.fixture(scope='session') def session_syndic_config(session_master_config_file, session_syndic_conf_dir, session_syndic_default_options, session_syndic_config_overrides, running_username, log_server_port, log_server_level, session_syndic_log_prefix, session_syndic_id, log_handlers_dir, session_root_dir): ''' This fixture will return the salt syndic configuration options after being overridden with any options passed from ``syndic_config_overrides`` ''' return apply_syndic_config(session_syndic_default_options, session_master_config_file, session_syndic_conf_dir, session_syndic_config_overrides, running_username, log_server_port, log_server_level, session_syndic_log_prefix, session_syndic_id, log_handlers_dir, session_root_dir) @pytest.fixture def proxy_default_options(): return {} @pytest.fixture def proxy_config(root_dir, proxy_config_file, master_return_port, proxy_default_options, proxy_config_overrides, proxy_id, running_username, log_server_port, log_server_level, log_handlers_dir, proxy_log_prefix, proxy_tcp_pub_port, proxy_tcp_pull_port): ''' This fixture will return the salt proxy configuration options after being overrided with any options passed from ``proxy_config_overrides`` ''' return apply_proxy_config(proxy_default_options, root_dir, proxy_config_file, master_return_port, proxy_config_overrides, proxy_id, running_username, log_server_port, log_server_level, log_handlers_dir, proxy_log_prefix, proxy_tcp_pub_port, proxy_tcp_pull_port) @pytest.fixture(scope='session') def session_proxy_default_options(): return {} @pytest.fixture(scope='session') def session_proxy_config(session_root_dir, session_proxy_config_file, session_master_return_port, session_proxy_default_options, session_proxy_config_overrides, session_proxy_id, running_username, log_server_port, log_server_level, log_handlers_dir, session_proxy_log_prefix, session_proxy_tcp_pub_port, session_proxy_tcp_pull_port): ''' This fixture will return the session salt proxy configuration options after being overrided with any options passed from ``session_proxy_config_overrides`` ''' return apply_proxy_config(session_proxy_default_options, session_root_dir, session_proxy_config_file, session_master_return_port, session_proxy_config_overrides, session_proxy_id, running_username, log_server_port, log_server_level, log_handlers_dir, session_proxy_log_prefix, session_proxy_tcp_pub_port, session_proxy_tcp_pull_port) @pytest.fixture def salt_ssh_log_prefix(sshd_port): return 'salt-ssh/{}'.format(sshd_port) @pytest.fixture(scope='session') def session_salt_ssh_log_prefix(session_sshd_port): return 'salt-ssh/{}'.format(session_sshd_port) @pytest.fixture def ssh_client_key(ssh_config_dir): ''' The ssh client key ''' return _generate_ssh_key(ssh_config_dir.join('test_key').realpath().strpath) @pytest.fixture(scope='session') def session_ssh_client_key(session_ssh_config_dir): ''' The ssh client key ''' return _generate_ssh_key(session_ssh_config_dir.join('test_key').realpath().strpath) def _sshd_config_lines(sshd_port): ''' Return a list of lines which will make the sshd_config file ''' return [ 'Port {}'.format(sshd_port), 'ListenAddress 127.0.0.1', 'Protocol 2', 'UsePrivilegeSeparation yes', '# Turn strict modes off so that we can operate in /tmp', 'StrictModes no', '# Lifetime and size of ephemeral version 1 server key', 'KeyRegenerationInterval 3600', 'ServerKeyBits 1024', '# Logging', 'SyslogFacility AUTH', 'LogLevel INFO', '# Authentication:', 'LoginGraceTime 120', 'PermitRootLogin without-password', 'StrictModes yes', 'RSAAuthentication yes', 'PubkeyAuthentication yes', '#AuthorizedKeysFile %h/.ssh/authorized_keys', '#AuthorizedKeysFile key_test.pub', '# Don\'t read the user\'s ~/.rhosts and ~/.shosts files', 'IgnoreRhosts yes', '# For this to work you will also need host keys in /etc/ssh_known_hosts', 'RhostsRSAAuthentication no', '# similar for protocol version 2', 'HostbasedAuthentication no', '#IgnoreUserKnownHosts yes', '# To enable empty passwords, change to yes (NOT RECOMMENDED)', 'PermitEmptyPasswords no', '# Change to yes to enable challenge-response passwords (beware issues with', '# some PAM modules and threads)', 'ChallengeResponseAuthentication no', '# Change to no to disable tunnelled clear text passwords', 'PasswordAuthentication no', 'X11Forwarding no', 'X11DisplayOffset 10', 'PrintMotd no', 'PrintLastLog yes', 'TCPKeepAlive yes', '#UseLogin no', 'AcceptEnv LANG LC_*', 'Subsystem sftp /usr/lib/openssh/sftp-server', '#UsePAM yes', ] @pytest.fixture def sshd_config_lines(sshd_port): ''' Return a list of lines which will make the sshd_config file ''' return _sshd_config_lines(sshd_port) @pytest.fixture(scope='session') def session_sshd_config_lines(session_sshd_port): ''' Return a list of lines which will make the sshd_config file ''' return _sshd_config_lines(session_sshd_port) @pytest.fixture def write_sshd_config(sshd_config_dir, sshd_config_lines, ssh_client_key): ''' This fixture will write the necessary configuration to run an SSHD server to be used in tests ''' return _write_sshd_config(sshd_config_dir, sshd_config_lines, ssh_client_key) @pytest.fixture(scope='session') def session_write_sshd_config(session_sshd_config_dir, session_sshd_config_lines, session_ssh_client_key): ''' This fixture will write the necessary configuration to run an SSHD server to be used in tests ''' return _write_sshd_config(session_sshd_config_dir, session_sshd_config_lines, session_ssh_client_key) @pytest.fixture def _write_sshd_config(sshd_config_dir, sshd_config_lines, ssh_client_key): ''' This fixture will write the necessary configuration to run an SSHD server to be used in tests ''' import pytestsalt.utils.compat as compat sshd = compat.which('sshd') if not sshd: pytest.skip('"sshd" not found.') # Generate server key server_key_dir = sshd_config_dir.realpath().strpath server_dsa_key_file = os.path.join(server_key_dir, 'ssh_host_dsa_key') server_ecdsa_key_file = os.path.join(server_key_dir, 'ssh_host_ecdsa_key') server_ed25519_key_file = os.path.join(server_key_dir, 'ssh_host_ed25519_key') _generate_ssh_key(server_dsa_key_file, 'dsa', 1024) _generate_ssh_key(server_ecdsa_key_file, 'ecdsa', 521) _generate_ssh_key(server_ed25519_key_file, 'ed25519', 521) sshd_config = sshd_config_lines[:] sshd_config.append('AuthorizedKeysFile {}.pub'.format(ssh_client_key)) sshd_config.append('HostKey {}'.format(server_dsa_key_file)) sshd_config.append('HostKey {}'.format(server_ecdsa_key_file)) sshd_config.append('HostKey {}'.format(server_ed25519_key_file)) with compat.fopen(sshd_config_dir.join('sshd_config').realpath().strpath, 'w') as wfh: wfh.write('\n'.join(sshd_config)) @pytest.fixture def sshd_server_log_prefix(sshd_port): ''' The log prefix to use for the sshd server fixture ''' return 'sshd-server/{}'.format(sshd_port) @pytest.fixture(scope='session') def session_sshd_server_log_prefix(session_sshd_port): ''' The log prefix to use for the sshd server fixture ''' return 'session-sshd-server/{}'.format(session_sshd_port) def _generate_ssh_key(key_path, key_type='ecdsa', key_size=521): ''' Generate an SSH key ''' import pytestsalt.utils.compat as compat log.debug('Generating ssh key(type: %s; size: %d; path: %s;)', key_type, key_size, key_path) keygen = compat.which('ssh-keygen') if not keygen: pytest.skip('"ssh-keygen" not found') keygen_process = subprocess.Popen( [ keygen, '-t', key_type, '-b', str(key_size), '-C', '"$(whoami)@$(hostname)-$(date -I)"', '-f', os.path.basename(key_path), '-P', '' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=os.path.dirname(key_path) ) _, keygen_err = keygen_process.communicate() if keygen_err: pytest.skip( 'ssh-keygen had errors generating {}({}:{}): {}'.format( os.path.basename(key_path), key_type, key_size, keygen_err ) ) return key_path @pytest.fixture def roster_config_file(conf_dir): ''' Returns the path to the salt-ssh roster configuration file ''' return conf_dir.join('roster').realpath().strpath @pytest.fixture(scope='session') def session_roster_config_file(session_conf_dir): ''' Returns the path to the salt-ssh roster configuration file ''' return session_conf_dir.join('roster').realpath().strpath @pytest.fixture def roster_config_overrides(): ''' This fixture should be implemented to overwrite default salt-ssh roster configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_roster_config_overrides(): ''' This fixture should be implemented to overwrite default salt-ssh roster configuration options. It will be applied over the loaded default options ''' def _roster_config(config_file, config, config_overrides): import pytestsalt.utils.compat as compat import salt.utils.yaml as yamlserialize if config_overrides: config.update(config_overrides) with compat.fopen(config_file, 'w') as wfh: yamlserialize.safe_dump(config, wfh, default_flow_style=False) return config @pytest.fixture def roster_config(roster_config_file, roster_config_overrides, running_username, ssh_client_key, master_config, sshd_port): config = { 'localhost': { 'host': '127.0.0.1', 'port': sshd_port, 'user': running_username, 'priv': ssh_client_key } } return _roster_config(roster_config_file, config, roster_config_overrides) @pytest.fixture(scope='session') def session_roster_config(session_roster_config_file, session_roster_config_overrides, running_username, session_ssh_client_key, session_sshd_port, session_master_config): config = { 'localhost': { 'host': '127.0.0.1', 'port': session_sshd_port, 'user': running_username, 'priv': session_ssh_client_key } } return _roster_config(session_roster_config_file, config, session_roster_config_overrides) @pytest.mark.trylast def pytest_configure(config): pytest.helpers.utils.register(apply_master_config) pytest.helpers.utils.register(apply_minion_config) pytest.helpers.utils.register(apply_syndic_config) pytest-salt-2019.6.13/pytestsalt/fixtures/daemons.py0000644000175000017500000014472613467034234023237 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' pytestsalt.fixtures.daemons ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Salt daemons fixtures ''' # pylint: disable=redefined-outer-name # Import python libs from __future__ import absolute_import, print_function import os import sys import logging import subprocess # Import 3rd-party libs import pytest from pytestsalt.utils import SaltCliScriptBase, SaltDaemonScriptBase, start_daemon log = logging.getLogger(__name__) @pytest.fixture def salt_cli_default_timeout(): ''' Default timeout for CLI tools ''' @pytest.fixture(scope='session') def salt_version(_cli_bin_dir, cli_master_script_name, python_executable_path): ''' Return the salt version for the CLI install ''' import salt # pylint: disable=unused-import try: import salt.ext.six as six except ImportError: import six args = [ os.path.join(_cli_bin_dir, cli_master_script_name), '--version' ] if sys.platform.startswith('win'): # We always need to prefix the call arguments with the python executable on windows args.insert(0, python_executable_path) proc = subprocess.Popen(args, stdout=subprocess.PIPE) stdout, stderr = proc.communicate() version = stdout.split()[1] if six.PY3: version = version.decode(__salt_system_encoding__) return version @pytest.fixture def salt_master_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-master and after ending it. ''' # Prep routines go here # Start the salt-master yield # Clean routines go here @pytest.fixture def salt_master_after_start(salt_master): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-master and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_master(request, conf_dir, master_id, master_config, salt_master_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument master_log_prefix, cli_master_script_name, _cli_bin_dir, _salt_fail_hard): ''' Returns a running salt-master ''' return start_daemon(request, daemon_name='salt-master', daemon_id=master_id, daemon_log_prefix=master_log_prefix, daemon_cli_script_name=cli_master_script_name, daemon_config=master_config, daemon_config_dir=conf_dir, daemon_class=SaltMaster, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=conf_dir, start_timeout=60) @pytest.fixture(scope='session') def session_salt_master_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-master and after ending it. ''' # Prep routines go here # Start the salt-master yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_master_after_start(session_salt_master): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-master and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_master(request, session_conf_dir, session_master_id, session_master_config, session_salt_master_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument session_master_log_prefix, cli_master_script_name, _cli_bin_dir, _salt_fail_hard): ''' Returns a running salt-master ''' return start_daemon(request, daemon_name='salt-master', daemon_id=session_master_id, daemon_log_prefix=session_master_log_prefix, daemon_cli_script_name=cli_master_script_name, daemon_config=session_master_config, daemon_config_dir=session_conf_dir, daemon_class=SaltMaster, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=session_conf_dir, start_timeout=60) @pytest.fixture def salt_master_of_masters_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-master and after ending it. ''' # Prep routines go here # Start the salt-master yield # Clean routines go here @pytest.fixture def salt_master_of_masters_after_start(salt_master_of_masters): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-master and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_master_of_masters(request, master_of_masters_conf_dir, master_of_masters_id, master_of_masters_config, salt_master_of_masters_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument master_of_masters_log_prefix, cli_master_script_name, _cli_bin_dir, _salt_fail_hard): ''' Returns a running salt-master ''' return start_daemon(request, daemon_name='salt-master', daemon_id=master_of_masters_id, daemon_log_prefix=master_of_masters_log_prefix, daemon_cli_script_name=cli_master_script_name, daemon_config=master_of_masters_config, daemon_config_dir=master_of_masters_conf_dir, daemon_class=SaltMaster, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=master_of_masters_conf_dir, start_timeout=60) @pytest.fixture(scope='session') def session_salt_master_of_masters_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-master and after ending it. ''' # Prep routines go here # Start the salt-master yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_master_of_masters_after_start(session_salt_master_of_masters): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-master and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_master_of_masters(request, session_master_of_masters_conf_dir, session_master_of_masters_id, session_master_of_masters_config, session_salt_master_of_masters_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument session_master_of_masters_log_prefix, cli_master_script_name, _cli_bin_dir, _salt_fail_hard): ''' Returns a running salt-master ''' return start_daemon(request, daemon_name='salt-master', daemon_id=session_master_of_masters_id, daemon_log_prefix=session_master_of_masters_log_prefix, daemon_cli_script_name=cli_master_script_name, daemon_config=session_master_of_masters_config, daemon_config_dir=session_master_of_masters_conf_dir, daemon_class=SaltMaster, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=session_master_of_masters_conf_dir, start_timeout=60) @pytest.fixture def salt_minion_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-minion and after ending it. ''' # Prep routines go here # Start the salt-minion yield # Clean routines go here @pytest.fixture def salt_minion_after_start(salt_minion): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-minion and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_minion(request, salt_master, minion_id, minion_config, salt_minion_before_start, # pylint: disable=unused-argument minion_log_prefix, cli_minion_script_name, log_server, _cli_bin_dir, _salt_fail_hard, conf_dir): # pylint: disable=unused-argument ''' Returns a running salt-minion ''' return start_daemon(request, daemon_name='salt-minion', daemon_id=minion_id, daemon_log_prefix=minion_log_prefix, daemon_cli_script_name=cli_minion_script_name, daemon_config=minion_config, daemon_config_dir=conf_dir, daemon_class=SaltMinion, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=conf_dir, start_timeout=60) @pytest.fixture(scope='session') def session_salt_minion_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-minion and after ending it. ''' # Prep routines go here # Start the salt-minion yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_minion_after_start(session_salt_minion): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-minion and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_minion(request, session_salt_master, session_minion_id, session_minion_config, session_salt_minion_before_start, # pylint: disable=unused-argument session_minion_log_prefix, cli_minion_script_name, log_server, _cli_bin_dir, session_conf_dir, _salt_fail_hard): ''' Returns a running salt-minion ''' return start_daemon(request, daemon_name='salt-minion', daemon_id=session_minion_id, daemon_log_prefix=session_minion_log_prefix, daemon_cli_script_name=cli_minion_script_name, daemon_config=session_minion_config, daemon_config_dir=session_conf_dir, daemon_class=SaltMinion, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=session_conf_dir, start_timeout=60) @pytest.fixture def secondary_salt_minion_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-minion and after ending it. ''' # Prep routines go here # Start the salt-minion yield # Clean routines go here @pytest.fixture def secondary_salt_minion_after_start(secondary_salt_minion): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-minion and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def secondary_salt_minion(request, salt_master, secondary_minion_id, secondary_minion_config, secondary_salt_minion_before_start, # pylint: disable=unused-argument secondary_minion_log_prefix, cli_minion_script_name, log_server, _cli_bin_dir, _salt_fail_hard, conf_dir, secondary_conf_dir): # pylint: disable=unused-argument ''' Returns a running salt-minion ''' return start_daemon(request, daemon_name='salt-minion', daemon_id=secondary_minion_id, daemon_log_prefix=secondary_minion_log_prefix, daemon_cli_script_name=cli_minion_script_name, daemon_config=secondary_minion_config, daemon_config_dir=secondary_conf_dir, daemon_class=SaltMinion, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=conf_dir, start_timeout=60) @pytest.fixture(scope='session') def session_secondary_salt_minion_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-minion and after ending it. ''' # Prep routines go here # Start the salt-minion yield # Clean routines go here @pytest.fixture(scope='session') def session_secondary_salt_minion_after_start(session_secondary_salt_minion): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-minion and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_secondary_salt_minion(request, session_salt_master, session_secondary_minion_id, session_secondary_minion_config, session_secondary_salt_minion_before_start, # pylint: disable=unused-argument session_secondary_minion_log_prefix, cli_minion_script_name, log_server, _cli_bin_dir, _salt_fail_hard, session_conf_dir, session_secondary_conf_dir): ''' Returns a running salt-minion ''' return start_daemon(request, daemon_name='salt-minion', daemon_id=session_secondary_minion_id, daemon_log_prefix=session_secondary_minion_log_prefix, daemon_cli_script_name=cli_minion_script_name, daemon_config=session_secondary_minion_config, daemon_config_dir=session_secondary_conf_dir, daemon_class=SaltMinion, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=session_conf_dir, start_timeout=60) @pytest.fixture def salt_syndic_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-syndic and after ending it. ''' # Prep routines go here # Start the daemon yield # Clean routines go here @pytest.fixture def salt_syndic_after_start(salt_syndic): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-master and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_syndic(request, syndic_conf_dir, syndic_id, syndic_config, salt_syndic_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument syndic_log_prefix, cli_syndic_script_name, conf_dir, _cli_bin_dir, _salt_fail_hard): ''' Returns a running salt-syndic ''' return start_daemon(request, daemon_name='salt-syndic', daemon_id=syndic_id, daemon_log_prefix=syndic_log_prefix, daemon_cli_script_name=cli_syndic_script_name, daemon_config=syndic_config, daemon_config_dir=syndic_conf_dir, daemon_class=SaltSyndic, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=conf_dir, start_timeout=60) @pytest.fixture(scope='session') def session_salt_syndic_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-syndic and after ending it. ''' # Prep routines go here # Start the daemon yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_syndic_after_start(session_salt_syndic): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-master and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_syndic(request, session_syndic_conf_dir, session_syndic_id, session_syndic_config, session_salt_syndic_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument session_syndic_log_prefix, cli_syndic_script_name, session_conf_dir, _cli_bin_dir, _salt_fail_hard): ''' Returns a running salt-syndic ''' return start_daemon(request, daemon_name='salt-syndic', daemon_id=session_syndic_id, daemon_log_prefix=session_syndic_log_prefix, daemon_cli_script_name=cli_syndic_script_name, daemon_config=session_syndic_config, daemon_config_dir=session_syndic_conf_dir, daemon_class=SaltSyndic, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=session_conf_dir, start_timeout=60) @pytest.fixture def salt_proxy_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-proxy and after ending it. ''' # Prep routines go here # Start the salt-proxy yield # Clean routines go here @pytest.fixture def salt_proxy_after_start(salt_proxy): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-proxy and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_proxy(request, salt_master, proxy_id, proxy_config, salt_proxy_before_start, # pylint: disable=unused-argument proxy_log_prefix, cli_proxy_script_name, log_server, _cli_bin_dir, _salt_fail_hard, conf_dir): # pylint: disable=unused-argument ''' Returns a running salt-proxy ''' return start_daemon(request, daemon_name='salt-proxy', daemon_id=proxy_id, daemon_log_prefix=proxy_log_prefix, daemon_cli_script_name=cli_proxy_script_name, daemon_config=proxy_config, daemon_config_dir=conf_dir, daemon_class=SaltProxy, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=conf_dir, start_timeout=60) @pytest.fixture(scope='session') def session_salt_proxy_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the salt-minion and after ending it. ''' # Prep routines go here # Start the salt-proxy yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_proxy_after_start(session_salt_proxy): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-proxy and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_proxy(request, session_salt_master, session_proxy_id, session_proxy_config, session_salt_proxy_before_start, # pylint: disable=unused-argument session_proxy_log_prefix, cli_proxy_script_name, log_server, _cli_bin_dir, session_conf_dir, _salt_fail_hard): ''' Returns a running salt-proxy ''' return start_daemon(request, daemon_name='salt-proxy', daemon_id=session_proxy_id, daemon_log_prefix=session_proxy_log_prefix, daemon_cli_script_name=cli_proxy_script_name, daemon_config=session_proxy_config, daemon_config_dir=session_conf_dir, daemon_class=SaltProxy, bin_dir_path=_cli_bin_dir, fail_hard=_salt_fail_hard, event_listener_config_dir=session_conf_dir, start_timeout=60) @pytest.fixture def salt_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-call and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture def salt_after_start(salt): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt CLI script and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt(request, salt_minion, minion_config, _cli_bin_dir, conf_dir, cli_salt_script_name, salt_cli_default_timeout, salt_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument salt_log_prefix): # pylint: disable=unused-argument ''' Returns a salt fixture ''' salt = Salt(request, minion_config, conf_dir, _cli_bin_dir, salt_log_prefix, cli_script_name=cli_salt_script_name, default_timeout=salt_cli_default_timeout) yield salt @pytest.fixture(scope='session') def session_salt_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-call and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_after_start(session_salt): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt CLI script and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt(request, session_salt_minion, session_minion_config, _cli_bin_dir, session_conf_dir, cli_salt_script_name, salt_cli_default_timeout, session_salt_before_start, # pylint: disable=unused-argument log_server, # pylint: disable=unused-argument session_salt_log_prefix): # pylint: disable=unused-argument ''' Returns a salt fixture ''' salt = Salt(request, session_minion_config, session_conf_dir, _cli_bin_dir, session_salt_log_prefix, cli_script_name=cli_salt_script_name, default_timeout=salt_cli_default_timeout) yield salt @pytest.fixture def salt_call_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-call and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture def salt_call_after_start(salt_call): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-call and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_call(request, salt_minion, salt_call_before_start, salt_call_log_prefix, cli_call_script_name, minion_config, conf_dir, _cli_bin_dir, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' Returns a salt_call fixture ''' salt_call = SaltCall(request, minion_config, conf_dir, _cli_bin_dir, salt_call_log_prefix, cli_script_name=cli_call_script_name, default_timeout=salt_cli_default_timeout) yield salt_call @pytest.fixture(scope='session') def session_salt_call_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-call and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_call_after_start(session_salt_call): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-call and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_call(request, session_salt_minion, session_salt_call_before_start, session_salt_call_log_prefix, cli_call_script_name, session_minion_config, session_conf_dir, _cli_bin_dir, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' Returns a salt_call fixture ''' salt_call = SaltCall(request, session_minion_config, session_conf_dir, _cli_bin_dir, session_salt_call_log_prefix, cli_script_name=cli_call_script_name, default_timeout=salt_cli_default_timeout) yield salt_call @pytest.fixture def salt_key_before_start(): ''' this fixture should be overridden if you need to do some preparation work before running salt-key and clean up after ending it. ''' # prep routines go here # run! yield # clean routines go here @pytest.fixture def salt_key_after_start(salt_key): ''' this fixture should be overridden if you need to do some preparation and clean up work after starting the salt-key and before ending it. ''' # prep routines go here # resume test execution yield # clean routines go here @pytest.fixture def salt_key(request, salt_master, salt_key_before_start, salt_key_log_prefix, cli_key_script_name, master_config, conf_dir, _cli_bin_dir, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' returns a salt_key fixture ''' salt_key = SaltKey(request, master_config, conf_dir, _cli_bin_dir, salt_key_log_prefix, cli_script_name=cli_key_script_name, default_timeout=salt_cli_default_timeout) yield salt_key @pytest.fixture(scope='session') def session_salt_key_before_start(): ''' this fixture should be overridden if you need to do some preparation work before running salt-key and clean up after ending it. ''' # prep routines go here # run! yield # clean routines go here @pytest.fixture(scope='session') def session_salt_key_after_start(session_salt_key): ''' this fixture should be overridden if you need to do some preparation and clean up work after starting the salt-key and before ending it. ''' # prep routines go here # resume test execution yield # clean routines go here @pytest.fixture(scope='session') def session_salt_key(request, session_salt_master, session_salt_key_before_start, session_salt_key_log_prefix, cli_key_script_name, session_master_config, session_conf_dir, _cli_bin_dir, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' returns a salt_key fixture ''' salt_key = SaltKey(request, session_master_config, session_conf_dir, _cli_bin_dir, session_salt_key_log_prefix, cli_script_name=cli_key_script_name, default_timeout=salt_cli_default_timeout) yield salt_key @pytest.fixture def salt_run_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-run and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture def salt_run_after_start(salt_run): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-run and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_run(request, salt_master, salt_run_before_start, # pylint: disable=unused-argument salt_run_log_prefix, cli_run_script_name, conf_dir, master_config, _cli_bin_dir, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' Returns a salt_run fixture ''' salt_run = SaltRun(request, master_config, conf_dir, _cli_bin_dir, salt_run_log_prefix, cli_script_name=cli_run_script_name, default_timeout=salt_cli_default_timeout) yield salt_run @pytest.fixture(scope='session') def session_salt_run_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-run and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_run_after_start(session_salt_run): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-run and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_run(request, session_salt_master, session_salt_run_before_start, # pylint: disable=unused-argument session_salt_run_log_prefix, cli_run_script_name, session_conf_dir, session_master_config, _cli_bin_dir, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' Returns a salt_run fixture ''' salt_run = SaltRun(request, session_master_config, session_conf_dir, _cli_bin_dir, session_salt_run_log_prefix, cli_script_name=cli_run_script_name, default_timeout=salt_cli_default_timeout) yield salt_run @pytest.fixture def salt_ssh_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-ssh and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture def salt_ssh_after_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-ssh and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def salt_ssh(request, sshd_server, conf_dir, salt_ssh_before_start, # pylint: disable=unused-argument salt_ssh_log_prefix, _cli_bin_dir, cli_ssh_script_name, roster_config, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' Returns a salt_ssh fixture ''' salt_ssh = SaltSSH(request, roster_config, conf_dir, _cli_bin_dir, salt_ssh_log_prefix, cli_script_name=cli_ssh_script_name, default_timeout=salt_cli_default_timeout) yield salt_ssh @pytest.fixture(scope='session') def session_salt_ssh_before_start(): ''' This fixture should be overridden if you need to do some preparation work before running salt-ssh and clean up after ending it. ''' # Prep routines go here # Run! yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_ssh_after_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the salt-ssh and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_salt_ssh(request, session_sshd_server, session_conf_dir, session_salt_ssh_before_start, # pylint: disable=unused-argument session_salt_ssh_log_prefix, _cli_bin_dir, cli_ssh_script_name, session_roster_config, salt_cli_default_timeout, log_server): # pylint: disable=unused-argument ''' Returns a salt_ssh fixture ''' salt_ssh = SaltSSH(request, session_roster_config, session_conf_dir, _cli_bin_dir, session_salt_ssh_log_prefix, cli_script_name=cli_ssh_script_name, default_timeout=salt_cli_default_timeout) yield salt_ssh @pytest.fixture def sshd_server_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the sshd server and after ending it. ''' # Prep routines go here # Start the sshd server yield # Clean routines go here @pytest.fixture def sshd_server_after_start(sshd_server): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the sshd server and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture def sshd_server(request, write_sshd_config, # pylint: disable=unused-argument sshd_server_before_start, # pylint: disable=unused-argument sshd_server_log_prefix, sshd_port, sshd_config_dir, sshd_priv_dir, log_server): # pylint: disable=unused-argument ''' Returns a running sshd server ''' log.info('[%s] Starting pytest sshd server at port %s', sshd_server_log_prefix, sshd_port) attempts = 0 while attempts <= 3: # pylint: disable=too-many-nested-blocks attempts += 1 process = SSHD(request, {'port': sshd_port}, sshd_config_dir, None, # bin_dir_path, sshd_server_log_prefix, cli_script_name='sshd') process.start() if process.is_alive(): try: connectable = process.wait_until_running(timeout=10) if connectable is False: connectable = process.wait_until_running(timeout=5) if connectable is False: process.terminate() if attempts >= 3: pytest.xfail( 'The pytest sshd server({}) has failed to confirm ' 'running status after {} attempts'.format(sshd_port, attempts)) continue except Exception as exc: # pylint: disable=broad-except log.exception('[%s] %s', sshd_server_log_prefix, exc, exc_info=True) process.terminate() if attempts >= 3: pytest.xfail(str(exc)) continue log.info( '[%s] The pytest sshd server(%s) is running and accepting commands ' 'after %d attempts', sshd_server_log_prefix, sshd_port, attempts ) yield process break else: process.terminate() continue else: pytest.xfail( 'The pytest sshd server({}) has failed to start after {} attempts'.format( sshd_port, attempts-1 ) ) log.info('[%s] Stopping pytest sshd server(%s)', sshd_server_log_prefix, sshd_port) process.terminate() log.info('[%s] pytest sshd server(%s) stopped', sshd_server_log_prefix, sshd_port) @pytest.fixture(scope='session') def session_sshd_server_before_start(): ''' This fixture should be overridden if you need to do some preparation and clean up work before starting the sshd server and after ending it. ''' # Prep routines go here # Start the sshd server yield # Clean routines go here @pytest.fixture def session_sshd_server_after_start(sshd_server): ''' This fixture should be overridden if you need to do some preparation and clean up work after starting the sshd server and before ending it. ''' # Prep routines go here # Resume test execution yield # Clean routines go here @pytest.fixture(scope='session') def session_sshd_server(request, session_write_sshd_config, # pylint: disable=unused-argument session_sshd_server_before_start, # pylint: disable=unused-argument session_sshd_server_log_prefix, session_sshd_port, session_sshd_config_dir, session_sshd_priv_dir, log_server): # pylint: disable=unused-argument ''' Returns a running sshd server ''' log.info('[%s] Starting pytest sshd server at port %s', session_sshd_server_log_prefix, session_sshd_port) attempts = 0 while attempts <= 3: # pylint: disable=too-many-nested-blocks attempts += 1 process = SSHD(request, {'port': session_sshd_port}, session_sshd_config_dir, None, # bin_dir_path, session_sshd_server_log_prefix, cli_script_name='sshd') process.start() if process.is_alive(): try: connectable = process.wait_until_running(timeout=10) if connectable is False: connectable = process.wait_until_running(timeout=5) if connectable is False: process.terminate() if attempts >= 3: pytest.xfail( 'The pytest sshd server({}) has failed to confirm ' 'running status after {} attempts'.format(session_sshd_port, attempts)) continue except Exception as exc: # pylint: disable=broad-except log.exception('[%s] %s', session_sshd_server_log_prefix, exc, exc_info=True) process.terminate() if attempts >= 3: pytest.xfail(str(exc)) continue log.info( '[%s] The pytest sshd server(%s) is running and accepting commands ' 'after %d attempts', session_sshd_server_log_prefix, session_sshd_port, attempts ) yield process break else: process.terminate() continue else: pytest.xfail( 'The pytest sshd server({}) has failed to start after {} attempts'.format( session_sshd_port, attempts-1 ) ) log.info('[%s] Stopping pytest sshd server(%s)', session_sshd_server_log_prefix, session_sshd_port) process.terminate() log.info('[%s] pytest sshd server(%s) stopped', session_sshd_server_log_prefix, session_sshd_port) class Salt(SaltCliScriptBase): ''' Class which runs salt-call commands ''' def get_minion_tgt(self, **kwargs): return kwargs.pop('minion_tgt', self.config['id']) def process_output(self, tgt, stdout, stderr, cli_cmd): # pylint: disable=signature-differs if 'No minions matched the target. No command was sent, no jid was assigned.\n' in stdout: stdout = stdout.split('\n', 1)[1:][0] old_stdout = None if '--show-jid' in cli_cmd and stdout.startswith('jid: '): old_stdout = stdout stdout = stdout.split('\n', 1)[-1].strip() stdout, stderr, json_out = SaltCliScriptBase.process_output(self, tgt, stdout, stderr, cli_cmd) if old_stdout is not None: stdout = old_stdout if json_out: if not isinstance(json_out, dict): # A string was most likely loaded, not what we want. return stdout, stderr, None return stdout, stderr, json_out[tgt] return stdout, stderr, json_out class SaltCall(SaltCliScriptBase): ''' Class which runs salt-call commands ''' def get_script_args(self): return ['--retcode-passthrough'] class SaltKey(SaltCliScriptBase): ''' Class which runs salt-key commands ''' class SaltRun(SaltCliScriptBase): ''' Class which runs salt-run commands ''' def process_output(self, tgt, stdout, stderr, cli_cmd): # pylint: disable=signature-differs if 'No minions matched the target. No command was sent, no jid was assigned.\n' in stdout: stdout = stdout.split('\n', 1)[1:][0] stdout, stderr, json_out = SaltCliScriptBase.process_output(self, tgt, stdout, stderr, cli_cmd) return stdout, stderr, json_out class SaltSSH(SaltCliScriptBase): ''' Class which runs salt-ssh commands ''' def get_script_args(self): return [ '-l', 'trace', '-w', '--rand-thin-dir', '--roster-file={}'.format(os.path.join(self.config_dir, 'roster')), '--ignore-host-keys', ] def get_minion_tgt(self, **kwargs): return 'localhost' def process_output(self, tgt, stdout, stderr, cli_cmd): # pylint: disable=signature-differs stdout, stderr, json_out = SaltCliScriptBase.process_output(self, tgt, stdout, stderr, cli_cmd) if json_out: return stdout, stderr, json_out[tgt] return stdout, stderr, json_out class SaltMinion(SaltDaemonScriptBase): ''' Class which runs the salt-minion daemon ''' def get_script_args(self): script_args = ['-l', 'quiet'] if sys.platform.startswith('win') is False: script_args.append('--disable-keepalive') return script_args def get_check_events(self): if sys.platform.startswith('win'): return super(SaltMinion, self).get_check_events() return set(['salt/{}/{}/start'.format(self.config['__role'], self.config['id'])]) def get_check_ports(self): if sys.platform.startswith('win'): return set([self.config['tcp_pub_port'], self.config['tcp_pull_port']]) return super(SaltMinion, self).get_check_ports() class SaltProxy(SaltDaemonScriptBase): ''' Class which runs the salt-proxy daemon ''' def get_script_args(self): script_args = ['-l', 'quiet'] script_args.extend(['--proxyid', self.config['id']]) if sys.platform.startswith('win') is False: script_args.append('--disable-keepalive') return script_args def get_check_events(self): if sys.platform.startswith('win'): return super(SaltProxy, self).get_check_events() return set(['salt/{}/{}/start'.format(self.config['__role'], self.config['id'])]) def get_check_ports(self): if sys.platform.startswith('win'): return set([self.config['tcp_pub_port'], self.config['tcp_pull_port']]) return super(SaltProxy, self).get_check_ports() class SaltMaster(SaltDaemonScriptBase): ''' Class which runs the salt-master daemon ''' def get_script_args(self): return ['-l', 'quiet'] def get_check_events(self): if sys.platform.startswith('win'): return super(SaltMaster, self).get_check_events() return set(['salt/{}/{}/start'.format(self.config['__role'], self.config['id'])]) def get_check_ports(self): if sys.platform.startswith('win'): return set([self.config['ret_port'], self.config['publish_port']]) return super(SaltMaster, self).get_check_ports() class SaltSyndic(SaltDaemonScriptBase): ''' Class which runs the salt-syndic daemon ''' def get_script_args(self): return ['-l', 'quiet'] class SSHD(SaltDaemonScriptBase): ''' Class which runs an sshd daemon ''' def get_script_path(self, script_name): ''' Returns the path to the script to run ''' import pytestsalt.utils.compat as compat sshd = compat.which(self.cli_script_name) if not sshd: pytest.skip('"sshd" not found') return sshd def get_base_script_args(self): return ['-D', '-f', os.path.join(self.config_dir, 'sshd_config')] def get_check_ports(self): return [self.config['port']] @pytest.hookimpl(tryfirst=True) def pytest_runtest_setup(item): ''' Fixtures injection based on markers ''' for fixture in ('salt_master', 'salt_minion', 'salt_call', 'salt', 'salt_key', 'salt_run'): if fixture in item.fixturenames: after_start_fixture = '{}_after_start'.format(fixture) if after_start_fixture not in item.fixturenames: item.fixturenames.append(after_start_fixture) pytest-salt-2019.6.13/pytestsalt/_version.py0000644000175000017500000000103413500170424021532 0ustar vampasvampas00000000000000 # This file was generated by 'versioneer.py' (0.18) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. from __future__ import absolute_import import json version_json = ''' { "date": "2019-06-12T13:32:25+0100", "dirty": false, "error": null, "full-revisionid": "5d8883b10459d2ec7fe65566a1d773b936bec649", "version": "2019.6.13" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) pytest-salt-2019.6.13/MANIFEST.in0000644000175000017500000000006513402450013016655 0ustar vampasvampas00000000000000include versioneer.py include pytestsalt/_version.py pytest-salt-2019.6.13/.testing.pylintrc0000644000175000017500000003227713401741236020463 0ustar vampasvampas00000000000000[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Pickle collected data for later comparisons. persistent=no # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins=saltpylint.pep8, saltpylint.pep263, saltpylint.strings, saltpylint.fileperms, saltpylint.smartup, # Use multiple processes to speed up Pylint. jobs=1 # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code extension-pkg-whitelist= # Fileperms Lint Plugin Settings fileperms-default=0o644 fileperms-ignore-paths=setup.py [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED confidence= # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" #disable= disable=R, I0011, I0012, I0013, E1101, E1103, C0102, C0103, C0111, C0203, C0204, C0301, C0302, C0330, W0110, W0122, W0142, W0201, W0212, W0404, W0511, W0603, W0612, W0613, W0621, W0622, W0631, W0704, W1202, W1307, F0220, F0401, E8501, E8116, E8121, E8122, E8123, E8124, E8125, E8126, E8127, E8128, E8129, E8131, E8265, E8266, E8402, E8731, locally-disabled, repr-flag-used-in-string, un-indexed-curly-braces-error, un-indexed-curly-braces-warning # Disabled: # R* [refactoring suggestions & reports] # I0011 (locally-disabling) # I0012 (locally-enabling) # I0013 (file-ignored) # E1101 (no-member) [pylint isn't smart enough] # E1103 (maybe-no-member) # C0102 (blacklisted-name) [because it activates C0103 too] # C0103 (invalid-name) # C0111 (missing-docstring) # C0203 (bad-mcs-method-argument) # C0204 (bad-mcs-classmethod-argument) # C0301 (line-too-long) # C0302 (too-many-lines) # C0330 (bad-continuation) # W0110 (deprecated-lambda) # W0122 (exec-statement) # W0142 (star-args) # W0201 (attribute-defined-outside-init) [done in several places in the codebase] # W0212 (protected-access) # W0404 (reimported) [done intentionally for legit reasons] # W0511 (fixme) [several outstanding instances currently in the codebase] # W0603 (global-statement) # W0612 (unused-variable) [unused return values] # W0613 (unused-argument) # W0621 (redefined-outer-name) # W0622 (redefined-builtin) [many parameter names shadow builtins] # W0631 (undefined-loop-variable) [~3 instances, seem to be okay] # W0704 (pointless-except) [misnomer; "ignores the exception" rather than "pointless"] # F0220 (unresolved-interface) # F0401 (import-error) # W1202 (logging-format-interpolation) Use % formatting in logging functions but pass the % parameters as arguments # W1307 (invalid-format-index) Using invalid lookup key '%s' in format specifier "0['%s']" # # E8116 PEP8 E116: unexpected indentation (comment) # E812* All PEP8 E12* # E8265 PEP8 E265 - block comment should start with "# " # E8266 PEP8 E266 - too many leading '#' for block comment # E8501 PEP8 line too long # E8402 module level import not at top of file # E8731 do not assign a lambda expression, use a def # # E1322(repr-flag-used-in-string) [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=no # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details #msg-template= msg-template='{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}' [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format logging-modules=logging [SPELLING] # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the name of dummy variables (i.e. expectedly # not used). dummy-variables-rgx=_$|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins=__opts__,__virtual__,__salt_system_encoding__ # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_,_cb [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO [BASIC] # List of builtins function names that should not be used, separated by a comma bad-functions=map,filter,input # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_,log,pytest_plugins # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Include a hint for the correct naming format with invalid-name include-naming-hint=no # Regular expression matching correct function names function-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for function names function-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct variable names variable-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for variable names variable-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct constant names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Naming hint for constant names const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression matching correct attribute names attr-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for attribute names attr-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct argument names argument-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for argument names argument-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression matching correct class attribute names class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,60}|(__.*__))$ # Naming hint for class attribute names class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,60}|(__.*__))$ # Regular expression matching correct inline iteration names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Naming hint for inline iteration names inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ # Regular expression matching correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Naming hint for class names class-name-hint=[A-Z_][a-zA-Z0-9]+$ # Regular expression matching correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Naming hint for module names module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression matching correct method names method-rgx=[a-z_][a-z0-9_]{2,60}$ # Naming hint for method names method-name-hint=[a-z_][a-z0-9_]{2,60}$ # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=__.*__ # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 [FORMAT] # Maximum number of characters on a single line. max-line-length=120 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no # List of optional constructs for which whitespace checking is disabled no-space-check=trailing-comma,dict-separator # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format=LF [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis ignored-modules= # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes= # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members= [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=regsub,TERMIOS,Bastion,rexec # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branches=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict,_fields,_replace,_source,_make [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception pytest-salt-2019.6.13/LICENSE0000644000175000017500000002612513401741236016142 0ustar vampasvampas00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015-2018 SaltStack Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pytest-salt-2019.6.13/PKG-INFO0000644000175000017500000000227613500170424016226 0ustar vampasvampas00000000000000Metadata-Version: 1.2 Name: pytest-salt Version: 2019.6.13 Summary: Pytest Salt Plugin Home-page: https://github.com/saltstack/pytest-salt Author: Pedro Algarvio Author-email: pedro@algarvio.me Maintainer: Pedro Algarvio Maintainer-email: pedro@algarvio.me License: Apache Software License 2.0 Description: PyTest Salt Plugin ================== This plugin will allow the Salt Daemons to be used in tests. This plugin is currently being used in Salt's test suite for the develop branch, however, this is still considered beta software. Please do submit bug reports for any issues you find. Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Testing Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: Apache Software License pytest-salt-2019.6.13/.gitignore0000644000175000017500000000142512667420712017127 0ustar vampasvampas00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # Ignore pyenv python version file .python-version # Ignore local vimrc file .lvimrc pytest-salt-2019.6.13/versioneer.py0000644000175000017500000022074513402450452017672 0ustar vampasvampas00000000000000 # Version: 0.18 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy * [![Latest Version][pypi-image]][pypi-url] * [![Build Status][travis-image]][travis-url] This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere to your $PATH * add a `[versioneer]` section to your setup.cfg (see below) * run `versioneer install` in your source tree, commit the results ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/warner/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/warner/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/warner/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ### Unicode version strings While Versioneer works (and is continually tested) with both Python 2 and Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. Newer releases probably generate unicode version strings on py2. It's not clear that this is wrong, but it may be surprising for applications when then write these strings to a network connection or include them in bytes-oriented APIs like cryptographic checksums. [Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates this question. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg [pypi-url]: https://pypi.python.org/pypi/versioneer/ [travis-image]: https://img.shields.io/travis/warner/python-versioneer/master.svg [travis-url]: https://travis-ci.org/warner/python-versioneer """ from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise EnvironmentError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode LONG_VERSION_PY['git'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date, "branch": None} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None, "branch": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s*" %% tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # abbrev-ref available with git >= 1.7 branch_name_out, rc = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) branch_name = branch_name_out.strip() if branch_name == 'HEAD': # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches_out, rc = run_command(GITS, ["branch", "--contains"], cwd=root) branches = branches_out.split('\n') # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches if branch and branch[4:5] != '('] if 'master' in branches: branch_name = 'master' elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces['branch'] = branch_name # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_pep440_branch_based(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.BRANCH_gHEX[.dirty] """ replacements = ([' ', '.'], ['(', ''], [')', ''], ['\\', '.'], ['/', '.']) branch_name = pieces.get('branch') or '' if branch_name: for old, new in replacements: branch_name = branch_name.replace(old, new) else: branch_name = 'unknown_branch' if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += '.dev0' + plus_or_dot(pieces) rendered += "%%d.%%s.g%%s" %% ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.%%s.g%%s" %% ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "pep440-branch-based": rendered = render_pep440_branch_based(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date, "branch": None} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None, "branch": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # abbrev-ref available with git >= 1.7 branch_name_out, rc = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) branch_name = branch_name_out.strip() if branch_name == 'HEAD': # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches_out, rc = run_command(GITS, ["branch", "--contains"], cwd=root) branches = branches_out.split('\n') # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches if branch and branch[4:5] != '('] if 'master' in branches: branch_name = 'master' elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces['branch'] = branch_name # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.18) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. from __future__ import absolute_import import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_pep440_branch_based(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.BRANCH_gHEX[.dirty] """ replacements = ([' ', '.'], ['(', ''], [')', ''], ['\\', '.'], ['/', '.']) branch_name = pieces.get('branch') or '' if branch_name: for old, new in replacements: branch_name = branch_name.replace(old, new) else: branch_name = 'unknown_branch' if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += '.dev0' + plus_or_dot(pieces) rendered += "%d.%s.g%s" % ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.%s.g%s" % ( pieces["distance"], branch_name, pieces['short'] ) if pieces["dirty"]: rendered += ".dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "pep440-branch-based": rendered = render_pep440_branch_based(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(cmdclass=None): """Get the custom setuptools/distutils subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument. """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} if cmdclass is None else cmdclass.copy() # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if 'build_py' in cmds: _build_py = cmds['build_py'] elif "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if 'sdist' in cmds: _sdist = cmds['sdist'] elif "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ INIT_PY_SNIPPET_RE = re.compile(INIT_PY_SNIPPET.replace( '(', r'\(').replace( ')', r'\)').replace( '[', r'\[').replace( ']', r'\]').replace( ' ._version', r' ([\w\._]+)?._version'), re.MULTILINE) def do_setup(): """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET_RE.search(old) is None: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass(" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)