本文整理汇总了Python中salttesting.mock.patch函数的典型用法代码示例。如果您正苦于以下问题:Python patch函数的具体用法?Python patch怎么用?Python patch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了patch函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_push_success
def test_push_success(self):
'''
Test if push succeeds.
'''
path = '/srv/salt/saltines'
file_data = ''
mock_buf_size = len(file_data)
mock_id = 'You don\'t need to see his identification.'
ret = True
class MockChannel(object):
@staticmethod
def factory(__opts__):
return MockChannel()
def send(self, load):
return 'channel info'
class MockAuth(object):
def gen_token(self, salt):
return 'token info'
def mock_auth_factory():
return MockAuth()
with patch('salt.transport.Channel', MockChannel):
with patch('salt.modules.cp._auth', mock_auth_factory):
with patch('salt.utils.fopen', mock_open(read_data=file_data)):
with patch.dict(cp.__opts__,
{'file_buffer_size': mock_buf_size,
'id': mock_id}):
self.assertEqual(cp.push(path), ret)
示例2: test_existing_binary_in_windows_pathext
def test_existing_binary_in_windows_pathext(self, osaccess):
# We define the side_effect attribute on the mocked object in order to
# specify which calls return which values. First call to os.access
# returns X, the second Y, the third Z, etc...
osaccess.side_effect = [
# The first os.access should return False(the abspath one)
False,
# The second, iterating through $PATH, should also return False,
# still checking for Linux
False,
# We will now also return False 3 times so we get a .CMD back from
# the function, see PATHEXT below.
# Lastly return True, this is the windows check.
False, False, False,
True
]
# Let's patch os.environ to provide a custom PATH variable
with patch.dict(os.environ, {'PATH': '/bin',
'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;'
'.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY'}):
# Let's also patch is_windows to return True
with patch('salt.utils.is_windows', lambda: True):
with patch('os.path.isfile', lambda x: True):
self.assertEqual(
salt.utils.which('this-binary-exists-under-windows'),
# The returned path should return the .exe suffix
'/bin/this-binary-exists-under-windows.CMD'
)
示例3: test_manage_devices_just_cd
def test_manage_devices_just_cd(self):
'''
Tests that when adding IDE/CD drives, controller keys will be in the apparent
safe-range on ESX 5.5 but randomly generated on other versions (i.e. 6)
'''
device_map = {
'ide': {
'IDE 0': {},
'IDE 1': {}
},
'cd': {
'CD/DVD Drive 1': {'controller': 'IDE 0'}
}
}
with patch('salt.cloud.clouds.vmware.get_vcenter_version', return_value='VMware ESXi 5.5.0'):
specs = vmware._manage_devices(device_map, vm=None)['device_specs']
self.assertEqual(specs[0].device.key, vmware.SAFE_ESX_5_5_CONTROLLER_KEY_INDEX)
self.assertEqual(specs[1].device.key, vmware.SAFE_ESX_5_5_CONTROLLER_KEY_INDEX+1)
self.assertEqual(specs[2].device.controllerKey, vmware.SAFE_ESX_5_5_CONTROLLER_KEY_INDEX)
with patch('salt.cloud.clouds.vmware.get_vcenter_version', return_value='VMware ESXi 6'):
with patch('salt.cloud.clouds.vmware.randint', return_value=100) as first_key:
specs = vmware._manage_devices(device_map, vm=None)['device_specs']
self.assertEqual(specs[0].device.key, first_key.return_value)
self.assertEqual(specs[2].device.controllerKey, first_key.return_value)
示例4: test_remove
def test_remove(self):
'''
Tests to remove the specified kernel module
'''
mod = 'cheese'
err_msg = 'Cannot find module: it has been eaten'
mock_persist = MagicMock(return_value=set([mod]))
mock_lsmod = MagicMock(return_value=[{'size': 100,
'module': None,
'depcount': 10,
'deps': None}])
mock_run_all_0 = MagicMock(return_value={'retcode': 0})
mock_run_all_1 = MagicMock(return_value={'retcode': 1,
'stderr': err_msg})
with patch('salt.modules.kmod._remove_persistent_module', mock_persist):
with patch('salt.modules.kmod.lsmod', mock_lsmod):
with patch.dict(kmod.__salt__, {'cmd.run_all': mock_run_all_0}):
self.assertEqual([mod], kmod.remove(mod, True))
self.assertEqual([], kmod.remove(mod))
with patch.dict(kmod.__salt__, {'cmd.run_all': mock_run_all_1}):
self.assertEqual('Error removing module {0}: {1}'.format(mod, err_msg),
kmod.remove(mod, True))
示例5: test_delete_object
def test_delete_object(self):
'''
Deleting an object from the store.
:return:
'''
with patch("gzip.open", MagicMock()):
with patch("csv.reader", MagicMock(return_value=iter([[], ['foo:int', 'bar:str', 'spam:float'],
['123', 'test', '0.123'],
['234', 'another', '0.456']]))):
class InterceptedCsvDB(CsvDB):
def __init__(self, path):
CsvDB.__init__(self, path)
self._remained = list()
def store(self, obj, distinct=False):
self._remained.append(obj)
csvdb = InterceptedCsvDB('/foobar')
csvdb.open()
csvdb.create_table_from_object = MagicMock()
csvdb.flush = MagicMock()
assert csvdb.delete(FoobarEntity, eq={'foo': 123}) is True
assert len(csvdb._remained) == 1
assert csvdb._remained[0].foo == 234
assert csvdb._remained[0].bar == 'another'
assert csvdb._remained[0].spam == 0.456
示例6: test_upgrade_failure
def test_upgrade_failure(self):
'''
Test system upgrade failure.
:return:
'''
zypper_out = '''
Loading repository data...
Reading installed packages...
Computing distribution upgrade...
Use 'zypper repos' to get the list of defined repositories.
Repository 'DUMMY' not found by its alias, number, or URI.
'''
class FailingZypperDummy(object):
def __init__(self):
self.stdout = zypper_out
self.stderr = ""
self.pid = 1234
self.exit_code = 555
self.noraise = MagicMock()
self.SUCCESS_EXIT_CODES = [0]
def __call__(self, *args, **kwargs):
return self
with patch('salt.modules.zypper.__zypper__', FailingZypperDummy()) as zypper_mock:
zypper_mock.noraise.call = MagicMock()
with patch('salt.modules.zypper.list_pkgs', MagicMock(side_effect=[{"vim": "1.1"}, {"vim": "1.1"}])):
with self.assertRaises(CommandExecutionError) as cmd_exc:
ret = zypper.upgrade(dist_upgrade=True, fromrepo=["DUMMY"])
self.assertEqual(cmd_exc.exception.info['changes'], {})
self.assertEqual(cmd_exc.exception.info['result']['stdout'], zypper_out)
zypper_mock.noraise.call.assert_called_with('dist-upgrade', '--auto-agree-with-licenses', '--from', 'DUMMY')
示例7: test_cluster_found
def test_cluster_found(self):
with patch('salt.utils.vmware.get_managed_object_name',
MagicMock(return_value='fake_dc')):
with patch('salt.utils.vmware.get_mors_with_properties',
MagicMock(return_value=self.mock_entries)):
res = vmware.get_cluster(self.mock_dc, 'fake_cluster2')
self.assertEqual(res, self.mock_cluster2)
示例8: test_pkg
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"))
示例9: test_sdecode
def test_sdecode(self):
b = '\xe7\xb9\x81\xe4\xbd\x93' if six.PY2 else bytes((0xe7, 0xb9, 0x81, 0xe4, 0xbd, 0x93))
u = u'\u7e41\u4f53'
with patch('salt.utils.locales.get_encodings', return_value=['ascii']):
self.assertEqual(locales.sdecode(b), b) # no decode
with patch('salt.utils.locales.get_encodings', return_value=['utf-8']):
self.assertEqual(locales.sdecode(b), u)
示例10: test_freebsd_remotes_on
def test_freebsd_remotes_on(self):
with patch('salt.utils.is_sunos', lambda: False):
with patch('salt.utils.is_freebsd', lambda: True):
with patch('subprocess.check_output',
return_value=FREEBSD_SOCKSTAT):
remotes = network._freebsd_remotes_on('4506', 'remote')
self.assertEqual(remotes, set(['127.0.0.1']))
示例11: test_master_daemon_hash_type_verified
def test_master_daemon_hash_type_verified(self):
'''
Verify if Master is verifying hash_type config option.
:return:
'''
def _create_master():
'''
Create master instance
:return:
'''
master = daemons.Master()
master.config = {'user': 'dummy', 'hash_type': alg}
for attr in ['master', 'start_log_info', 'prepare']:
setattr(master, attr, MagicMock())
return master
_logger = LoggerMock()
with patch('salt.cli.daemons.check_user', MagicMock(return_value=True)):
with patch('salt.cli.daemons.log', _logger):
for alg in ['md5', 'sha1']:
_create_master().start()
self.assertTrue(_logger.messages)
self.assertTrue(_logger.has_message('Do not use {alg}'.format(alg=alg),
log_type='warning'))
_logger.reset()
for alg in ['sha224', 'sha256', 'sha384', 'sha512']:
_create_master().start()
self.assertTrue(_logger.messages)
self.assertFalse(_logger.has_message('Do not use '))
示例12: test_proxy_minion_daemon_hash_type_verified
def test_proxy_minion_daemon_hash_type_verified(self):
'''
Verify if ProxyMinion is verifying hash_type config option.
:return:
'''
def _create_proxy_minion():
'''
Create proxy minion instance
:return:
'''
obj = daemons.ProxyMinion()
obj.config = {'user': 'dummy', 'hash_type': alg}
for attr in ['minion', 'start_log_info', 'prepare', 'shutdown', 'tune_in']:
setattr(obj, attr, MagicMock())
obj.minion.restart = False
return obj
_logger = LoggerMock()
with patch('salt.cli.daemons.check_user', MagicMock(return_value=True)):
with patch('salt.cli.daemons.log', _logger):
for alg in ['md5', 'sha1']:
_create_proxy_minion().start()
self.assertTrue(_logger.messages)
self.assertTrue(_logger.has_message('Do not use {alg}'.format(alg=alg),
log_type='warning'))
_logger.reset()
for alg in ['sha224', 'sha256', 'sha384', 'sha512']:
_create_proxy_minion().start()
self.assertTrue(_logger.messages)
self.assertFalse(_logger.has_message('Do not use '))
示例13: test_wait_for_task_call
def test_wait_for_task_call(self):
mock_wait_for_task = MagicMock()
with patch('salt.utils.vmware.get_managed_object_name',
MagicMock(return_value='fake_cluster')):
with patch('salt.utils.vmware.wait_for_task', mock_wait_for_task):
vmware.update_cluster(self.mock_cluster,
self.mock_cluster_spec)
mock_wait_for_task.assert_called_once_with(
self.mock_task, 'fake_cluster', 'ClusterUpdateTask')
示例14: test_cluster_not_found
def test_cluster_not_found(self):
with patch('salt.utils.vmware.get_managed_object_name',
MagicMock(return_value='fake_dc')):
with patch('salt.utils.vmware.get_mors_with_properties',
MagicMock(return_value=self.mock_entries)):
with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
vmware.get_cluster(self.mock_dc, 'fake_cluster')
self.assertEqual(excinfo.exception.strerror,
'Cluster \'fake_cluster\' was not found in '
'datacenter \'fake_dc\'')
示例15: test_mod_list
def test_mod_list(self):
"""
Tests return a list of the loaded module names
"""
with patch("salt.modules.kmod._get_modules_conf", MagicMock(return_value="/etc/modules")):
with patch("salt.modules.kmod._strip_module_name", MagicMock(return_value="lp")):
self.assertListEqual(["lp"], kmod.mod_list(True))
mock_ret = [{"size": 100, "module": None, "depcount": 10, "deps": None}]
with patch("salt.modules.kmod.lsmod", MagicMock(return_value=mock_ret)):
self.assertListEqual([None], kmod.mod_list(False))