def test_runner(self): ''' Test for execute a runner on the master and return the data from the runner function ''' with patch.dict(raet_publish.__opts__, {'id': 'id'}): with patch.object(salt.transport.Channel, 'factory', MagicMock()): self.assertTrue(raet_publish.runner('fun')) class MockFactory(object): ''' Mock factory class ''' load = '' def send(self, load): ''' mock send method ''' self.load = load raise SaltReqTimeoutError(load) with patch.dict(raet_publish.__opts__, {'id': 'id'}): with patch.object(salt.transport.Channel, 'factory', MagicMock(return_value=MockFactory())): self.assertEqual(raet_publish.runner(1), '\'1\' runner publish timed out')
def test_get(self): ''' Test if it get a value from etcd, by direct path ''' class MockEtcd(object): """ Mock of etcd """ value = 'salt' def __init__(self): self.key = None def get(self, key): """ Mock of get method """ self.key = key if key == '': raise KeyError elif key == 'err': raise return MockEtcd with patch.object(etcd_util, 'get_conn', MagicMock(return_value=MockEtcd())): self.assertEqual(etcd_mod.get_('salt'), 'salt') with patch.object(etcd_util, 'tree', MagicMock(return_value={})): self.assertDictEqual(etcd_mod.get_('salt', recurse=True), {}) self.assertEqual(etcd_mod.get_(''), '') self.assertRaises(Exception, etcd_mod.get_, 'err')
def test_fire_master(self, salt_crypt_sauth, salt_transport_channel_factory): ''' Test for Fire an event off up to the master server ''' preload = {'id': 'id', 'tag': 'tag', 'data': 'data', 'tok': 'salt', 'cmd': '_minion_event'} with patch.dict(event.__opts__, {'transport': 'raet', 'id': 'id', 'local': False}): with patch.object(salt_transport_channel_factory, 'send', return_value=None): self.assertTrue(event.fire_master('data', 'tag')) with patch.dict(event.__opts__, {'transport': 'A', 'id': 'id', 'master_uri': 'localhost', 'local': False}): with patch.object(salt_crypt_sauth, 'gen_token', return_value='tok'): with patch.object(salt_transport_channel_factory, 'send', return_value=None): self.assertTrue(event.fire_master('data', 'tag', preload)) with patch.dict(event.__opts__, {'transport': 'A', 'local': False}): with patch.object(salt.utils.event.MinionEvent, 'fire_event', side_effect=Exception('foo')): self.assertFalse(event.fire_master('data', 'tag'))
def test_pkg(self): ''' Test to execute a packaged state run ''' mock = MagicMock(side_effect=[False, True, True, True, True, True]) with patch.object(os.path, 'isfile', mock): self.assertEqual(state.pkg("/tmp/state_pkg.tgz", "", "md5"), {}) mock = MagicMock(side_effect=[False, 0, 0, 0, 0]) with patch.object(salt.utils, 'get_hash', mock): self.assertDictEqual(state.pkg("/tmp/state_pkg.tgz", "", "md5"), {}) self.assertDictEqual(state.pkg("/tmp/state_pkg.tgz", 0, "md5"), {}) MockTarFile.path = "" MockJson.flag = True with patch('salt.utils.fopen', mock_open()): self.assertListEqual(state.pkg("/tmp/state_pkg.tgz", 0, "md5"), [True]) MockTarFile.path = "" MockJson.flag = False with patch('salt.utils.fopen', mock_open()): self.assertTrue(state.pkg("/tmp/state_pkg.tgz", 0, "md5"))
def test_provider_case_insensitive(self): ''' Ensure that both lowercase and non-lowercase values are supported ''' provider = 'GitPython' for role_name, role_class in ( ('gitfs', salt.utils.gitfs.GitFS), ('git_pillar', salt.utils.gitfs.GitPillar), ('winrepo', salt.utils.gitfs.WinRepo)): key = '{0}_provider'.format(role_name) with patch.object(role_class, 'verify_gitpython', MagicMock(return_value=True)): with patch.object(role_class, 'verify_pygit2', MagicMock(return_value=False)): with patch.object(role_class, 'verify_dulwich', MagicMock(return_value=False)): args = [OPTS] if role_name == 'winrepo': args.append('/tmp/winrepo-dir') with patch.dict(OPTS, {key: provider}): # Try to create an instance with uppercase letters in # provider name. If it fails then a # FileserverConfigError will be raised, so no assert is # necessary. role_class(*args) # Now try to instantiate an instance with all lowercase # letters. Again, no need for an assert here. role_class(*args)
def test_set_hwclock(self): ''' Test to sets the hardware clock to be either UTC or localtime ''' zone = 'America/Denver' with patch.object(timezone, 'get_zone', return_value=zone): with patch.dict(timezone.__grains__, {'os_family': 'Solaris', 'cpuarch': 'sparc'}): self.assertRaises( SaltInvocationError, timezone.set_hwclock, 'clock' ) self.assertRaises( SaltInvocationError, timezone.set_hwclock, 'localtime' ) with patch.dict(timezone.__grains__, {'os_family': 'DoesNotMatter'}): with patch.object(os.path, 'exists', return_value=False): self.assertRaises( CommandExecutionError, timezone.set_hwclock, 'UTC' )
def test_get_enabled(self): ''' Test to return a list of all enabled services ''' cmd_mock = MagicMock(return_value=_LIST_UNIT_FILES) listdir_mock = MagicMock(return_value=['foo', 'bar', 'baz', 'README']) sd_mock = MagicMock( return_value=set( [x.replace('.service', '') for x in _SYSTEMCTL_STATUS] ) ) access_mock = MagicMock( side_effect=lambda x, y: x != os.path.join( systemd.INITSCRIPT_PATH, 'README' ) ) sysv_enabled_mock = MagicMock(side_effect=lambda x: x == 'baz') with patch.dict(systemd.__salt__, {'cmd.run': cmd_mock}): with patch.object(os, 'listdir', listdir_mock): with patch.object(systemd, '_get_systemd_services', sd_mock): with patch.object(os, 'access', side_effect=access_mock): with patch.object(systemd, '_sysv_enabled', sysv_enabled_mock): self.assertListEqual( systemd.get_enabled(), ['baz', 'service1', 'timer1.timer'] )
def test_usage(self): ''' Test if it shows in which disk the chunks are allocated. ''' mock = MagicMock(return_value={'retcode': 1, 'stderr': '', 'stdout': 'Salt'}) with patch.dict(btrfs.__salt__, {'cmd.run_all': mock}): mock = MagicMock(return_value={'Salt': 'salt'}) with patch.object(btrfs, '_usage_specific', mock): self.assertDictEqual(btrfs.usage('/dev/sda1'), {'Salt': 'salt'}) mock = MagicMock(return_value={'retcode': 1, 'stderr': '', 'stdout': 'Unallocated:\n'}) with patch.dict(btrfs.__salt__, {'cmd.run_all': mock}): mock = MagicMock(return_value={'/dev/sda1': True}) with patch.object(btrfs, '_usage_unallocated', mock): self.assertDictEqual(btrfs.usage('/dev/sda1'), {'unallocated': {'/dev/sda1': True}}) mock = MagicMock(return_value={'retcode': 1, 'stderr': '', 'stdout': 'Overall:\n'}) with patch.dict(btrfs.__salt__, {'cmd.run_all': mock}): mock = MagicMock(return_value={'/dev/sda1': True}) with patch.object(btrfs, '_usage_overall', mock): self.assertDictEqual(btrfs.usage('/dev/sda1'), {'overall': {'/dev/sda1': True}})
def test_get_saved_policy(self): ''' Test if it return the current policy for the specified table/chain ''' self.assertEqual(iptables.get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'), 'Error: Chain needs to be specified') with patch.object(iptables, '_parse_conf', MagicMock(return_value={'filter': {'INPUT': {'policy': True}}})): self.assertTrue(iptables.get_saved_policy(table='filter', chain='INPUT', conf_file=None, family='ipv4')) with patch.object(iptables, '_parse_conf', MagicMock(return_value={'filter': {'INPUT': {'policy1': True}}})): self.assertIsNone(iptables.get_saved_policy(table='filter', chain='INPUT', conf_file=None, family='ipv4'))
def test_get_disabled(self): ''' Test to return a list of all disabled services ''' cmd_mock = MagicMock(return_value=_LIST_UNIT_FILES) # 'foo' should collide with the systemd services (as returned by # sd_mock) and thus not be returned by _get_sysv_services(). It doesn't # matter that it's not part of the _LIST_UNIT_FILES output, we just # want to ensure that 'foo' isn't identified as a disabled initscript # even though below we are mocking it to show as not enabled (since # only 'baz' will be considered an enabled sysv service). listdir_mock = MagicMock(return_value=['foo', 'bar', 'baz', 'README']) sd_mock = MagicMock( return_value=set( [x.replace('.service', '') for x in _SYSTEMCTL_STATUS] ) ) access_mock = MagicMock( side_effect=lambda x, y: x != os.path.join( systemd.INITSCRIPT_PATH, 'README' ) ) sysv_enabled_mock = MagicMock(side_effect=lambda x: x == 'baz') with patch.dict(systemd.__salt__, {'cmd.run': cmd_mock}): with patch.object(os, 'listdir', listdir_mock): with patch.object(systemd, '_get_systemd_services', sd_mock): with patch.object(os, 'access', side_effect=access_mock): with patch.object(systemd, '_sysv_enabled', sysv_enabled_mock): self.assertListEqual( systemd.get_disabled(), ['bar', 'service2', 'timer2.timer'] )
def test_missing(self): ''' Test to the inverse of service.available. ''' mock = MagicMock(side_effect=lambda x: _SYSTEMCTL_STATUS[x]) # systemd < 231 with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 230}): with patch.object(systemd, '_systemctl_status', mock): self.assertFalse(systemd.missing('sshd.service')) self.assertTrue(systemd.missing('foo.service')) # systemd >= 231 with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 231}): with patch.dict(_SYSTEMCTL_STATUS, _SYSTEMCTL_STATUS_GTE_231): with patch.object(systemd, '_systemctl_status', mock): self.assertFalse(systemd.missing('sshd.service')) self.assertTrue(systemd.missing('bar.service')) # systemd < 231 with retcode/output changes backported (e.g. RHEL 7.3) with patch.dict(systemd.__context__, {'salt.utils.systemd.version': 219}): with patch.dict(_SYSTEMCTL_STATUS, _SYSTEMCTL_STATUS_GTE_231): with patch.object(systemd, '_systemctl_status', mock): self.assertFalse(systemd.missing('sshd.service')) self.assertTrue(systemd.missing('bar.service'))
def test_user_remove(self): ''' Tests to remove a cluster admin or a database user. ''' with patch.object(influx, 'user_exists', return_value=False): self.assertFalse(influx.user_remove(name='A', user='******', password='******', host='localhost', port=8000)) self.assertFalse(influx.user_remove(name='A', database='test', user='******', password='******', host='localhost', port=8000)) mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): with patch.object(influx, 'user_exists', return_value=True): self.assertTrue(influx.user_remove(name='A', user='******', password='******', host='localhost', port=8000)) self.assertTrue(influx.user_remove(name='A', database='test', user='******', password='******', host='localhost', port=8000))
def test_genrepo(self): ''' Test to refresh the winrepo.p file of the repository ''' ret = {'name': 'salt', 'changes': {}, 'result': False, 'comment': ''} mock = MagicMock(side_effect=[False, True, True, True, True, True, True]) with patch.object(os.path, 'exists', mock): ret.update({'comment': 'missing /srv/salt/win/repo'}) self.assertDictEqual(winrepo.genrepo('salt'), ret) mock = MagicMock(return_value={'win_repo': 'salt', 'win_repo_mastercachefile': 'abc'}) with patch.object(salt.config, 'master_config', mock): mock = MagicMock(return_value=[0, 1, 2, 3, 4, 5, 6, 7, 8]) with patch.object(os, 'stat', mock): mock = MagicMock(return_value=[]) with patch.object(os, 'walk', mock): with patch.dict(winrepo.__opts__, {"test": True}): ret.update({'comment': '', 'result': None}) self.assertDictEqual(winrepo.genrepo('salt'), ret) with patch.dict(winrepo.__opts__, {"test": False}): ret.update({'result': True}) self.assertDictEqual(winrepo.genrepo('salt'), ret) ret.update({'changes': {'winrepo': []}}) self.assertDictEqual(winrepo.genrepo('salt', True), ret)
def test_selfupdate(self): """ Test for Composer selfupdate """ mock = MagicMock(return_value=False) with patch.object(composer, "_valid_composer", mock): self.assertRaises(CommandNotFoundError, composer.selfupdate) mock = MagicMock(return_value=True) with patch.object(composer, "_valid_composer", mock): mock = MagicMock(return_value={"retcode": 1, "stderr": "A"}) with patch.dict(composer.__salt__, {"cmd.run_all": mock}): self.assertRaises(CommandExecutionError, composer.selfupdate) mock = MagicMock(return_value=True) with patch.object(composer, "_valid_composer", mock): mock = MagicMock(return_value={"retcode": 0, "stderr": "A"}) with patch.dict(composer.__salt__, {"cmd.run_all": mock}): self.assertTrue(composer.selfupdate(quiet=True)) mock = MagicMock(return_value=True) with patch.object(composer, "_valid_composer", mock): rval = {"retcode": 0, "stderr": "A", "stdout": "B"} mock = MagicMock(return_value=rval) with patch.dict(composer.__salt__, {"cmd.run_all": mock}): self.assertEqual(composer.selfupdate(), rval)
def test_get_enabled(self): ''' Test to return a list of all enabled services ''' def sysv(name): if name in ['d', 'e']: return True return False def sysve(name): if name in ['e']: return True return False mock = MagicMock(return_value={"a": "enabled", "b": "enabled", "c": "disabled"}) lmock = MagicMock(return_value={"d": "disabled", "a": "disabled", "b": "disabled", "e": "disabled"}) with patch.object(systemd, "_sysv_is_disabled", sysve): with patch.object(systemd, "_service_is_sysv", sysv): with patch.object(systemd, '_get_all_unit_files', mock): with patch.object(systemd, '_get_all_units', lmock): self.assertListEqual( systemd.get_enabled(), ["a", "b", "d"])
def test_connect(self, mock_socket): ''' Test for Test connectivity to a host using a particular port from the minion. ''' self.assertDictEqual(network.connect(False, 'port'), {'comment': 'Required argument, host, is missing.', 'result': False}) self.assertDictEqual(network.connect('host', False), {'comment': 'Required argument, port, is missing.', 'result': False}) ret = 'Unable to connect to host (0) on tcp port port' mock_socket.side_effect = Exception('foo') with patch.object(salt.utils.network, 'sanitize_host', return_value='A'): with patch.object(socket, 'getaddrinfo', return_value=[['ipv4', 'A', 6, 'B', '0.0.0.0']]): self.assertDictEqual(network.connect('host', 'port'), {'comment': ret, 'result': False}) ret = 'Successfully connected to host (0) on tcp port port' mock_socket.side_effect = MagicMock() mock_socket.settimeout().return_value = None mock_socket.connect().return_value = None mock_socket.shutdown().return_value = None with patch.object(salt.utils.network, 'sanitize_host', return_value='A'): with patch.object(socket, 'getaddrinfo', return_value=[['ipv4', 'A', 6, 'B', '0.0.0.0']]): self.assertDictEqual(network.connect('host', 'port'), {'comment': ret, 'result': True})
def test_restart(self): ''' Test for Restart the named service ''' with patch.object(launchctl, 'stop', return_value=None): with patch.object(launchctl, 'start', return_value=True): self.assertTrue(launchctl.restart('job_label'))
def test_status(self): ''' Test for Return the status for a service ''' launchctl_data = '''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>salt-minion</string> <key>LastExitStatus</key> <integer>0</integer> <key>LimitLoadToSessionType</key> <string>System</string> <key>OnDemand</key> <false/> <key>PID</key> <integer>71</integer> <key>ProgramArguments</key> <array> <string>/usr/local/bin/salt-minion</string> </array> <key>TimeOut</key> <integer>30</integer> </dict> </plist>''' with patch.object(launchctl, '_service_by_name', return_value={'plist': {'Label': 'A'}}): if six.PY3: launchctl_data = salt.utils.to_bytes(launchctl_data) with patch.object(launchctl, '_get_launchctl_data', return_value=launchctl_data): self.assertTrue(launchctl.status('job_label'))
def test_lucene_version(self): ''' Test to get the lucene version that solr is using. ''' with patch.object(solr, '_get_return_dict', return_value={'A': 'a'}): with patch.object(solr, '_get_none_or_value', side_effect=[None, True, True]): with patch.object(solr, '_check_for_cores', side_effect=[True, False, False]): tempdict = {'success': 'success', 'errors': 'errors', 'data': {'lucene': {'lucene-spec-version': 1}}} with patch.object(solr, '_get_admin_info', side_effect=[tempdict, tempdict, {'success': None}]): with patch.dict(solr.__salt__, {'config.option': MagicMock(return_value=['A'])}): with patch.object(solr, '_update_return_dict', return_value={'A': 'a'}): self.assertDictEqual(solr.lucene_version('c'), {'A': 'a'}) self.assertDictEqual(solr.lucene_version('c'), {'A': 'a'}) self.assertDictEqual(solr.lucene_version('c'), {'success': None})
def test_set_replication_enabled(self): ''' Test to sets the master to ignore poll requests from the slaves. ''' with patch.object(solr, '_is_master', side_effect=[False, True, True, True]): with patch.object(solr, '_get_none_or_value', side_effect=[None, None, True, True, True]): with patch.object(solr, '_get_return_dict', side_effect=[{'A': 'a'}, {}]): with patch.object(solr, '_replication_request', return_value='A'): self.assertDictEqual(solr.set_replication_enabled('s'), {'A': 'a'}) with patch.object(solr, '_check_for_cores', return_value=True): with patch.dict(solr.__opts__, {'solr.cores': MagicMock(return_value='n')}): self.assertEqual(solr.set_replication_enabled ('s'), {}) self.assertEqual(solr.set_replication_enabled('s'), 'A') self.assertEqual(solr.set_replication_enabled(False), 'A')
def test_reload_core(self): ''' Test to load a new core from the same configuration as an existing registered core. ''' error = ['solr.reload_core can only be called by "multi-core" minions'] with patch.object(solr, '_check_for_cores', side_effect=[False, True, True, True]): with patch.object(solr, '_get_none_or_value', side_effect=[None, True]): with patch.object(solr, '_get_return_dict', return_value={'A': 'a'}): with patch.object(solr, '_format_url', return_value='A'): with patch.object(solr, '_http_request', return_value='A'): with patch.dict(solr.__opts__, {'solr.cores': MagicMock(return_value='n')}): self.assertIsNone(solr.reload_core()) self.assertDictEqual(solr.reload_core(), {'A': 'a', 'errors': error, 'success': False}) self.assertEqual(solr.reload_core(), 'A')
def test_grains(self): ''' test cache.grains runner ''' mock_minion = ['Larry'] mock_ret = {} self.assertEqual(cache.grains(minion=mock_minion), mock_ret) mock_data = 'grain stuff' mock_outputter = 'deprecated' class MockMaster(object): def __init__(self, *args, **kwargs): pass def get_minion_grains(self): return mock_data mock_ret = {'outputter': mock_outputter, 'data': mock_data} with patch.object(salt.utils.master, 'MasterPillarUtil', MockMaster): self.assertEqual(cache.grains(outputter=mock_outputter), mock_ret) mock_outputter = None with patch.object(salt.utils.master, 'MasterPillarUtil', MockMaster): self.assertEqual(cache.grains(outputter=mock_outputter), mock_data)
def test_single(self): ''' Test to execute single state function ''' ret = {'pkg_|-name=vim_|-name=vim_|-installed': list} mock = MagicMock(side_effect=["A", None, None, None, None]) with patch.object(state, '_check_queue', mock): self.assertEqual(state.single("pkg.installed", " name=vim"), "A") self.assertEqual(state.single("pk", "name=vim"), "Invalid function passed") with patch.dict(state.__opts__, {"test": "install"}): mock = MagicMock(return_value={"test": ""}) with patch.object(state, '_get_opts', mock): mock = MagicMock(return_value=True) with patch.object(salt.utils, 'test_mode', mock): self.assertRaises(SaltInvocationError, state.single, "pkg.installed", "name=vim", pillar="A") MockState.State.flag = True self.assertTrue(state.single("pkg.installed", "name=vim")) MockState.State.flag = False self.assertDictEqual(state.single("pkg.installed", "name=vim"), ret)
def test_latest(self): ''' Test to Make sure the repository is cloned to the given directory and is up to date ''' ret = {'changes': {}, 'comment': '', 'name': 'salt', 'result': True} mock = MagicMock(return_value=True) with patch.object(hg, '_fail', mock): self.assertTrue(hg.latest("salt")) mock = MagicMock(side_effect=[False, True, False, False, False, False]) with patch.object(os.path, 'isdir', mock): mock = MagicMock(return_value=True) with patch.object(hg, '_handle_existing', mock): self.assertTrue(hg.latest("salt", target="c:\\salt")) with patch.dict(hg.__opts__, {'test': True}): mock = MagicMock(return_value=True) with patch.object(hg, '_neutral_test', mock): self.assertTrue(hg.latest("salt", target="c:\\salt")) with patch.dict(hg.__opts__, {'test': False}): mock = MagicMock(return_value=True) with patch.object(hg, '_clone_repo', mock): self.assertDictEqual(hg.latest("salt", target="c:\\salt"), ret)
def test_get_bond(self): ''' Test to return the content of a bond script ''' with patch.object(os.path, 'join', return_value='A'): with patch.object(rh_ip, '_read_file', return_value='A'): self.assertEqual(rh_ip.get_bond('iface'), 'A')
def test_enabled(self): """ Test for Return True if the named service is enabled, false otherwise """ mock = MagicMock(return_value={'name': ['default']}) with patch.object(gentoo_service, 'get_enabled', mock): # service is enabled at any level self.assertTrue(gentoo_service.enabled('name')) # service is enabled at the requested runlevels self.assertTrue(gentoo_service.enabled('name', runlevels='default')) # service is enabled at a different runlevels self.assertFalse(gentoo_service.enabled('name', runlevels='boot')) mock = MagicMock(return_value={'name': ['boot', 'default']}) with patch.object(gentoo_service, 'get_enabled', mock): # service is enabled at any level self.assertTrue(gentoo_service.enabled('name')) # service is enabled at the requested runlevels self.assertTrue(gentoo_service.enabled('name', runlevels='default')) # service is enabled at all levels self.assertTrue(gentoo_service.enabled('name', runlevels=['boot', 'default'])) # service is enabled at a different runlevels self.assertFalse(gentoo_service.enabled('name', runlevels='some-other-level')) # service is enabled at a different runlevels self.assertFalse(gentoo_service.enabled('name', runlevels=['boot', 'some-other-level']))
def test_installed(self): ''' Test to install specified windows updates ''' ret = {'name': 'salt', 'changes': {}, 'result': False, 'comment': ''} mock = MagicMock(side_effect=[['Saltstack', False, 5], ['Saltstack', True, 5], ['Saltstack', True, 5], ['Saltstack', True, 5]]) with patch.object(win_update, '_search', mock): ret.update({'comment': 'Saltstack'}) self.assertDictEqual(win_update.installed('salt'), ret) mock = MagicMock(side_effect=[['dude', False, 5], ['dude', True, 5], ['dude', True, 5]]) with patch.object(win_update, '_download', mock): ret.update({'comment': 'Saltstackdude'}) self.assertDictEqual(win_update.installed('salt'), ret) mock = MagicMock(side_effect=[['@Me', False, 5], ['@Me', True, 5]]) with patch.object(win_update, '_install', mock): ret.update({'comment': 'Saltstackdude@Me'}) self.assertDictEqual(win_update.installed('salt'), ret) ret.update({'changes': True, 'result': True}) self.assertDictEqual(win_update.installed('salt'), ret)
def test_get_routes(self): ''' Test to return the contents of the interface routes script. ''' with patch.object(os.path, 'join', return_value='A'): with patch.object(rh_ip, '_read_file', return_value='A'): self.assertEqual(rh_ip.get_routes('iface'), 'A')
def test_core_status(self): ''' Test to get the status for a given core or all cores if no core is specified ''' error = ['solr.reload_core can only be called by "multi-core" minions'] with patch.object(solr, '_check_for_cores', side_effect=[False, True, True, True]): with patch.object(solr, '_get_none_or_value', side_effect=[None, True]): with patch.object(solr, '_get_return_dict', return_value={'A': 'a'}): with patch.object(solr, '_format_url', return_value='A'): with patch.object(solr, '_http_request', return_value='A'): with patch.dict(solr.__opts__, {'solr.cores': MagicMock(return_value='n')}): self.assertIsNone(solr.core_status()) self.assertDictEqual(solr.core_status(), {'A': 'a', 'errors': error, 'success': False}) self.assertEqual(solr.core_status(), 'A')
def test_verify_log(self): """ Test that verify_log works as expected """ message = "Insecure logging configuration detected! Sensitive data may be logged." mock_cheese = MagicMock() with patch.object(log, "warning", mock_cheese): verify_log({"log_level": "cheeseshop"}) mock_cheese.assert_called_once_with(message) mock_trace = MagicMock() with patch.object(log, "warning", mock_trace): verify_log({"log_level": "trace"}) mock_trace.assert_called_once_with(message) mock_none = MagicMock() with patch.object(log, "warning", mock_none): verify_log({}) mock_none.assert_called_once_with(message) mock_info = MagicMock() with patch.object(log, "warning", mock_info): verify_log({"log_level": "info"}) mock_info.assert_not_called()
def test_pack_sources(self): ''' Test to accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ''' with patch.object(yaml, 'safe_load', MagicMock(side_effect=yaml.parser.ParserError('f'))): with patch.dict(pkg_resource.__salt__, {'pkg.normalize_name': MagicMock()}): self.assertDictEqual(pkg_resource.pack_sources('sources'), {}) self.assertDictEqual(pkg_resource.pack_sources(['A', 'a']), {}) self.assertTrue(pkg_resource.pack_sources([{'A': 'a'}]))
def test_sls_id(self): ''' Test to call a single ID from the named module(s) and handle all requisites ''' mock = MagicMock(side_effect=["A", None, None, None]) with patch.object(state, '_check_queue', mock): self.assertEqual(state.sls_id("apache", "http"), "A") with patch.dict(state.__opts__, {"test": "A"}): mock = MagicMock(return_value={'test': True}) with patch.object(state, '_get_opts', mock): mock = MagicMock(return_value=True) with patch.object(salt.utils, 'test_mode', mock): MockState.State.flag = True MockState.HighState.flag = True self.assertEqual(state.sls_id("apache", "http"), 2) MockState.State.flag = False self.assertDictEqual(state.sls_id("ABC", "http"), {'': 'ABC'}) self.assertRaises(SaltInvocationError, state.sls_id, "DEF", "http")
def test_show_sls(self): ''' Test to display the state data from a specific sls ''' mock = MagicMock(side_effect=["A", None, None, None]) with patch.object(state, '_check_queue', mock): self.assertEqual(state.show_sls("foo"), "A") with patch.dict(state.__opts__, {"test": "A"}): mock = MagicMock(return_value={'test': True}) with patch.object(state, '_get_opts', mock): mock = MagicMock(return_value=True) with patch.object(salt.utils, 'test_mode', mock): self.assertRaises(SaltInvocationError, state.show_sls, "foo", pillar="A") MockState.State.flag = True self.assertEqual(state.show_sls("foo"), 2) MockState.State.flag = False self.assertListEqual(state.show_sls("foo"), ['a', 'b'])
def test_flush(self): ''' Test to flush current nftables state ''' ret = {'name': 'salt', 'changes': {}, 'result': None, 'comment': ''} mock = MagicMock(return_value=[]) with patch.object(nftables, '_STATE_INTERNAL_KEYWORDS', mock): mock = MagicMock(side_effect=[False, True, True, True]) with patch.dict(nftables.__salt__, {'nftables.check_table': mock}): ret.update({ 'comment': 'Failed to flush table in family' ' ipv4, table does not exist.', 'result': False }) self.assertDictEqual( nftables.flush('salt', table='', chain=''), ret) mock = MagicMock(side_effect=[False, True, True]) with patch.dict(nftables.__salt__, {'nftables.check_chain': mock}): ret.update({ 'comment': 'Failed to flush chain in table' ' in family ipv4, chain does not exist.' }) self.assertDictEqual( nftables.flush('salt', table='', chain=''), ret) mock = MagicMock(side_effect=[True, False]) with patch.dict(nftables.__salt__, {'nftables.flush': mock}): ret.update({ 'changes': { 'locale': 'salt' }, 'comment': 'Flush nftables rules in table' ' chain ipv4 family', 'result': True }) self.assertDictEqual( nftables.flush('salt', table='', chain=''), ret) ret.update({ 'changes': {}, 'comment': 'Failed to flush' ' nftables rules', 'result': False }) self.assertDictEqual( nftables.flush('salt', table='', chain=''), ret)
def test_rename_set(self): ''' Test for Delete ipset set. ''' self.assertEqual(ipset.rename_set(), 'Error: Set needs to be specified') self.assertEqual(ipset.rename_set('s'), 'Error: New name for set needs to be specified') with patch.object(ipset, '_find_set_type', return_value=False): self.assertEqual(ipset.rename_set('s', 'd'), 'Error: Set does not exist') with patch.object(ipset, '_find_set_type', return_value=True): self.assertEqual(ipset.rename_set('s', 'd'), 'Error: New Set already exists') with patch.object(ipset, '_find_set_type', side_effect=[True, False]): with patch.object(ipset, '_ipset_cmd', return_value='A'): mock = MagicMock(return_value=True) with patch.dict(ipset.__salt__, {'cmd.run': mock}): self.assertTrue(ipset.rename_set('set', 'new_set'))
def test_template(self): ''' Test of executing the information stored in a template file on the minion ''' mock = MagicMock(side_effect=[False, None, None]) with patch.object(state, '_check_queue', mock): self.assertFalse(state.template('/home/salt/salt.sls')) MockState.HighState.flag = True self.assertTrue(state.template('/home/salt/salt.sls')) MockState.HighState.flag = False self.assertTrue(state.template('/home/salt/salt.sls'))
def test_set_fstab(self): ''' Tests to verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. ''' mock = MagicMock(return_value=False) with patch.object(os.path, 'isfile', mock): self.assertRaises(CommandExecutionError, mount.set_fstab, 'A', 'B', 'C') mock = MagicMock(return_value=True) mock_read = MagicMock(side_effect=OSError) with patch.object(os.path, 'isfile', mock): with patch.object(salt.utils, 'fopen', mock_read): self.assertRaises(CommandExecutionError, mount.set_fstab, 'A', 'B', 'C') mock = MagicMock(return_value=True) with patch.object(os.path, 'isfile', mock): with patch('salt.utils.fopen', mock_open(read_data=MOCK_SHELL_FILE)): self.assertEqual(mount.set_fstab('A', 'B', 'C'), 'new')
def test_wait_success_absent_container(self): client = Mock() client.api_version = '1.21' dockerng_inspect_container = Mock(side_effect=CommandExecutionError) with patch.object(dockerng_mod, 'inspect_container', dockerng_inspect_container): with patch.dict(dockerng_mod.__context__, {'docker.client': client}): dockerng_mod._clear_context() result = dockerng_mod.wait('foo', ignore_already_stopped=True) self.assertEqual(result, { 'result': True, 'comment': "Container 'foo' absent" })
def test_make_pkgng_aware(self): ''' Test if it make jail ``jname`` pkgng aware. ''' ret1 = 'Could not create or find required directory /tmp/salt' ret2 = 'Looks like file /tmp/salt/salt-make.conf could not be created' ret3 = {'changes': 'Created /tmp/salt/salt-make.conf'} mock = MagicMock(return_value='/tmp/salt') mock_true = MagicMock(return_value=True) with patch.dict(poudriere.__salt__, { 'config.option': mock, 'file.write': mock_true }): with patch.object(os.path, 'isdir', MagicMock(return_value=False)): with patch.object(os, 'makedirs', mock_true): self.assertEqual(poudriere.make_pkgng_aware('salt'), ret1) with patch.object(os.path, 'isdir', mock_true): self.assertEqual(poudriere.make_pkgng_aware('salt'), ret2) with patch.object(os.path, 'isfile', mock_true): self.assertDictEqual(poudriere.make_pkgng_aware('salt'), ret3)
def test_list_upgrades(self): output = ''' arel (5.0.1.20140414130214 < 6.0.0) rails (4.1.9 < 4.2.0) rake (10.3.2 < 10.4.2) ''' mock = MagicMock(return_value=output) with patch.object(gem, '_gem', new=mock): self.assertEqual( { 'arel': '6.0.0', 'rails': '4.2.0', 'rake': '10.4.2' }, gem.list_upgrades())
def test_validate_input_min_docker_py(self): docker_mock = Mock() docker_mock.version_info = (1, 0, 0) dockerng_mod.docker = None with patch.dict(dockerng_mod.VALID_CREATE_OPTS['command'], {'path': 'Config:Cmd', 'image_path': 'Config:Cmd', 'min_docker_py': (999, 0, 0)}): with patch.object(dockerng_mod, 'docker', docker_mock): self.assertRaisesRegexp(SaltInvocationError, "The 'command' parameter requires at" " least docker-py 999.0.0.*$", dockerng_state._validate_input, {'command': 'echo boom'})
def test_context_extablished(self): mock_context = MagicMock(return_value=MagicMock()) mock_context.return_value.established = True mock_context.return_value.step = MagicMock(return_value='out_token') with patch.object(salt.utils.vmware.gssapi, 'InitContext', mock_context): mock_context.established = True mock_context.step = MagicMock(return_value=None) with self.assertRaises(excs.CommandExecutionError) as excinfo: salt.utils.vmware.get_gssapi_token('principal', 'host', 'domain') self.assertEqual(mock_context.step.called, 0) self.assertIn('Context established, but didn\'t receive token', excinfo.exception.strerror)
def test_init(self): ''' Test if it mount the named image via qemu-nbd and return the mounted roots ''' mock = MagicMock(return_value=True) with patch.dict(qemu_nbd.__salt__, {'cmd.run': mock}): self.assertEqual(qemu_nbd.init('/srv/image.qcow2'), '') with patch.object(os.path, 'isfile', mock): with patch.object(glob, 'glob', MagicMock(return_value=['/dev/nbd0'])): with patch.dict( qemu_nbd.__salt__, { 'cmd.run': mock, 'mount.mount': mock, 'cmd.retcode': MagicMock(side_effect=[1, 0]) }): self.assertDictEqual( qemu_nbd.init('/srv/image.qcow2'), { '{0}/nbd/nbd0/nbd0'.format(tempfile.gettempdir()): '/dev/nbd0' })
def test_keyspaces(self): ''' Test for Return existing keyspaces ''' mock_keyspaces = ['A', 'B', 'C', 'D'] class MockSystemManager(object): def list_keyspaces(self): return mock_keyspaces mock_sys_mgr = MagicMock(return_value=MockSystemManager()) with patch.object(cassandra, '_sys_mgr', mock_sys_mgr): self.assertEqual(cassandra.keyspaces(), mock_keyspaces)
def test_vfstab(self): ''' List the content of the vfstab ''' mock = MagicMock(return_value=False) with patch.object(os.path, 'isfile', mock): self.assertEqual(mount.vfstab(), {}) mock = MagicMock(return_value=True) with patch.dict(mount.__grains__, {'kernel': 'SunOS'}): with patch.object(os.path, 'isfile', mock): file_data = '\n'.join(['#', 'swap - /tmp tmpfs - yes size=2048m']) with patch('salt.utils.fopen', mock_open(read_data=file_data), create=True) as m: m.return_value.__iter__.return_value = file_data.splitlines() self.assertEqual(mount.fstab(), {'/tmp': {'device': 'swap', 'device_fsck': '-', 'fstype': 'tmpfs', 'mount_at_boot': 'yes', 'opts': ['size=2048m'], 'pass_fsck': '-'}})
def test_user_remove(self): ''' Tests to remove a cluster admin or a database user. ''' with patch.object(influx, 'user_exists', return_value=False): self.assertFalse( influx.user_remove(name='A', user='******', password='******', host='localhost', port=8000)) self.assertFalse( influx.user_remove(name='A', database='test', user='******', password='******', host='localhost', port=8000)) mock_inf_db_client = MagicMock(return_value=MockInfluxDBClient()) with patch.object(influx, '_client', mock_inf_db_client): with patch.object(influx, 'user_exists', return_value=True): self.assertTrue( influx.user_remove(name='A', user='******', password='******', host='localhost', port=8000)) self.assertTrue( influx.user_remove(name='A', database='test', user='******', password='******', host='localhost', port=8000))
def test_configfile(self): ''' Test to allows for inputting a yaml dictionary into a file for apache configuration files. ''' name = '/etc/distro/specific/apache.conf' config = 'VirtualHost: this: "*:80"' new_config = 'LiteralHost: that: "*:79"' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} with patch.object(salt.utils, 'fopen', mock_open(read_data=config)): mock_config = MagicMock(return_value=config) with patch.dict(apache.__salt__, {'apache.config': mock_config}): ret.update({'comment': 'Configuration is up to date.'}) self.assertDictEqual(apache.configfile(name, config), ret) with patch.object(salt.utils, 'fopen', mock_open(read_data=config)): mock_config = MagicMock(return_value=new_config) with patch.dict(apache.__salt__, {'apache.config': mock_config}): ret.update({'comment': 'Configuration will update.', 'changes': {'new': new_config, 'old': config}, 'result': None}) with patch.dict(apache.__opts__, {'test': True}): self.assertDictEqual(apache.configfile(name, new_config), ret) with patch.object(salt.utils, 'fopen', mock_open(read_data=config)): mock_config = MagicMock(return_value=new_config) with patch.dict(apache.__salt__, {'apache.config': mock_config}): ret.update({'comment': 'Successfully created configuration.', 'result': True}) with patch.dict(apache.__opts__, {'test': False}): self.assertDictEqual(apache.configfile(name, config), ret)
def test_status(self): ''' Test for Return the status for a service ''' launchctl_data = '''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>salt-minion</string> <key>LastExitStatus</key> <integer>0</integer> <key>LimitLoadToSessionType</key> <string>System</string> <key>OnDemand</key> <false/> <key>PID</key> <integer>71</integer> <key>ProgramArguments</key> <array> <string>/usr/local/bin/salt-minion</string> </array> <key>TimeOut</key> <integer>30</integer> </dict> </plist>''' with patch.object(launchctl, '_service_by_name', return_value={'plist': { 'Label': 'A' }}): if six.PY3: launchctl_data = salt.utils.to_bytes(launchctl_data) with patch.object(launchctl, '_get_launchctl_data', return_value=launchctl_data): self.assertTrue(launchctl.status('job_label'))
def test_update(self): ''' Test to add, replace, or update a DNS record. ''' mock_request = textwrap.dedent('''\ id 29380 opcode QUERY rcode NOERROR flags RD ;QUESTION name.zone. IN AAAA ;ANSWER ;AUTHORITY ;ADDITIONAL''') mock_rdtype = 28 # rdtype of AAAA record class MockRrset(object): def __init__(self): self.items = [{'address': 'localhost'}] self.ttl = 2 class MockAnswer(object): def __init__(self, *args, **kwargs): self.answer = [MockRrset()] def rcode(self): return 0 def mock_udp_query(*args, **kwargs): return MockAnswer with patch.object(dns.message, 'make_query', MagicMock(return_value=mock_request)): with patch.object(dns.query, 'udp', mock_udp_query()): with patch.object(dns.rdatatype, 'from_text', MagicMock(return_value=mock_rdtype)): with patch.object(ddns, '_get_keyring', return_value=None): with patch.object(ddns, '_config', return_value=None): self.assertTrue(ddns.update('zone', 'name', 1, 'AAAA', '::1'))
def test_install(self): ''' Test for Install composer dependencies for a directory. ''' mock = MagicMock(return_value=False) msg = "'composer.install' is not available. Couldn't find 'composer'." with patch.object(composer, '_valid_composer', mock): self.assertEqual(composer.install('dir'), msg) mock = MagicMock(return_value=True) msg = "'dir' is required for 'composer.install'" with patch.object(composer, '_valid_composer', mock): self.assertEqual(composer.install(None), msg) mock = MagicMock(return_value=True) with patch.object(composer, '_valid_composer', mock): mock = MagicMock(return_value={'retcode': 1, 'stderr': 'A'}) with patch.dict(composer.__salt__, {'cmd.run_all': mock}): self.assertRaises(CommandExecutionError, composer.install, 'd') mock = MagicMock(return_value=True) with patch.object(composer, '_valid_composer', mock): mock = MagicMock(return_value={'retcode': 0, 'stderr': 'A'}) with patch.dict(composer.__salt__, {'cmd.run_all': mock}): self.assertTrue( composer.install('dir', None, None, None, None, None, None, None, None, None, True)) mock = MagicMock(return_value=True) with patch.object(composer, '_valid_composer', mock): mock = MagicMock(return_value={ 'retcode': 0, 'stderr': 'A', 'stdout': 'B' }) with patch.dict(composer.__salt__, {'cmd.run_all': mock}): self.assertEqual(composer.install('dir'), 'B')
def test_list_vms(self): ''' Test parallels.list_vms ''' runas = 'macdev' # Validate a simple list mock_plain = MagicMock() with patch.object(parallels, 'prlctl', mock_plain): parallels.list_vms(runas=runas) mock_plain.assert_called_once_with('list', [], runas=runas) # Validate listing a single VM mock_name = MagicMock() with patch.object(parallels, 'prlctl', mock_name): parallels.list_vms(name='macvm', runas=runas) mock_name.assert_called_once_with('list', ['macvm'], runas=runas) # Validate listing templates mock_templ = MagicMock() with patch.object(parallels, 'prlctl', mock_templ): parallels.list_vms(template=True, runas=runas) mock_templ.assert_called_once_with('list', ['--template'], runas=runas) # Validate listing extra info mock_info = MagicMock() with patch.object(parallels, 'prlctl', mock_info): parallels.list_vms(info=True, runas=runas) mock_info.assert_called_once_with('list', ['--info'], runas=runas) # Validate listing with extra options mock_complex = MagicMock() with patch.object(parallels, 'prlctl', mock_complex): parallels.list_vms(args=' -o uuid,status', all=True, runas=runas) mock_complex.assert_called_once_with( 'list', ['-o', 'uuid,status', '--all'], runas=runas)
def test_get_saved_policy(self): ''' Test if it return the current policy for the specified table/chain ''' self.assertEqual( iptables.get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'), 'Error: Chain needs to be specified') with patch.object( iptables, '_parse_conf', MagicMock(return_value={'filter': { 'INPUT': { 'policy': True } }})): self.assertTrue( iptables.get_saved_policy(table='filter', chain='INPUT', conf_file=None, family='ipv4')) with patch.object( iptables, '_parse_conf', MagicMock( return_value={'filter': { 'INPUT': { 'policy1': True } }})): self.assertIsNone( iptables.get_saved_policy(table='filter', chain='INPUT', conf_file=None, family='ipv4'))
def test_pvdisplay(self): ''' Tests information about the physical volume(s) ''' mock = MagicMock(return_value={'retcode': 1}) with patch.dict(linux_lvm.__salt__, {'cmd.run_all': mock}): self.assertDictEqual(linux_lvm.pvdisplay(), {}) mock = MagicMock(return_value={ 'retcode': 0, 'stdout': 'A:B:C:D:E:F:G:H:I:J:K' }) with patch.dict(linux_lvm.__salt__, {'cmd.run_all': mock}): self.assertDictEqual( linux_lvm.pvdisplay(), { 'A': { 'Allocated Physical Extents': 'K', 'Current Logical Volumes Here': 'G', 'Free Physical Extents': 'J', 'Internal Physical Volume Number': 'D', 'Physical Extent Size (kB)': 'H', 'Physical Volume (not) Allocatable': 'F', 'Physical Volume Device': 'A', 'Physical Volume Size (kB)': 'C', 'Physical Volume Status': 'E', 'Total Physical Extents': 'I', 'Volume Group Name': 'B' } }) mockpath = MagicMock(return_value='Z') with patch.object(os.path, 'realpath', mockpath): self.assertDictEqual( linux_lvm.pvdisplay(real=True), { 'Z': { 'Allocated Physical Extents': 'K', 'Current Logical Volumes Here': 'G', 'Free Physical Extents': 'J', 'Internal Physical Volume Number': 'D', 'Physical Extent Size (kB)': 'H', 'Physical Volume (not) Allocatable': 'F', 'Physical Volume Device': 'A', 'Physical Volume Size (kB)': 'C', 'Physical Volume Status': 'E', 'Real Physical Volume Device': 'Z', 'Total Physical Extents': 'I', 'Volume Group Name': 'B' } })
def test_get_docker_with_container_id(self): ''' Test for Get all mine data for 'dockerng.ps' and run an aggregation. ''' ps_response = { 'localhost': { 'host': { 'interfaces': { 'docker0': { 'hwaddr': '88:99:00:00:99:99', 'inet': [{'address': '172.17.42.1', 'broadcast': None, 'label': 'docker0', 'netmask': '255.255.0.0'}], 'inet6': [{'address': 'ffff::eeee:aaaa:bbbb:8888', 'prefixlen': '64'}], 'up': True}, 'eth0': {'hwaddr': '88:99:00:99:99:99', 'inet': [{'address': '192.168.0.1', 'broadcast': '192.168.0.255', 'label': 'eth0', 'netmask': '255.255.255.0'}], 'inet6': [{'address': 'ffff::aaaa:aaaa:bbbb:8888', 'prefixlen': '64'}], 'up': True}, }}, 'abcdefhjhi1234567899': { # container Id 'Ports': [{'IP': '0.0.0.0', # we bind on every interfaces 'PrivatePort': 80, 'PublicPort': 80, 'Type': 'tcp'}], 'Image': 'image:latest', 'Info': {'Id': 'abcdefhjhi1234567899'}, }, }} with patch.object(mine, 'get', return_value=ps_response): self.assertEqual( mine.get_docker(with_container_id=True), { 'image:latest': { 'ipv4': { 80: [ ('172.17.42.1:80', 'abcdefhjhi1234567899'), ('192.168.0.1:80', 'abcdefhjhi1234567899'), ] } } })
def test_info(self): ''' Test the user information ''' self.assertEqual(useradd.info('username-that-doesnt-exist'), {}) mock = MagicMock(return_value=pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false'))) with patch.object(pwd, 'getpwnam', mock): self.assertEqual( useradd.info('username-that-doesnt-exist')['name'], '_TEST_GROUP')
def test_rename(self): ''' Test if the username for a named user changed ''' mock = MagicMock(return_value=False) with patch.object(useradd, 'info', mock): self.assertRaises(CommandExecutionError, useradd.rename, 'salt', 1) mock = MagicMock(return_value=True) with patch.object(useradd, 'info', mock): self.assertRaises(CommandExecutionError, useradd.rename, 'salt', 1) mock = MagicMock(return_value=None) with patch.dict(useradd.__salt__, {'cmd.run': mock}): mock = MagicMock(side_effect=[{'name': ''}, False, {'name': 'salt'}]) with patch.object(useradd, 'info', mock): self.assertTrue(useradd.rename('name', 'salt')) mock = MagicMock(return_value=None) with patch.dict(useradd.__salt__, {'cmd.run': mock}): mock = MagicMock(side_effect=[{'name': ''}, False, {'name': ''}]) with patch.object(useradd, 'info', mock): self.assertFalse(useradd.rename('salt', 'salt'))
def test_swapoff(self): ''' Deactivate a named swap mount ''' mock = MagicMock(return_value={}) with patch.dict(mount.__grains__, {'kernel': ''}): with patch.object(mount, 'swaps', mock): self.assertEqual(mount.swapoff('name'), None) mock = MagicMock(return_value={'name': 'name'}) with patch.dict(mount.__grains__, {'kernel': ''}): with patch.object(mount, 'swaps', mock): with patch.dict(mount.__grains__, {'os': 'test'}): mock = MagicMock(return_value=None) with patch.dict(mount.__salt__, {'cmd.run': mock}): self.assertFalse(mount.swapoff('name')) mock = MagicMock(side_effect=[{'name': 'name'}, {}]) with patch.dict(mount.__grains__, {'kernel': ''}): with patch.object(mount, 'swaps', mock): with patch.dict(mount.__grains__, {'os': 'test'}): mock = MagicMock(return_value=None) with patch.dict(mount.__salt__, {'cmd.run': mock}): self.assertTrue(mount.swapoff('name'))
def test_swapon(self): ''' Activate a swap disk ''' mock = MagicMock(return_value={'name': 'name'}) with patch.dict(mount.__grains__, {'kernel': ''}): with patch.object(mount, 'swaps', mock): self.assertEqual(mount.swapon('name'), {'stats': 'name', 'new': False}) mock = MagicMock(return_value={}) with patch.dict(mount.__grains__, {'kernel': ''}): with patch.object(mount, 'swaps', mock): mock = MagicMock(return_value=None) with patch.dict(mount.__salt__, {'cmd.run': mock}): self.assertEqual(mount.swapon('name', False), {}) mock = MagicMock(side_effect=[{}, {'name': 'name'}]) with patch.dict(mount.__grains__, {'kernel': ''}): with patch.object(mount, 'swaps', mock): mock = MagicMock(return_value=None) with patch.dict(mount.__salt__, {'cmd.run': mock}): self.assertEqual(mount.swapon('name'), {'stats': 'name', 'new': True})
def test_set_zone(self): ''' Test to unlinks, then symlinks /etc/localtime to the set timezone. ''' def zone_checking_and_unlinking(): ret = ('Zone does not exist: /usr/share/lib/zoneinfo/timezone') mock = MagicMock(side_effect=[False, True, True]) with patch.object(os.path, 'exists', mock): self.assertEqual(timezone.set_zone('timezone'), ret) with patch.object(os, 'unlink', return_value=None): with patch.dict( timezone.__salt__, {'file.sed': MagicMock(return_value=None)}): self.assertTrue(timezone.set_zone('timezone')) with patch.dict(timezone.__grains__, {'os_family': 'Solaris'}): with patch.object(salt.utils, 'which', return_value=False): zone_checking_and_unlinking() with patch.object(salt.utils, 'which', return_value=True): with patch.dict(timezone.__salt__, {'cmd.run': MagicMock(return_value='')}): zone_checking_and_unlinking()
def test_create_send_host_config(self, *args): ''' Check host_config object is passed to create_container. ''' __salt__ = { 'config.get': Mock(), 'mine.send': Mock(), } host_config = {'PublishAllPorts': True} client = Mock() client.api_version = '1.19' client.create_host_config.return_value = host_config client.create_container.return_value = {} get_client_mock = MagicMock(return_value=client) with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}): with patch.object(dockerng_mod, '_get_client', get_client_mock): with patch.object(dockerng_mod, 'get_client_args', self.client_args_mock): dockerng_mod.create('image', name='ctn', publish_all_ports=True) client.create_container.assert_called_once_with( host_config=host_config, image='image', name='ctn')