def setup_loader_modules(self): patcher = patch('salt.utils.which', Mock(return_value='/usr/bin/uwsgi')) patcher.start() self.addCleanup(patcher.stop) return {uwsgi: {}}
def test_show(self): """ Test that the pkg.show function properly parses apt-cache show output. This test uses an abridged output per package, for simplicity. """ show_mock_success = MagicMock( return_value={ "retcode": 0, "pid": 12345, "stderr": "", "stdout": textwrap.dedent("""\ Package: foo1.0 Architecture: amd64 Version: 1.0.5-3ubuntu4 Description: A silly package (1.0 release cycle) Provides: foo Suggests: foo-doc Package: foo1.0 Architecture: amd64 Version: 1.0.4-2ubuntu1 Description: A silly package (1.0 release cycle) Provides: foo Suggests: foo-doc Package: foo-doc Architecture: all Version: 1.0.5-3ubuntu4 Description: Silly documentation for a silly package (1.0 release cycle) Package: foo-doc Architecture: all Version: 1.0.4-2ubuntu1 Description: Silly documentation for a silly package (1.0 release cycle) """), }) show_mock_failure = MagicMock( return_value={ "retcode": 1, "pid": 12345, "stderr": textwrap.dedent("""\ N: Unable to locate package foo* N: Couldn't find any package by glob 'foo*' N: Couldn't find any package by regex 'foo*' E: No packages found """), "stdout": "", }) refresh_mock = Mock() expected = { "foo1.0": { "1.0.5-3ubuntu4": { "Architecture": "amd64", "Description": "A silly package (1.0 release cycle)", "Provides": "foo", "Suggests": "foo-doc", }, "1.0.4-2ubuntu1": { "Architecture": "amd64", "Description": "A silly package (1.0 release cycle)", "Provides": "foo", "Suggests": "foo-doc", }, }, "foo-doc": { "1.0.5-3ubuntu4": { "Architecture": "all", "Description": "Silly documentation for a silly package (1.0 release cycle)", }, "1.0.4-2ubuntu1": { "Architecture": "all", "Description": "Silly documentation for a silly package (1.0 release cycle)", }, }, } # Make a copy of the above dict and strip out some keys to produce the # expected filtered result. filtered = copy.deepcopy(expected) for k1 in filtered: for k2 in filtered[k1]: # Using list() because we will modify the dict during iteration for k3 in list(filtered[k1][k2]): if k3 not in ("Description", "Provides"): filtered[k1][k2].pop(k3) with patch.dict(aptpkg.__salt__, {"cmd.run_all": show_mock_success}), patch.object( aptpkg, "refresh_db", refresh_mock): # Test success (no refresh) self.assertEqual(aptpkg.show("foo*"), expected) refresh_mock.assert_not_called() refresh_mock.reset_mock() # Test success (with refresh) self.assertEqual(aptpkg.show("foo*", refresh=True), expected) self.assert_called_once(refresh_mock) refresh_mock.reset_mock() # Test filtered return self.assertEqual( aptpkg.show("foo*", filter="description,provides"), filtered) refresh_mock.assert_not_called() refresh_mock.reset_mock() with patch.dict(aptpkg.__salt__, {"cmd.run_all": show_mock_failure}), patch.object( aptpkg, "refresh_db", refresh_mock): # Test failure (no refresh) self.assertEqual(aptpkg.show("foo*"), {}) refresh_mock.assert_not_called() refresh_mock.reset_mock() # Test failure (with refresh) self.assertEqual(aptpkg.show("foo*", refresh=True), {}) self.assert_called_once(refresh_mock) refresh_mock.reset_mock()
def test_refresh_db_with_options(self): with patch('salt.utils.pkg.clear_rtag', Mock()): # With check_update=True we will do a cmd.run to run the clean_cmd, and # then a separate cmd.retcode to check for updates. # with fromrepo clean_cmd = Mock() update_cmd = MagicMock(return_value=0) with patch.dict(yumpkg.__salt__, { 'cmd.run': clean_cmd, 'cmd.retcode': update_cmd }): yumpkg.refresh_db(check_update=True, fromrepo='good', branch='foo') clean_cmd.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=*', '--enablerepo=good', '--branch=foo' ], python_shell=False) update_cmd.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'check-update', '--setopt=autocheck_running_kernel=false', '--disablerepo=*', '--enablerepo=good', '--branch=foo' ], output_loglevel='trace', ignore_retcode=True, python_shell=False) # without fromrepo clean_cmd = Mock() update_cmd = MagicMock(return_value=0) with patch.dict(yumpkg.__salt__, { 'cmd.run': clean_cmd, 'cmd.retcode': update_cmd }): yumpkg.refresh_db(check_update=True, enablerepo='good', disablerepo='bad', branch='foo') clean_cmd.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=bad', '--enablerepo=good', '--branch=foo' ], python_shell=False) update_cmd.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'check-update', '--setopt=autocheck_running_kernel=false', '--disablerepo=bad', '--enablerepo=good', '--branch=foo' ], output_loglevel='trace', ignore_retcode=True, python_shell=False) # With check_update=False we will just do a cmd.run for the clean_cmd # with fromrepo clean_cmd = Mock() with patch.dict(yumpkg.__salt__, {'cmd.run': clean_cmd}): yumpkg.refresh_db(check_update=False, fromrepo='good', branch='foo') clean_cmd.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=*', '--enablerepo=good', '--branch=foo' ], python_shell=False) # without fromrepo clean_cmd = Mock() with patch.dict(yumpkg.__salt__, {'cmd.run': clean_cmd}): yumpkg.refresh_db(check_update=False, enablerepo='good', disablerepo='bad', branch='foo') clean_cmd.assert_called_once_with([ 'yum', '--quiet', '--assumeyes', 'clean', 'expire-cache', '--disablerepo=bad', '--enablerepo=good', '--branch=foo' ], python_shell=False)
def test_chattr_version_returns_None_if_no_tune2fs_exists(self): patch_which = patch("hubblestack.utils.path.which", Mock(return_value=""),) with patch_which: actual = filemod._chattr_version() self.assertIsNone(actual)
from __future__ import absolute_import, print_function # Import Salt Testing libs from tests.support.unit import skipIf, TestCase from tests.support.mock import NO_MOCK, NO_MOCK_REASON, Mock, patch # Import salt libs from salt.exceptions import CommandExecutionError from salt.modules import uptime uptime.__grains__ = None # in order to stub it w/patch below uptime.__salt__ = None # in order to stub it w/patch below if NO_MOCK is False: SALT_STUB = { 'pillar.get': Mock(return_value='http://localhost:5000'), 'requests.put': Mock(), } else: SALT_STUB = {} class RequestMock(Mock): ''' Request Mock''' def get(self, *args, **kwargs): return RequestResponseMock() def put(self, *args, **kwargs): self.args = args self.kwargs = kwargs return RequestPutResponseMock()
def test_check_mine_cache_is_refreshed_on_container_change_event(self): ''' Every command that might modify docker containers state. Should trig an update on ``mine.send`` ''' with patch.object(docker_mod, '_get_exec_driver'): client_args_mock = MagicMock( return_value={ 'create_container': [ 'image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'ports', 'environment', 'volumes', 'network_disabled', 'name', 'entrypoint', 'working_dir', 'domainname', 'cpuset', 'host_config', 'mac_address', 'labels', 'volume_driver', 'stop_signal', 'networking_config', 'healthcheck', 'stop_timeout' ], 'host_config': [ 'binds', 'port_bindings', 'lxc_conf', 'publish_all_ports', 'links', 'privileged', 'dns', 'dns_search', 'volumes_from', 'network_mode', 'restart_policy', 'cap_add', 'cap_drop', 'devices', 'extra_hosts', 'read_only', 'pid_mode', 'ipc_mode', 'security_opt', 'ulimits', 'log_config', 'mem_limit', 'memswap_limit', 'mem_reservation', 'kernel_memory', 'mem_swappiness', 'cgroup_parent', 'group_add', 'cpu_quota', 'cpu_period', 'blkio_weight', 'blkio_weight_device', 'device_read_bps', 'device_write_bps', 'device_read_iops', 'device_write_iops', 'oom_kill_disable', 'shm_size', 'sysctls', 'tmpfs', 'oom_score_adj', 'dns_opt', 'cpu_shares', 'cpuset_cpus', 'userns_mode', 'pids_limit', 'isolation', 'auto_remove', 'storage_opt' ], 'networking_config': [ 'aliases', 'links', 'ipv4_address', 'ipv6_address', 'link_local_ips' ], }) for command_name, args in ( ('create', ()), ('rm_', ()), ('kill', ()), ('pause', ()), ('signal_', ('KILL', )), ('start_', ()), ('stop', ()), ('unpause', ()), ('_run', ('command', )), ('_script', ('command', )), ): mine_send = Mock() command = getattr(docker_mod, command_name) client = MagicMock() client.api_version = '1.12' with patch.dict( docker_mod.__salt__, { 'mine.send': mine_send, 'container_resource.run': MagicMock(), 'cp.cache_file': MagicMock(return_value=False) }): with patch.dict( docker_mod.__utils__, {'docker.get_client_args': client_args_mock}): with patch.object(docker_mod, '_get_client', client): command('container', *args) mine_send.assert_called_with('docker.ps', verbose=True, all=True, host=True)
def test_SaltInvocationError_should_be_raised_when_file_is_missing(self): patch_exists = patch("os.path.exists", Mock(return_value=False),) with patch_exists, self.assertRaises(HubbleInvocationError): filemod.lsattr("foo")
def call_procs(self): WMI = Mock() WMI.win32_process = Mock(return_value=self.__processes) with patch.object(wmi, 'WMI', Mock(return_value=WMI)): self.result = status.procs()
def test_present(): """ Test docker_volume.present """ volumes = [] default_driver = "dummy_default" def create_volume(name, driver=None, driver_opts=None): for v in volumes: assert v["Name"] != name if driver is None: driver = default_driver new = {"Name": name, "Driver": driver} volumes.append(new) return new def remove_volume(name): removed = [v for v in volumes if v["Name"] == name] assert 1 == len(removed) volumes.remove(removed[0]) return removed[0] docker_create_volume = Mock(side_effect=create_volume) __salt__ = { "docker.create_volume": docker_create_volume, "docker.volumes": Mock(return_value={"Volumes": volumes}), "docker.remove_volume": Mock(side_effect=remove_volume), } with patch.dict(docker_state.__dict__, {"__salt__": __salt__}): ret = docker_state.present("volume_foo") docker_create_volume.assert_called_with( "volume_foo", driver=None, driver_opts=None ) assert ret == { "name": "volume_foo", "comment": "", "changes": {"created": {"Driver": default_driver, "Name": "volume_foo"}}, "result": True, } assert len(volumes) == 1 assert volumes[0]["Name"] == "volume_foo" assert volumes[0]["Driver"] is default_driver # run it again with the same arguments orig_volumes = [volumes[0].copy()] ret = docker_state.present("volume_foo") assert ret == { "name": "volume_foo", "comment": "Volume 'volume_foo' already exists.", "changes": {}, "result": True, } assert orig_volumes == volumes # run it again with a different driver but don't force ret = docker_state.present("volume_foo", driver="local") assert ret == { "name": "volume_foo", "comment": ( "Driver for existing volume 'volume_foo'" " ('dummy_default') does not match specified" " driver ('local') and force is False" ), "changes": {}, "result": False, } assert orig_volumes == volumes # run it again with a different driver and force ret = docker_state.present("volume_foo", driver="local", force=True) assert ret == { "name": "volume_foo", "comment": "", "changes": { "removed": {"Driver": default_driver, "Name": "volume_foo"}, "created": {"Driver": "local", "Name": "volume_foo"}, }, "result": True, } mod_orig_volumes = [orig_volumes[0].copy()] mod_orig_volumes[0]["Driver"] = "local" assert mod_orig_volumes == volumes
# We should attempt to call the cmd 5 times assert cmd_mock.call_count == 5 cmd_mock.has_calls(expected_calls) def test_services_need_restart_checkrestart_missing(): """Test that the user is informed about the required dependency.""" with patch("salt.utils.path.which_bin", Mock(return_value=None)): with pytest.raises(CommandNotFoundError): aptpkg.services_need_restart() @patch("salt.utils.path.which_bin", Mock(return_value="/usr/sbin/checkrestart")) def test_services_need_restart(): """ Test that checkrestart output is parsed correctly """ cr_output = """ PROCESSES: 24 PROGRAMS: 17 PACKAGES: 8 SERVICE:rsyslog,385,/usr/sbin/rsyslogd SERVICE:cups-daemon,390,/usr/sbin/cupsd """ with patch.dict(aptpkg.__salt__, {"cmd.run_stdout": Mock(return_value=cr_output)}): assert sorted(aptpkg.services_need_restart()) == [
def test_services_need_restart_checkrestart_missing(): """Test that the user is informed about the required dependency.""" with patch("salt.utils.path.which_bin", Mock(return_value=None)): with pytest.raises(CommandNotFoundError): aptpkg.services_need_restart()
# Import salt libs import salt.ext.six as six from salt.modules import deb_postgres deb_postgres.__grains__ = None # in order to stub it w/patch below deb_postgres.__salt__ = None # in order to stub it w/patch below LSCLUSTER = '''\ 8.4 main 5432 online postgres /srv/8.4/main \ /var/log/postgresql/postgresql-8.4-main.log 9.1 main 5433 online postgres /srv/9.1/main \ /var/log/postgresql/postgresql-9.1-main.log ''' if NO_MOCK is False: SALT_STUB = { 'config.option': Mock(), 'cmd.run_all': Mock(return_value={'stdout': LSCLUSTER}), 'file.chown': Mock(), 'file.remove': Mock(), } else: SALT_STUB = {} @skipIf(NO_MOCK, NO_MOCK_REASON) @patch.multiple(deb_postgres, __salt__=SALT_STUB) @patch('salt.utils.which', Mock(return_value='/usr/bin/pg_createcluster')) class PostgresClusterTestCase(TestCase): def test_cluster_create(self): deb_postgres.cluster_create('9.3', 'main',
from tests.support.runtests import RUNTIME_VARS from tests.support.unit import skipIf try: import servicemanager import win32api import win32event import win32service import win32serviceutil CODE_DIR = win32api.GetLongPathName(RUNTIME_VARS.CODE_DIR) HAS_WIN32 = True except ImportError: # Mock win32serviceutil object to avoid # a stacktrace in the _ServiceManager class win32serviceutil = Mock() HAS_WIN32 = False logger = logging.getLogger(__name__) PASSWORD = "******" NOPRIV_STDERR = "ERROR: Logged-on user does not have administrative privilege.\n" PRIV_STDOUT = ( "\nINFO: The system global flag 'maintain objects list' needs\n " "to be enabled to see local opened files.\n See Openfiles " "/? for more information.\n\n\nFiles opened remotely via local share " "points:\n---------------------------------------------\n\n" "INFO: No shared open files found.\n") if HAS_WIN32: RUNAS_PATH = os.path.abspath(os.path.join(CODE_DIR, "runas.py")) RUNAS_OUT = os.path.abspath(os.path.join(CODE_DIR, "runas.out"))
class CpTestCase(TestCase, LoaderModuleMockMixin): ''' TestCase for salt.modules.cp module ''' def setup_loader_modules(self): return {cp: {}} def test__render_filenames_undefined_template(self): ''' Test if _render_filenames fails upon getting a template not in TEMPLATE_REGISTRY. ''' path = '/srv/salt/saltines' dest = '/srv/salt/cheese' saltenv = 'base' template = 'biscuits' ret = (path, dest) self.assertRaises(CommandExecutionError, cp._render_filenames, path, dest, saltenv, template) def test__render_filenames_render_failed(self): ''' Test if _render_filenames fails when template rendering fails. ''' path = 'salt://saltines' dest = '/srv/salt/cheese' saltenv = 'base' template = 'jinja' file_data = 'Remember to keep your files well salted.' mock_jinja = lambda *args, **kwargs: { 'result': False, 'data': file_data } with patch.dict(templates.TEMPLATE_REGISTRY, {'jinja': mock_jinja}): with patch('salt.utils.fopen', mock_open(read_data=file_data)): self.assertRaises(CommandExecutionError, cp._render_filenames, path, dest, saltenv, template) def test__render_filenames_success(self): ''' Test if _render_filenames succeeds. ''' path = 'salt://saltines' dest = '/srv/salt/cheese' saltenv = 'base' template = 'jinja' file_data = '/srv/salt/biscuits' mock_jinja = lambda *args, **kwargs: { 'result': True, 'data': file_data } ret = (file_data, file_data ) # salt.utils.fopen can only be mocked once with patch.dict(templates.TEMPLATE_REGISTRY, {'jinja': mock_jinja}): with patch('salt.utils.fopen', mock_open(read_data=file_data)): self.assertEqual( cp._render_filenames(path, dest, saltenv, template), ret) @patch('salt.modules.cp.hash_file', MagicMock(return_value=False)) def test_get_file_not_found(self): ''' Test if get_file can't find the file. ''' path = 'salt://saltines' dest = '/srv/salt/cheese' ret = '' self.assertEqual(cp.get_file(path, dest), ret) def test_get_file_str_success(self): ''' Test if get_file_str succeeds. ''' path = 'salt://saltines' dest = '/srv/salt/cheese/saltines' file_data = 'Remember to keep your files well salted.' saltenv = 'base' ret = file_data with patch('salt.utils.fopen', mock_open(read_data=file_data)): with patch('salt.modules.cp.cache_file', MagicMock(return_value=dest)): self.assertEqual(cp.get_file_str(path, dest), ret) def test_push_non_absolute_path(self): ''' Test if push fails on a non absolute path. ''' path = '../saltines' ret = False self.assertEqual(cp.push(path), ret) def test_push_dir_non_absolute_path(self): ''' Test if push_dir fails on a non absolute path. ''' path = '../saltines' ret = False self.assertEqual(cp.push_dir(path), ret) @patch('salt.modules.cp.os.path', MagicMock(isfile=Mock(return_value=True), wraps=cp.os.path)) @patch.multiple( 'salt.modules.cp', _auth=MagicMock(**{'return_value.gen_token.return_value': 'token'}), __opts__={ 'id': 'abc', 'file_buffer_size': 10 }) @patch('salt.utils.fopen', mock_open(read_data='content')) @patch('salt.transport.Channel.factory', MagicMock()) def test_push(self): ''' Test if push works with good posix path. ''' response = cp.push('/saltines/test.file') self.assertEqual(response, True) self.assertEqual(salt.utils.fopen().read.call_count, 2) # pylint: disable=resource-leakage salt.transport.Channel.factory({}).send.assert_called_once_with( dict( loc=salt.utils.fopen().tell(), # pylint: disable=resource-leakage cmd='_file_recv', tok='token', path=['saltines', 'test.file'], data= '', # data is empty here because load['data'] is overwritten id='abc'))
def mock_json_response(data): response = MagicMock() response.json = MagicMock(return_value=data) return Mock(return_value=response)
def test_show(self): ''' Test that the pkg.show function properly parses apt-cache show output. This test uses an abridged output per package, for simplicity. ''' show_mock_success = MagicMock(return_value={ 'retcode': 0, 'pid': 12345, 'stderr': '', 'stdout': textwrap.dedent('''\ Package: foo1.0 Architecture: amd64 Version: 1.0.5-3ubuntu4 Description: A silly package (1.0 release cycle) Provides: foo Suggests: foo-doc Package: foo1.0 Architecture: amd64 Version: 1.0.4-2ubuntu1 Description: A silly package (1.0 release cycle) Provides: foo Suggests: foo-doc Package: foo-doc Architecture: all Version: 1.0.5-3ubuntu4 Description: Silly documentation for a silly package (1.0 release cycle) Package: foo-doc Architecture: all Version: 1.0.4-2ubuntu1 Description: Silly documentation for a silly package (1.0 release cycle) '''), }) show_mock_failure = MagicMock(return_value={ 'retcode': 1, 'pid': 12345, 'stderr': textwrap.dedent('''\ N: Unable to locate package foo* N: Couldn't find any package by glob 'foo*' N: Couldn't find any package by regex 'foo*' E: No packages found '''), 'stdout': '', }) refresh_mock = Mock() expected = { 'foo1.0': { '1.0.5-3ubuntu4': { 'Architecture': 'amd64', 'Description': 'A silly package (1.0 release cycle)', 'Provides': 'foo', 'Suggests': 'foo-doc', }, '1.0.4-2ubuntu1': { 'Architecture': 'amd64', 'Description': 'A silly package (1.0 release cycle)', 'Provides': 'foo', 'Suggests': 'foo-doc', }, }, 'foo-doc': { '1.0.5-3ubuntu4': { 'Architecture': 'all', 'Description': 'Silly documentation for a silly package (1.0 release cycle)', }, '1.0.4-2ubuntu1': { 'Architecture': 'all', 'Description': 'Silly documentation for a silly package (1.0 release cycle)', }, }, } # Make a copy of the above dict and strip out some keys to produce the # expected filtered result. filtered = copy.deepcopy(expected) for k1 in filtered: for k2 in filtered[k1]: # Using list() because we will modify the dict during iteration for k3 in list(filtered[k1][k2]): if k3 not in ('Description', 'Provides'): filtered[k1][k2].pop(k3) with patch.dict(aptpkg.__salt__, {'cmd.run_all': show_mock_success}), \ patch.object(aptpkg, 'refresh_db', refresh_mock): # Test success (no refresh) self.assertEqual(aptpkg.show('foo*'), expected) refresh_mock.assert_not_called() refresh_mock.reset_mock() # Test success (with refresh) self.assertEqual(aptpkg.show('foo*', refresh=True), expected) self.assert_called_once(refresh_mock) refresh_mock.reset_mock() # Test filtered return self.assertEqual( aptpkg.show('foo*', filter='description,provides'), filtered ) refresh_mock.assert_not_called() refresh_mock.reset_mock() with patch.dict(aptpkg.__salt__, {'cmd.run_all': show_mock_failure}), \ patch.object(aptpkg, 'refresh_db', refresh_mock): # Test failure (no refresh) self.assertEqual(aptpkg.show('foo*'), {}) refresh_mock.assert_not_called() refresh_mock.reset_mock() # Test failure (with refresh) self.assertEqual(aptpkg.show('foo*', refresh=True), {}) self.assert_called_once(refresh_mock) refresh_mock.reset_mock()
def test_status(self): """ Test to confirm that the function retries when the service is in the activating/deactivating state. """ active = {"stdout": "active", "stderr": "", "retcode": 0, "pid": 12345} inactive = { "stdout": "inactive", "stderr": "", "retcode": 3, "pid": 12345 } activating = { "stdout": "activating", "stderr": "", "retcode": 3, "pid": 12345 } deactivating = { "stdout": "deactivating", "stderr": "", "retcode": 3, "pid": 12345, } check_mock = Mock() cmd_mock = MagicMock( side_effect=[activating, activating, active, inactive]) with patch.dict(systemd.__salt__, {"cmd.run_all": cmd_mock}), patch.object( systemd, "_check_for_unit_changes", check_mock): ret = systemd.status("foo") assert ret is True # We should only have had three calls, since the third was not # either in the activating or deactivating state and we should not # have retried after. assert cmd_mock.call_count == 3 cmd_mock = MagicMock( side_effect=[deactivating, deactivating, inactive, active]) with patch.dict(systemd.__salt__, {"cmd.run_all": cmd_mock}), patch.object( systemd, "_check_for_unit_changes", check_mock): ret = systemd.status("foo") assert ret is False # We should only have had three calls, since the third was not # either in the activating or deactivating state and we should not # have retried after. assert cmd_mock.call_count == 3 cmd_mock = MagicMock( side_effect=[activating, activating, active, inactive]) with patch.dict(systemd.__salt__, {"cmd.run_all": cmd_mock}), patch.object( systemd, "_check_for_unit_changes", check_mock): ret = systemd.status("foo", wait=0.25) assert ret is False # We should only have had two calls, because "wait" was set too low # to allow for more than one retry. assert cmd_mock.call_count == 2 cmd_mock = MagicMock(side_effect=[active, inactive]) with patch.dict(systemd.__salt__, {"cmd.run_all": cmd_mock}), patch.object( systemd, "_check_for_unit_changes", check_mock): ret = systemd.status("foo") assert ret is True # We should only have a single call, because the first call was in # the active state. assert cmd_mock.call_count == 1 cmd_mock = MagicMock(side_effect=[inactive, active]) with patch.dict(systemd.__salt__, {"cmd.run_all": cmd_mock}), patch.object( systemd, "_check_for_unit_changes", check_mock): ret = systemd.status("foo") assert ret is False # We should only have a single call, because the first call was in # the inactive state. assert cmd_mock.call_count == 1
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import skipIf, TestCase from tests.support.mock import NO_MOCK, NO_MOCK_REASON, MagicMock, Mock, patch # Import salt libs import salt.modules.uwsgi as uwsgi @skipIf(NO_MOCK, NO_MOCK_REASON) @patch('salt.utils.which', Mock(return_value='/usr/bin/uwsgi')) class UwsgiTestCase(TestCase, LoaderModuleMockMixin): def setup_loader_modules(self): return {uwsgi: {}} def test_uwsgi_stats(self): socket = "127.0.0.1:5050" mock = MagicMock(return_value='{"a": 1, "b": 2}') with patch.dict(uwsgi.__salt__, {'cmd.run': mock}): result = uwsgi.stats(socket) mock.assert_called_once_with( ['uwsgi', '--connect-and-read', '{0}'.format(socket)], python_shell=False) self.assertEqual(result, {'a': 1, 'b': 2})
def test_if_lsattr_is_missing_it_should_return_None(self): patch_which = patch("hubblestack.utils.path.which", Mock(return_value=None),) with patch_which: actual = filemod.lsattr("foo") assert actual is None, actual
def test_yum_base_error(self): if not yumpkg.HAS_YUM: sys.modules['yum'] = Mock() with patch('yum.YumBase') as mock_yum_yumbase: mock_yum_yumbase.side_effect = CommandExecutionError self.assertRaises(CommandExecutionError, yumpkg._get_yum_config)
def run(self, result=None): patch_aix = patch("hubblestack.utils.platform.is_aix", Mock(return_value=False),) patch_exists = patch("os.path.exists", Mock(return_value=True),) patch_which = patch("hubblestack.utils.path.which", Mock(return_value="some/tune2fs"),) with patch_aix, patch_exists, patch_which: super(ChattrTests, self).run(result)
def test_sls_sync(subtests): """ Test test.sls with the sync argument We're only mocking the sync functions we expect to sync. If any other sync functions are run then they will raise a KeyError, which we want as it will tell us that we are syncing things we shouldn't. """ expected_err_msg = "{} called {} time(s) (expected: {})" mock_empty_list = MagicMock(return_value=[]) with patch.object(state, "running", mock_empty_list), patch.object( state, "_disabled", mock_empty_list), patch.object(state, "_get_pillar_errors", mock_empty_list): with subtests.test("sync_mods=modules,states"): sync_mocks = { "saltutil.sync_modules": Mock(), "saltutil.sync_states": Mock(), } if salt.utils.platform.is_windows(): sync_mocks["cmd.run"] = Mock() with patch.dict(state.__salt__, sync_mocks): state.sls("foo", sync_mods="modules,states") for key in sync_mocks: call_count = sync_mocks[key].call_count expected = 1 assert call_count == expected, expected_err_msg.format( key, call_count, expected) with subtests.test("sync_mods=all"): # Test syncing all sync_mocks = {"saltutil.sync_all": Mock()} if salt.utils.platform.is_windows(): sync_mocks["cmd.run"] = Mock() with patch.dict(state.__salt__, sync_mocks): state.sls("foo", sync_mods="all") for key in sync_mocks: call_count = sync_mocks[key].call_count expected = 1 assert call_count == expected, expected_err_msg.format( key, call_count, expected) with subtests.test("sync_mods=True"): # sync_mods=True should be interpreted as sync_mods=all sync_mocks = {"saltutil.sync_all": Mock()} if salt.utils.platform.is_windows(): sync_mocks["cmd.run"] = Mock() with patch.dict(state.__salt__, sync_mocks): state.sls("foo", sync_mods=True) for key in sync_mocks: call_count = sync_mocks[key].call_count expected = 1 assert call_count == expected, expected_err_msg.format( key, call_count, expected) with subtests.test("sync_mods=modules,all"): # Test syncing all when "all" is passed along with module types. # This tests that we *only* run a sync_all and avoid unnecessary # extra syncing. sync_mocks = {"saltutil.sync_all": Mock()} if salt.utils.platform.is_windows(): sync_mocks["cmd.run"] = Mock() with patch.dict(state.__salt__, sync_mocks): state.sls("foo", sync_mods="modules,all") for key in sync_mocks: call_count = sync_mocks[key].call_count expected = 1 assert call_count == expected, expected_err_msg.format( key, call_count, expected)
def setup_loader_modules(self): self.WMI = Mock() self.addCleanup(delattr, self, "WMI") return {win_network: {}}
def setup_loader_modules(self): patcher = patch('salt.utils.path.which', Mock(return_value='/usr/bin/nginx')) patcher.start() self.addCleanup(patcher.stop) return {nginx: {'_urlopen': Mock(return_value=MockUrllibStatus())}}
def test_absent(name): """ Test various cases for win_path.absent """ ret_base = {"name": name, "result": True, "changes": {}} def _mock(retval): # Return a new MagicMock for each test case return MagicMock(side_effect=retval) # We don't really want to run the remove func with patch.dict(win_path.__salt__, {"win_path.remove": Mock()}): # Test mode OFF with patch.dict(win_path.__opts__, {"test": False}): # Test already absent with patch.dict(win_path.__salt__, {"win_path.exists": _mock([False])}): ret = copy.deepcopy(ret_base) ret["comment"] = "{} is not in the PATH".format(name) ret["result"] = True assert win_path.absent(name) == ret # Test successful removal with patch.dict(win_path.__salt__, {"win_path.exists": _mock([True, False])}): ret = copy.deepcopy(ret_base) ret["comment"] = "Removed {} from the PATH".format(name) ret["changes"]["removed"] = name ret["result"] = True assert win_path.absent(name) == ret # Test unsucessful removal with patch.dict(win_path.__salt__, {"win_path.exists": _mock([True, True])}): ret = copy.deepcopy(ret_base) ret["comment"] = "Failed to remove {} from the PATH".format( name) ret["result"] = False assert win_path.absent(name) == ret # Test mode ON with patch.dict(win_path.__opts__, {"test": True}): # Test already absent with patch.dict(win_path.__salt__, {"win_path.exists": _mock([False])}): ret = copy.deepcopy(ret_base) ret["comment"] = "{} is not in the PATH".format(name) ret["result"] = True assert win_path.absent(name) == ret # Test the test-mode return with patch.dict(win_path.__salt__, {"win_path.exists": _mock([True])}): ret = copy.deepcopy(ret_base) ret["comment"] = "{} would be removed from the PATH".format( name) ret["result"] = None assert win_path.absent(name) == ret
# Import Salt libs from salt.ext import six # Import Salt Testing libs from tests.support.unit import skipIf, TestCase from tests.support.mock import NO_MOCK, NO_MOCK_REASON, Mock, patch, ANY # wmi and pythoncom modules are platform specific... wmi = types.ModuleType('wmi') sys.modules['wmi'] = wmi pythoncom = types.ModuleType('pythoncom') sys.modules['pythoncom'] = pythoncom if NO_MOCK is False: WMI = Mock() wmi.WMI = Mock(return_value=WMI) pythoncom.CoInitialize = Mock() pythoncom.CoUninitialize = Mock() # This is imported late so mock can do its job import salt.modules.win_status as status @skipIf(NO_MOCK, NO_MOCK_REASON) @skipIf(sys.stdin.encoding != 'UTF-8', 'UTF-8 encoding required for this test is not supported') @skipIf(status.HAS_WMI is False, 'This test requires Windows') class TestProcsBase(TestCase): def __init__(self, *args, **kwargs): TestCase.__init__(self, *args, **kwargs)
def test_get_system_info(self): fields = [ "bios_caption", "bios_description", "bios_details", "bios_manufacturer", "bios_version", "bootup_state", "caption", "chassis_bootup_state", "chassis_sku_number", "description", "dns_hostname", "domain", "domain_role", "hardware_manufacturer", "hardware_model", "hardware_serial", "install_date", "last_boot", "name", "network_server_mode_enabled", "organization", "os_architecture", "os_manufacturer", "os_name", "os_type", "os_version", "part_of_domain", "pc_system_type", "power_state", "primary", "processor_cores", "processor_cores_enabled", "processor_manufacturer", "processor_max_clock_speed", "processors", "processors_logical", "registered_user", "status", "system_directory", "system_drive", "system_type", "thermal_state", "total_physical_memory", "total_physical_memory_raw", "users", "windows_directory", "workgroup", ] with patch( "salt.utils.win_system.get_computer_name", MagicMock()), patch( "salt.utils.winapi.Com", MagicMock()), patch.object( self.WMI, "Win32_OperatingSystem", return_value=[ MockWMI_OperatingSystem() ]), patch.object( self.WMI, "Win32_ComputerSystem", return_value=[ MockWMI_ComputerSystem() ]), patch.object( self.WMI, "Win32_ComputerSystemProduct", return_value=[MockWMI_ComputerSystemProduct()], ), patch.object( self.WMI, "Win32_Processor", return_value=[ MockWMI_Processor(), MockWMI_Processor() ], ), patch.object( self.WMI, "Win32_BIOS", return_value=[MockWMI_BIOS()]), patch.object( wmi, "WMI", Mock(return_value=self.WMI)): ret = win_system.get_system_info() # Make sure all the fields are in the return for field in fields: self.assertIn(field, ret) # os_type os_types = ["Work Station", "Domain Controller", "Server"] self.assertIn(ret["os_type"], os_types) domain_roles = [ "Standalone Workstation", "Member Workstation", "Standalone Server", "Member Server", "Backup Domain Controller", "Primary Domain Controller", ] self.assertIn(ret["domain_role"], domain_roles) system_types = [ "Unspecified", "Desktop", "Mobile", "Workstation", "Enterprise Server", "SOHO Server", "Appliance PC", "Performance Server", "Slate", "Maximum", ] self.assertIn(ret["pc_system_type"], system_types) warning_states = [ "Other", "Unknown", "Safe", "Warning", "Critical", "Non-recoverable", ] self.assertIn(ret["chassis_bootup_state"], warning_states) self.assertIn(ret["thermal_state"], warning_states)
def call_procs(self): WMI.win32_process = Mock(return_value=self.__processes) self.result = status.procs()
def _fake_makedir(self, num=errno.EEXIST): def _side_effect(*args, **kwargs): raise OSError(num, "Errno {0}".format(num)) return Mock(side_effect=_side_effect)
class PostgresUserTestCase(TestCase): @patch.dict(SALT_STUB, { 'postgres.role_get': Mock(return_value=None), 'postgres.user_create': MagicMock(), }) def test_present__creation(self): # test=True with patch.dict(postgres_user.__opts__, {'test': True}): ret = postgres_user.present('foo') self.assertEqual( ret, {'comment': 'User foo is set to be created', 'changes': {}, 'name': 'foo', 'result': None} ) self.assertEqual(SALT_STUB['postgres.user_create'].call_count, 0) # test=False ret = postgres_user.present('foo') self.assertEqual( ret, {'comment': 'The user foo has been created', 'changes': {'foo': 'Present'}, 'name': 'foo', 'result': True} ) SALT_STUB['postgres.user_create'].assert_called_once_with(username='******', superuser=None, encrypted=True, runas=None, inherit=None, rolepassword=None, port=None, replication=None, host=None, createroles=None, user=None, groups=None, maintenance_db=None, login=None, password=None, createdb=None) @patch.dict(SALT_STUB, { 'postgres.role_get': Mock(return_value={ 'can create databases': False, 'can create roles': False, 'can login': False, 'can update system catalogs': False, 'connections': None, 'defaults variables': {}, 'expiry time': None, 'inherits privileges': True, 'replication': False, 'superuser': False, }), 'postgres.user_update': MagicMock(), }) def test_present__update(self): # test=True with patch.dict(postgres_user.__opts__, {'test': True}): ret = postgres_user.present('foo', login=True, replication=False) self.assertEqual( ret, {'comment': 'User foo is set to be updated', 'changes': {'foo': {'login': True}}, 'name': 'foo', 'result': None} ) self.assertEqual(SALT_STUB['postgres.user_update'].call_count, 0) # test=False ret = postgres_user.present('foo', login=True, replication=False) self.assertEqual( ret, {'comment': 'The user foo has been updated', 'changes': {'foo': {'login': True}}, 'name': 'foo', 'result': True} ) SALT_STUB['postgres.user_update'].assert_called_once_with(username='******', superuser=None, encrypted=True, runas=None, inherit=None, rolepassword=None, port=None, replication=False, host=None, createroles=None, user=None, groups=None, maintenance_db=None, login=True, password=None, createdb=None) @patch.dict(SALT_STUB, { 'postgres.role_get': Mock(return_value={ 'can create databases': False, 'can create roles': False, 'can login': False, 'can update system catalogs': False, 'connections': None, 'defaults variables': {}, 'expiry time': None, 'inherits privileges': True, 'replication': False, 'superuser': False, }), 'postgres.user_update': MagicMock(), }) def test_present__no_update(self): # test=True with patch.dict(OPTS, {'test': True}): ret = postgres_user.present('foo', login=False, replication=False) self.assertEqual( ret, {'comment': 'User foo is already present', 'changes': {}, 'name': 'foo', 'result': True} ) self.assertEqual(SALT_STUB['postgres.user_update'].call_count, 0) # test=False ret = postgres_user.present('foo', login=False, replication=False) self.assertEqual( ret, {'comment': 'User foo is already present', 'changes': {}, 'name': 'foo', 'result': True} ) self.assertEqual(SALT_STUB['postgres.user_update'].call_count, 0)