pytest-salt-2018.1.13/0000755000175000017500000000000013226405071015120 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/PKG-INFO0000644000175000017500000000226113226405071016216 0ustar vampasvampas00000000000000Metadata-Version: 1.1 Name: pytest-salt Version: 2018.1.13 Summary: Pytest Salt Plugin Home-page: https://github.com/saltstack/pytest-salt Author: Pedro Algarvio Author-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.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: Apache Software License pytest-salt-2018.1.13/README.rst0000644000175000017500000000043513060555555016622 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-2018.1.13/pytest_salt.egg-info/0000755000175000017500000000000013226405071021165 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/pytest_salt.egg-info/dependency_links.txt0000644000175000017500000000007213226405071025243 0ustar vampasvampas00000000000000git+https://github.com/saltstack/salt.git@2016.3#egg=Salt pytest-salt-2018.1.13/pytest_salt.egg-info/PKG-INFO0000644000175000017500000000226113226405071022263 0ustar vampasvampas00000000000000Metadata-Version: 1.1 Name: pytest-salt Version: 2018.1.13 Summary: Pytest Salt Plugin Home-page: https://github.com/saltstack/pytest-salt Author: Pedro Algarvio Author-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.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: Apache Software License pytest-salt-2018.1.13/pytest_salt.egg-info/SOURCES.txt0000644000175000017500000000135713226405071023057 0ustar vampasvampas00000000000000README.rst setup.cfg setup.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/parser.py pytestsalt/utils.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/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/ipc.pypytest-salt-2018.1.13/pytest_salt.egg-info/entry_points.txt0000644000175000017500000000054013226405071024462 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.loader] engines_dirs = pytestsalt.salt.loader:engines_dirs log_handlers_dirs = pytestsalt.salt.loader:log_handlers_dirs pytest-salt-2018.1.13/pytest_salt.egg-info/top_level.txt0000644000175000017500000000001313226405071023711 0ustar vampasvampas00000000000000pytestsalt pytest-salt-2018.1.13/pytest_salt.egg-info/requires.txt0000644000175000017500000000011013226405071023555 0ustar vampasvampas00000000000000pytest >= 2.8.1 pytest-tempdir pytest-helpers-namespace psutil >= 4.2.0 pytest-salt-2018.1.13/setup.py0000644000175000017500000000604412755303074016644 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 # 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() # Version info -- read without importing _LOCALS = {} with codecs.open(os.path.join(SETUP_DIRNAME, 'pytestsalt', 'version.py'), encoding='utf-8') as rfh: contents = rfh.read() try: exec(contents, None, _LOCALS) # pylint: disable=exec-used except SyntaxError: # SyntaxError: encoding declaration in Unicode string exec(contents.encode('utf-8'), None, _LOCALS) # pylint: disable=exec-used VERSION = _LOCALS['__version__'] LONG_DESCRIPTION = read('README.rst') setup( name='pytest-salt', version=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=LONG_DESCRIPTION, packages=find_packages(), install_requires=[ 'pytest >= 2.8.1', #'pytest-catchlog', '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.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', '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.loader': [ 'engines_dirs = pytestsalt.salt.loader:engines_dirs', 'log_handlers_dirs = pytestsalt.salt.loader:log_handlers_dirs' ] }, ) pytest-salt-2018.1.13/pytestsalt/0000755000175000017500000000000013226405071017334 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/pytestsalt/fixtures/0000755000175000017500000000000013226405071021205 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/pytestsalt/fixtures/dirs.py0000644000175000017500000004410513122004047022515 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. pytestsalt.fixtures.dirs ~~~~~~~~~~~~~~~~~~~~~~~~ pytest salt directories related fixtures ''' # pylint: disable=redefined-outer-name # Import Python libs from __future__ import absolute_import import logging # Import 3rd-party libs import pytest 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 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-salt-2018.1.13/pytestsalt/fixtures/ports.py0000644000175000017500000002023713122002322022715 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. 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_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 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 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 salt_log_port(): ''' Returns an unused localhost port for the pytest logging manager ''' return get_unused_localhost_port() pytest-salt-2018.1.13/pytestsalt/fixtures/daemons.py0000644000175000017500000014364513210552165023222 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. 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 ''' 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('utf-8') return version @pytest.yield_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.yield_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, start_timeout=30) @pytest.yield_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.yield_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, start_timeout=30) @pytest.yield_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.yield_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, start_timeout=30) @pytest.yield_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.yield_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, start_timeout=30) @pytest.yield_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.yield_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, start_timeout=30) @pytest.yield_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.yield_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, start_timeout=30) @pytest.yield_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.yield_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, 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, start_timeout=30) @pytest.yield_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.yield_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_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, start_timeout=30) @pytest.yield_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.yield_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, _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, start_timeout=30) @pytest.yield_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.yield_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, _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, start_timeout=30) @pytest.yield_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.yield_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, start_timeout=30) @pytest.yield_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.yield_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_minion_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, start_timeout=30) @pytest.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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.yield_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, 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({0}) has failed to confirm ' 'running status after {1} 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({0}) has failed to start after {1} 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.yield_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.yield_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.yield_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, 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({0}) has failed to confirm ' 'running status after {1} 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({0}) has failed to start after {1} 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): 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): 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={0}'.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): 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/{0}/{1}/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/{0}/{1}/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/{0}/{1}/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_check_ports(self): return set([self.config['pytest_port']]) 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 salt.utils sshd = salt.utils.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 = '{0}_after_start'.format(fixture) if after_start_fixture not in item.fixturenames: item.fixturenames.append(after_start_fixture) pytest-salt-2018.1.13/pytestsalt/fixtures/__init__.py0000644000175000017500000000046513122002322023306 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. pytestsalt.fixtures ~~~~~~~~~~~~~~~~~~~ pytest salt fixtures ''' pytest-salt-2018.1.13/pytestsalt/fixtures/config.py0000644000175000017500000015463613206022351023035 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. 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 logging import subprocess # Import 3rd-party libs import pytest # Import pytest salt libs import pytestsalt.salt.engines import pytestsalt.salt.log_handlers 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_SESSION_MASTER_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' 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 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 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='function') 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 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 + '-{0}'.format(salt_master_of_masters_id_counter()) @pytest.fixture def master_id(salt_master_id_counter): ''' Returns the master id ''' return DEFAULT_MASTER_ID + '-{0}'.format(salt_master_id_counter()) @pytest.fixture def minion_id(salt_minion_id_counter): ''' Returns the minion id ''' return DEFAULT_MINION_ID + '-{0}'.format(salt_minion_id_counter()) @pytest.fixture def secondary_minion_id(salt_minion_id_counter): ''' Returns the secondary minion id ''' return DEFAULT_MINION_ID + '-{0}'.format(salt_minion_id_counter()) @pytest.fixture def syndic_id(salt_syndic_id_counter): ''' Returns the syndic id ''' return DEFAULT_SESSION_SYNDIC_ID + '-{0}'.format(salt_syndic_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_MOM_ID + '-{0}'.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 + '-{0}'.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 + '-{0}'.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_MINION_ID + '-{0}'.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 + '-{0}'.format(salt_syndic_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_master_config_overrides(): ''' This fixture should be implemented to overwrite default salt syndic master configuration options. It will be applied over the loaded default options ''' @pytest.fixture def syndic_minion_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_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_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_master_config_overrides(): ''' This fixture should be implemented to overwrite default salt syndic master configuration options. It will be applied over the loaded default options ''' @pytest.fixture(scope='session') def session_syndic_minion_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 master_log_prefix(master_id): return 'salt-master/{0}'.format(master_id) @pytest.fixture(scope='session') def session_master_log_prefix(session_master_id): return 'salt-master/{0}'.format(session_master_id) @pytest.fixture def master_of_masters_log_prefix(master_of_masters_id): return 'salt-master/{0}'.format(master_of_masters_id) @pytest.fixture(scope='session') def session_master_of_masters_log_prefix(session_master_of_masters_id): return 'salt-master/{0}'.format(session_master_of_masters_id) @pytest.fixture def minion_log_prefix(minion_id): return 'salt-minion/{0}'.format(minion_id) @pytest.fixture(scope='session') def session_minion_log_prefix(session_minion_id): return 'salt-minion/{0}'.format(session_minion_id) @pytest.fixture def proxy_log_prefix(minion_id): return 'salt-proxy/{0}'.format(minion_id) @pytest.fixture(scope='session') def session_proxy_log_prefix(session_minion_id): return 'salt-proxy/{0}'.format(session_minion_id) @pytest.fixture def secondary_minion_log_prefix(secondary_minion_id): return 'salt-minion/{0}'.format(secondary_minion_id) @pytest.fixture(scope='session') def session_secondary_minion_log_prefix(session_secondary_minion_id): return 'salt-minion/{0}'.format(session_secondary_minion_id) @pytest.fixture def syndic_log_prefix(syndic_id): return 'salt-syndic/{0}'.format(syndic_id) @pytest.fixture(scope='session') def session_syndic_log_prefix(session_syndic_id): return 'salt-syndic/{0}'.format(session_syndic_id) @pytest.fixture def salt_log_prefix(minion_id): return 'salt/{0}'.format(minion_id) @pytest.fixture(scope='session') def session_salt_log_prefix(session_minion_id): return 'salt/{0}'.format(session_minion_id) @pytest.fixture def salt_call_log_prefix(master_id): return 'salt-call/{0}'.format(master_id) @pytest.fixture(scope='session') def session_salt_call_log_prefix(session_master_id): return 'salt-call/{0}'.format(session_master_id) @pytest.fixture def salt_key_log_prefix(master_id): return 'salt-key/{0}'.format(master_id) @pytest.fixture(scope='session') def session_salt_key_log_prefix(session_master_id): return 'salt-key/{0}'.format(session_master_id) @pytest.fixture def salt_run_log_prefix(master_id): return 'salt-run/{0}'.format(master_id) @pytest.fixture(scope='session') def session_salt_run_log_prefix(session_master_id): return 'salt-run/{0}'.format(session_master_id) def apply_master_config(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, salt_log_port, 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 salt.config import salt.utils import salt.utils.dictupdate as dictupdate import salt.utils.verify as salt_verify import salt.serializers.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' } 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, os.path.dirname(pytestsalt.salt.engines.__file__)) default_options['pytest_port'] = engine_port if 'log_handlers_dirs' not in default_options: default_options['log_handlers_dirs'] = [] default_options['log_handlers_dirs'].insert(0, os.path.dirname(pytestsalt.salt.log_handlers.__file__)) default_options['pytest_log_port'] = salt_log_port default_options['pytest_log_prefix'] = '[{0}] '.format(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 configuration file to %s', config_file) # Write down the computed configuration into the config file with salt.utils.fopen(config_file, 'w') as wfh: wfh.write(yamlserialize.serialize(default_options)) # 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( 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_config(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, prod_env_state_tree_root_dir, base_env_pillar_tree_root_dir, prod_env_pillar_tree_root_dir, running_username, salt_log_port, 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(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, salt_log_port, 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_config(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, session_prod_env_state_tree_root_dir, session_base_env_pillar_tree_root_dir, session_prod_env_pillar_tree_root_dir, running_username, salt_log_port, 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_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, salt_log_port, 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 def master_of_masters_config(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, 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, salt_log_port, 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_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, salt_log_port, 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_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_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, salt_log_port, 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_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, salt_log_port, 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(root_dir, config_file, return_port, engine_port, config_overrides, minion_id, running_username, salt_log_port, minion_log_prefix, tcp_pub_port, tcp_pull_port): ''' This fixture will return the salt minion configuration options after being overridden with any options passed from ``config_overrides`` ''' import salt.config import salt.utils import salt.utils.dictupdate as dictupdate import salt.utils.verify as salt_verify import salt.serializers.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' } if config_overrides: # Merge in the default options with the minion_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, os.path.dirname(pytestsalt.salt.engines.__file__)) #default_options['pytest_port'] = engine_port if 'log_handlers_dirs' not in default_options: default_options['log_handlers_dirs'] = [] default_options['log_handlers_dirs'].insert(0, os.path.dirname(pytestsalt.salt.log_handlers.__file__)) default_options['pytest_log_port'] = salt_log_port default_options['pytest_log_prefix'] = '[{0}] '.format(minion_log_prefix) log.info('Writing configuration file to %s', config_file) # Write down the computed configuration into the config file with salt.utils.fopen(config_file, 'w') as wfh: wfh.write(yamlserialize.serialize(default_options)) # 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( 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_config(root_dir, minion_config_file, master_return_port, minion_engine_port, minion_config_overrides, minion_id, running_username, salt_log_port, 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(root_dir, minion_config_file, master_return_port, minion_engine_port, minion_config_overrides, minion_id, running_username, salt_log_port, minion_log_prefix, minion_tcp_pub_port, minion_tcp_pull_port) @pytest.fixture(scope='session') def session_minion_config(session_root_dir, session_minion_config_file, session_master_return_port, session_minion_engine_port, session_minion_config_overrides, session_minion_id, running_username, salt_log_port, 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_root_dir, session_minion_config_file, session_master_return_port, session_minion_engine_port, session_minion_config_overrides, session_minion_id, running_username, salt_log_port, session_minion_log_prefix, session_minion_tcp_pub_port, session_minion_tcp_pull_port) @pytest.fixture def secondary_minion_config(secondary_root_dir, secondary_minion_config_file, master_return_port, secondary_minion_engine_port, secondary_minion_config_overrides, secondary_minion_id, running_username, salt_log_port, 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_root_dir, secondary_minion_config_file, master_return_port, secondary_minion_engine_port, secondary_minion_config_overrides, secondary_minion_id, running_username, salt_log_port, secondary_minion_log_prefix, secondary_minion_tcp_pub_port, secondary_minion_tcp_pull_port) @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_engine_port, session_secondary_minion_config_overrides, session_secondary_minion_id, running_username, salt_log_port, 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_root_dir, session_secondary_minion_config_file, session_master_return_port, session_secondary_minion_engine_port, session_secondary_minion_config_overrides, session_secondary_minion_id, running_username, salt_log_port, session_secondary_minion_log_prefix, session_secondary_minion_tcp_pub_port, session_secondary_minion_tcp_pull_port) def apply_syndic_config(master_config, minion_config, syndic_conf_dir, engine_port, master_config_overrides, minion_config_overrides, running_username, salt_log_port, syndic_log_prefix, syndic_id): ''' This fixture will return the salt syndic configuration options after being overridden with any options passed from ``config_overrides`` ''' import salt.config import salt.utils import salt.utils.dictupdate as dictupdate import salt.utils.verify as salt_verify import salt.serializers.yaml as yamlserialize syndic_master_config_file = syndic_conf_dir.join('master').realpath().strpath syndic_minion_config_file = syndic_conf_dir.join('minion').realpath().strpath default_master_options = copy.deepcopy(master_config) default_minion_options = copy.deepcopy(minion_config) 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', 'pytest_port': engine_port, 'pytest_log_prefix': '[{0}] '.format(syndic_log_prefix) } master_config = copy.deepcopy(default_master_options) master_config.update(master_overrides) if master_config_overrides: # Merge in the default options with the minion_config_overrides dictupdate.update(master_config, master_config_overrides, merge_lists=True) # Write down the master computed configuration into the config file with salt.utils.fopen(syndic_master_config_file, 'w') as wfh: wfh.write(yamlserialize.serialize(master_config)) default_minion_options = copy.deepcopy(minion_config) minion_overrides = { 'id': syndic_id, } minion_config = copy.deepcopy(default_minion_options) minion_config.update(minion_overrides) if minion_config_overrides: # Merge in the default options with the minion_config_overrides dictupdate.update(minion_config, minion_config_overrides, merge_lists=True) # Write down the minion computed configuration into the config file with salt.utils.fopen(syndic_minion_config_file, 'w') as wfh: wfh.write(yamlserialize.serialize(minion_config)) options = salt.config.syndic_config(syndic_master_config_file, syndic_minion_config_file) return options @pytest.fixture def syndic_config(master_config, minion_config, syndic_conf_dir, syndic_engine_port, syndic_master_config_overrides, syndic_minion_config_overrides, running_username, salt_log_port, syndic_log_prefix, syndic_id): ''' This fixture will return the salt syndic configuration options after being overridden with any options passed from ``syndic_master_config_overrides`` and ``syndic_minion_config_overrides`` ''' return apply_syndic_config(master_config, minion_config, syndic_conf_dir, syndic_engine_port, syndic_master_config_overrides, syndic_minion_config_overrides, running_username, salt_log_port, syndic_log_prefix, syndic_id) @pytest.fixture(scope='session') def session_syndic_config(session_master_config, session_minion_config, session_syndic_conf_dir, session_syndic_engine_port, session_syndic_master_config_overrides, session_syndic_minion_config_overrides, running_username, salt_log_port, session_syndic_log_prefix, session_syndic_id): ''' This fixture will return the salt syndic configuration options after being overridden with any options passed from ``syndic_master_config_overrides`` and ``syndic_minion_config_overrides`` ''' return apply_syndic_config(session_master_config, session_minion_config, session_syndic_conf_dir, session_syndic_engine_port, session_syndic_master_config_overrides, session_syndic_minion_config_overrides, running_username, salt_log_port, session_syndic_log_prefix, session_syndic_id) @pytest.fixture def salt_ssh_log_prefix(sshd_port): return 'salt-ssh/{0}'.format(sshd_port) @pytest.fixture(scope='session') def session_salt_ssh_log_prefix(session_sshd_port): return 'salt-ssh/{0}'.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 {0}'.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 salt.utils sshd = salt.utils.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 {0}.pub'.format(ssh_client_key)) sshd_config.append('HostKey {0}'.format(server_dsa_key_file)) sshd_config.append('HostKey {0}'.format(server_ecdsa_key_file)) sshd_config.append('HostKey {0}'.format(server_ed25519_key_file)) with salt.utils.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/{0}'.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/{0}'.format(session_sshd_port) def _generate_ssh_key(key_path, key_type='ecdsa', key_size=521): ''' Generate an SSH key ''' import salt.utils log.debug('Generating ssh key(type: %s; size: %d; path: %s;)', key_type, key_size, key_path) keygen = salt.utils.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 {0}({1}:{2}): {3}'.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 salt.utils import salt.serializers.yaml as yamlserialize if config_overrides: config.update(config_overrides) with salt.utils.fopen(config_file, 'w') as wfh: wfh.write(yamlserialize.serialize(config)) 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-2018.1.13/pytestsalt/fixtures/log.py0000644000175000017500000000464413122002322022333 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: Copyright 2016 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. 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 import threading import logging try: import SocketServer as socketserver except ImportError: import socketserver # Import pytest libs import pytest # Import 3rd-party libs import msgpack log = logging.getLogger(__name__) @pytest.yield_fixture(scope='session') def log_server(salt_log_port): ''' Returns a log server fixture. This is an autouse fixture so no need to depend on it ''' server = ThreadedSocketServer(('localhost', salt_log_port), SocketServerRequestHandler) server_process = threading.Thread(target=server.serve_forever) server_process.daemon = True server_process.start() yield server server.server_close() server.shutdown() class ThreadingMixIn(socketserver.ThreadingMixIn): daemon_threads = True class ThreadedSocketServer(ThreadingMixIn, socketserver.TCPServer): def server_activate(self): self.shutting_down = threading.Event() socketserver.TCPServer.server_activate(self) #super(ThreadedSocketServer, self).server_activate() def server_close(self): self.shutting_down.set() socketserver.TCPServer.server_close(self) #super(ThreadedSocketServer, self).server_close() class SocketServerRequestHandler(socketserver.StreamRequestHandler): def handle(self): unpacker = msgpack.Unpacker(encoding='utf-8') while not self.server.shutting_down.is_set(): try: wire_bytes = self.request.recv(1024) if not wire_bytes: break 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) pytest-salt-2018.1.13/pytestsalt/salt/0000755000175000017500000000000013226405071020277 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/pytestsalt/salt/loader.py0000644000175000017500000000106413122002322022103 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: Copyright 2016 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. 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-2018.1.13/pytestsalt/salt/__init__.py0000644000175000017500000000003012673636375022423 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- pytest-salt-2018.1.13/pytestsalt/salt/engines/0000755000175000017500000000000013226405071021727 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/pytestsalt/salt/engines/pytest_engine.py0000644000175000017500000001013513226404564025164 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. 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 sys import errno import socket import logging # Import salt libs import salt.utils.event # Import 3rd-party libs from tornado import gen from tornado import ioloop from tornado import netutil log = logging.getLogger(__name__) __virtualname__ = 'pytest' def __virtual__(): return 'pytest_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.sock = None 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): if self.opts['__role'] == 'minion': yield self.listen_to_minion_connected_event() else: self.io_loop.spawn_callback(self.fire_master_started_event) port = int(self.opts['pytest_port']) log.info('Starting Pytest Engine(role=%s) on port %s', self.opts['__role'], port) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.setblocking(0) # bind the socket to localhost on the config provided port self.sock.bind(('localhost', port)) # become a server socket self.sock.listen(5) netutil.add_accept_handler( self.sock, self.handle_connection, io_loop=self.io_loop, ) def handle_connection(self, connection, address): log.warning('Accepted connection from %s. Role: %s', address, self.opts['__role']) # 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 listen_to_minion_connected_event(self): log.info('Listening for minion connected event...') minion_start_event_match = 'salt/minion/{0}/start'.format(self.opts['id']) event_bus = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=True) event_bus.subscribe(minion_start_event_match) while True: event = event_bus.get_event(full=True, no_block=True) if event is not None and event['tag'] == minion_start_event_match: log.info('Got minion connected event: %s', event) break yield gen.sleep(0.25) @gen.coroutine def fire_master_started_event(self): log.info('Firing salt-master started event...') event_bus = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False) master_start_event_tag = 'salt/master/{0}/start'.format(self.opts['id']) load = {'id': self.opts['id'], 'tag': master_start_event_tag, 'data': {}} # One minute should be more than enough to fire these events every second in order # for pytest-salt to pickup that the master is running timeout = 60 while True: timeout -= 1 event_bus.fire_event(load, master_start_event_tag, timeout=500) if timeout <= 0: break yield gen.sleep(1) pytest-salt-2018.1.13/pytestsalt/salt/engines/__init__.py0000644000175000017500000000003012673636375024053 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- pytest-salt-2018.1.13/pytestsalt/salt/log_handlers/0000755000175000017500000000000013226405071022740 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/pytestsalt/salt/log_handlers/__init__.py0000644000175000017500000000003012675614026025053 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- pytest-salt-2018.1.13/pytestsalt/salt/log_handlers/pytest_log_handler.py0000644000175000017500000000517113122002322027167 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: Copyright 2016 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. pytestsalt.salt.log_handlers.pytest_log_handler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Salt External Logging Handler ''' # Import python libs from __future__ import absolute_import 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 __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(): # 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.QueueHandler(queue) handler.setLevel(1) pytest_log_prefix = os.environ.get('PYTEST_LOG_PREFIX') or __opts__['pytest_log_prefix'] process_queue_thread = threading.Thread(target=process_queue, args=(__opts__['pytest_log_port'], pytest_log_prefix, queue)) process_queue_thread.daemon = True process_queue_thread.start() return handler def process_queue(port, prefix, queue): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', port)) 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'] = prefix + 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-2018.1.13/pytestsalt/version.py0000644000175000017500000000073313226404571021402 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. pytestsalt.version ~~~~~~~~~~~~~~~~~~ pytest salt plugin version information ''' # Import Python Libs from __future__ import absolute_import __version_info__ = (2018, 1, 13) __version__ = '{0}.{1}.{2}'.format(*__version_info__) pytest-salt-2018.1.13/pytestsalt/utils/0000755000175000017500000000000013226405071020474 5ustar vampasvampas00000000000000pytest-salt-2018.1.13/pytestsalt/utils/ipc.py0000644000175000017500000000550212707537074021637 0ustar vampasvampas00000000000000# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2016 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. pytestsalt.utils.ipc ~~~~~~~~~~~~~~~~~~~~ IPC Server/Client for communication between salt daemons and pytest-salt plugin ''' import logging import msgpack from tornado import gen from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado.tcpclient import TCPClient from tornado.tcpserver import TCPServer from tornado.netutil import add_accept_handler, bind_unix_socket log = logging.getLogger(__name__) class IPCServer: def __init__(self, socket_path, io_loop=None): self.socket_path = socket_path self._started = self._closing = False self.io_loop = io_loop or IOLoop.current() self._event_registry = {} def start(self): if self._started: return log.info('%s binding to: %s', self.__class__.__name__, self.socket_path) self._closing = False self.sock = bind_unix_socket(self.socket_path) add_accept_handler(self.sock, self.handle_connection, io_loop=self.io_loop) self._started = True def stop(self): if not self._started: return if self._closing: return log.info('%s stopping', self.__class__.__name__) self._closing = True if hasattr(self, 'sock'): self.sock.close() self._started = False def handle_connection(self, connection, address): log.info('%s handling connection to: %s', self.__class__.__name__, address) try: stream = IOStream(connection, io_loop=self.io_loop) self.io_loop.spawn_callback(self.handle_stream, stream) except Exception as exc: log.error('%s streaming error: %s', self.__class__.__name__, exc) log.exception(exc) @gen.coroutine def handle_stream(self, stream): unpacker = msgpack.Unpacker(encoding='utf-8') while not stream.closed(): try: wire_bytes = yield stream.read_bytes(4096, partial=True) unpacker.feed(wire_bytes) for action, events in unpacker: if action == 'subscribe': for event in events: self._event_registry.setdefault(event, set()).add(stream) elif action == 'unsubscribe': for event in events: if event in self._event_registry: if stream in self._event_registry[event]: self._event_registry[event].remove(stream) class Client(TCPClient): pass pytest-salt-2018.1.13/pytestsalt/__init__.py0000644000175000017500000000044113122004013021426 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. pytestsalt ~~~~~~~~~~ PyTest Salt Plugin ''' pytest-salt-2018.1.13/pytestsalt/utils.py0000644000175000017500000010135013226404571021052 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. 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('[{0}] - {1}'.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[::-1] # return a reversed list of the children def _terminate_process_list(process_list, kill=False, slow_stop=False): for process in process_list[:][::-1]: # Iterate over a reversed 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_child_processes(pid=None, children=None, kill=False, slow_stop=False): ''' Try to terminate/kill any started child processes of the provided pid ''' if pid: if not children: # Let's get the child processes of the started subprocess children = collect_child_processes(pid) else: # Let's collect children again since there might be new ones children.extend(collect_child_processes(pid)) if children: terminate_process_list(children, kill=slow_stop is False, slow_stop=slow_stop) 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=False, environ=None, cwd=None, **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 <= 3: # 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 >= 3: fail_method( 'The pytest {0}({1}) has failed to confirm running status ' 'after {2} 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 >= 3: 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 {0}({1}) has failed to start after {2} 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 = '{0}({1})'.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): 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 get_salt_run_event_listener(self): try: cli_script_name = self.request.getfixturevalue('cli_run_script_name') except AttributeError: cli_script_name = self.request.getfuncargvalue('cli_run_script_name') return SaltRunEventListener(self.request, self.config, self.config_dir, self.bin_dir_path, self.log_prefix, cli_script_name=cli_script_name) 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) process_output_thread = threading.Thread(target=self._process_output) process_output_thread.daemon = True self._running.set() process_output_thread.start() return True def _process_output(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 = self.get_salt_run_event_listener() 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: result = event_listener.run(check_events, timeout=timeout - 0.5) if result.exitcode == 0: for tag in result.json['matched']: check_events.remove(tag) 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'] = '[{0}] '.format(self.log_prefix) 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('{0}={1}'.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( '[{0}][{1}] Failed to run: args: {2!r}; kwargs: {3!r}; Error: {4}'.format( self.log_prefix, self.cli_display_name, args, kwargs, '[{0}][{1}] Timed out after {2} 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 ''' # Late import import salt.ext.six as six exitcode = 0 timeout_expire = time.time() + timeout environ = self.environ.copy() environ['PYTEST_LOG_PREFIX'] = '[{0}][EventListen] '.format(self.log_prefix) 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: 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 json_out = { 'matched': matched_events, 'unmatched': to_match_events } return ShellResult(exitcode, stdout, stderr, json_out) @pytest.mark.trylast def pytest_configure(config): pytest.helpers.utils.register(get_unused_localhost_port) pytest-salt-2018.1.13/pytestsalt/parser.py0000644000175000017500000000060313122002322021164 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. pytestsalt.parser ~~~~~~~~~~~~~~~~~ pytest salt plugin related parser options ''' # Import python libs from __future__ import absolute_import pytest-salt-2018.1.13/setup.cfg0000644000175000017500000000026613226405071016745 0ustar vampasvampas00000000000000[upload] sign = true identity = 84A298FF [aliases] release = clean sdist bdist_wheel upload [bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0