• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python mock.patch函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中salttesting.mock.patch函数的典型用法代码示例。如果您正苦于以下问题:Python patch函数的具体用法?Python patch怎么用?Python patch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了patch函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:DaveQB,项目名称:salt,代码行数:32,代码来源:cp_test.py


示例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'
                 )
开发者ID:wikimedia,项目名称:operations-debs-salt,代码行数:28,代码来源:which_test.py


示例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)
开发者ID:bryson,项目名称:salt,代码行数:27,代码来源:vmware_test.py


示例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))
开发者ID:HowardMei,项目名称:saltstack,代码行数:25,代码来源:kmod_test.py


示例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
开发者ID:bryson,项目名称:salt,代码行数:28,代码来源:inspect_fsdb_test.py


示例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')
开发者ID:bryson,项目名称:salt,代码行数:34,代码来源:zypper_test.py


示例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)
开发者ID:bryson,项目名称:salt,代码行数:7,代码来源:cluster_test.py


示例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"))
开发者ID:DaveQB,项目名称:salt,代码行数:29,代码来源:state_test.py


示例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)
开发者ID:DaveQB,项目名称:salt,代码行数:7,代码来源:locales_test.py


示例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']))
开发者ID:dmyerscough,项目名称:salt,代码行数:7,代码来源:network.py


示例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 '))
开发者ID:bryson,项目名称:salt,代码行数:33,代码来源:daemons_test.py


示例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 '))
开发者ID:bryson,项目名称:salt,代码行数:35,代码来源:daemons_test.py


示例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')
开发者ID:bryson,项目名称:salt,代码行数:9,代码来源:cluster_test.py


示例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\'')
开发者ID:bryson,项目名称:salt,代码行数:10,代码来源:cluster_test.py


示例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))
开发者ID:DaveQB,项目名称:salt,代码行数:11,代码来源:kmod_test.py


示例16: test_defined_container_ref

 def test_defined_container_ref(self):
     container_ref_mock = MagicMock()
     with patch('salt.utils.vmware.get_root_folder',
                self.get_root_folder_mock):
         with patch(self.obj_spec_method_name, self.obj_type_mock):
             salt.utils.vmware.get_content(
                 self.si_mock, self.obj_type_mock,
                 container_ref=container_ref_mock)
     self.assertEqual(self.get_root_folder_mock.call_count, 0)
     self.create_container_view_mock.assert_called_once_with(
         container_ref_mock, [self.obj_type_mock], True)
开发者ID:bryson,项目名称:salt,代码行数:11,代码来源:common_test.py


示例17: test__get_gpg_exec

    def test__get_gpg_exec(self):
        '''
        test _get_gpg_exec
        '''
        gpg_exec = '/bin/gpg'

        with patch('salt.utils.which', MagicMock(return_value=gpg_exec)):
            self.assertEqual(gpg._get_gpg_exec(), gpg_exec)

        with patch('salt.utils.which', MagicMock(return_value=False)):
            self.assertRaises(SaltRenderError, gpg._get_gpg_exec)
开发者ID:DaveQB,项目名称:salt,代码行数:11,代码来源:gpg_test.py


示例18: test_gen_keys

 def test_gen_keys(self):
     with patch('salt.utils.fopen', mock_open()):
         open_priv_wb = call('/keydir/keyname.pem', 'wb+')
         open_pub_wb = call('/keydir/keyname.pub', 'wb+')
         with patch('os.path.isfile', return_value=True):
             self.assertEqual(crypt.gen_keys('/keydir', 'keyname', 2048), '/keydir/keyname.pem')
             self.assertNotIn(open_priv_wb, salt.utils.fopen.mock_calls)
             self.assertNotIn(open_pub_wb, salt.utils.fopen.mock_calls)
         with patch('os.path.isfile', return_value=False):
             with patch('salt.utils.fopen', mock_open()):
                 crypt.gen_keys('/keydir', 'keyname', 2048)
                 salt.utils.fopen.assert_has_calls([open_priv_wb, open_pub_wb], any_order=True)
开发者ID:DaveQB,项目名称:salt,代码行数:12,代码来源:crypt_test.py


示例19: test_get_service_instance_from_managed_object

    def test_get_service_instance_from_managed_object(self):
        mock_dc_name = MagicMock()
        mock_get_service_instance_from_managed_object = MagicMock()
        with patch('salt.utils.vmware.get_managed_object_name',
                   MagicMock(return_value=mock_dc_name)):
            with patch(
                'salt.utils.vmware.get_service_instance_from_managed_object',
                mock_get_service_instance_from_managed_object):

                vmware.get_cluster(self.mock_dc, 'fake_cluster')
        mock_get_service_instance_from_managed_object.assert_called_once_with(
            self.mock_dc, name=mock_dc_name)
开发者ID:bryson,项目名称:salt,代码行数:12,代码来源:cluster_test.py


示例20: _run_suse_os_grains_tests

    def _run_suse_os_grains_tests(self, os_release_map):
        path_isfile_mock = MagicMock(side_effect=lambda x: x in os_release_map['files'])
        empty_mock = MagicMock(return_value={})
        osarch_mock = MagicMock(return_value="amd64")
        os_release_mock = MagicMock(return_value=os_release_map.get('os_release_file'))

        orig_import = __import__
        if six.PY2:
            built_in = '__builtin__'
        else:
            built_in = 'builtins'

        def _import_mock(name, *args):
            if name == 'lsb_release':
                raise ImportError('No module named lsb_release')
            return orig_import(name, *args)

        # Skip the first if statement
        with patch.object(salt.utils, 'is_proxy',
                          MagicMock(return_value=False)):
            # Skip the selinux/systemd stuff (not pertinent)
            with patch.object(core, '_linux_bin_exists',
                              MagicMock(return_value=False)):
                # Skip the init grain compilation (not pertinent)
                with patch.object(os.path, 'exists', path_isfile_mock):
                    # Ensure that lsb_release fails to import
                    with patch('{0}.__import__'.format(built_in),
                               side_effect=_import_mock):
                        # Skip all the /etc/*-release stuff (not pertinent)
                        with patch.object(os.path, 'isfile', path_isfile_mock):
                            with patch.object(core, '_parse_os_release', os_release_mock):
                                # Mock platform.linux_distribution to give us the
                                # OS name that we want.
                                distro_mock = MagicMock(
                                    return_value=('SUSE test', 'version', 'arch')
                                )
                                with patch("salt.utils.fopen", mock_open()) as suse_release_file:
                                    suse_release_file.return_value.__iter__.return_value = os_release_map.get('suse_release_file', '').splitlines()
                                    with patch.object(platform, 'linux_distribution', distro_mock):
                                        with patch.object(core, '_linux_gpu_data', empty_mock):
                                            with patch.object(core, '_linux_cpudata', empty_mock):
                                                with patch.object(core, '_virtual', empty_mock):
                                                    # Mock the osarch
                                                    with patch.dict(core.__salt__, {'cmd.run': osarch_mock}):
                                                        os_grains = core.os_data()

        self.assertEqual(os_grains.get('os'), 'SUSE')
        self.assertEqual(os_grains.get('os_family'), 'Suse')
        self.assertEqual(os_grains.get('osfullname'), os_release_map['osfullname'])
        self.assertEqual(os_grains.get('oscodename'), os_release_map['oscodename'])
        self.assertEqual(os_grains.get('osrelease'), os_release_map['osrelease'])
        self.assertListEqual(list(os_grains.get('osrelease_info')), os_release_map['osrelease_info'])
        self.assertEqual(os_grains.get('osmajorrelease'), os_release_map['osmajorrelease'])
开发者ID:bryson,项目名称:salt,代码行数:53,代码来源:core_test.py



注:本文中的salttesting.mock.patch函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mock.MagicMock类代码示例发布时间:2022-05-27
下一篇:
Python mock.mock_open函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap