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

Python mock.MagicMock类代码示例

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

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



在下文中一共展示了MagicMock类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_install_cached_requirements_used

 def test_install_cached_requirements_used(self, get_cached_requirements):
     get_cached_requirements.return_value = "my_cached_reqs"
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
         pip.install(requirements="salt://requirements.txt")
         expected_cmd = "pip install --requirement='my_cached_reqs'"
         mock.assert_called_once_with(expected_cmd, saltenv="base", runas=None, cwd=None)
开发者ID:AccelerationNet,项目名称:salt,代码行数:7,代码来源:pip_test.py


示例2: test_check_mine_cache_is_refreshed_on_container_change_event

    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``
        '''

        for command_name, args in (('create', ()),
                                   ('rm_', ()),
                                   ('kill', ()),
                                   ('pause', ()),
                                   ('signal_', ('KILL',)),
                                   ('start', ()),
                                   ('stop', ()),
                                   ('unpause', ()),
                                   ('_run', ('command',)),
                                   ('_script', ('command',)),
                                   ):
            mine_send = Mock()
            command = getattr(dockerng_mod, command_name)
            docker_client = MagicMock()
            docker_client.api_version = '1.12'
            with patch.dict(dockerng_mod.__salt__,
                            {'mine.send': mine_send,
                             'container_resource.run': MagicMock(),
                             'cp.cache_file': MagicMock(return_value=False)}):
                with patch.dict(dockerng_mod.__context__,
                                {'docker.client': docker_client}):
                    command('container', *args)
            mine_send.assert_called_with('dockerng.ps', verbose=True, all=True,
                                         host=True)
开发者ID:bryson,项目名称:salt,代码行数:30,代码来源:dockerng_test.py


示例3: test__rvm

 def test__rvm(self):
     mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
     with patch.dict(rvm.__salt__, {'cmd.run_all': mock}):
         rvm._rvm('install', '1.9.3')
         mock.assert_called_once_with(
             '/usr/local/rvm/bin/rvm install 1.9.3', runas=None
         )
开发者ID:1mentat,项目名称:salt,代码行数:7,代码来源:rvm_test.py


示例4: test_set_proxy_windows

    def test_set_proxy_windows(self):
        '''
            Test to make sure we can set the proxy settings on Windows
        '''
        proxy.__grains__['os'] = 'Windows'
        expected = {
            'changes': {},
            'comment': 'Proxy settings updated correctly',
            'name': '192.168.0.1',
            'result': True
        }

        set_proxy_mock = MagicMock(return_value=True)
        patches = {
            'proxy.get_proxy_win': MagicMock(return_value={}),
            'proxy.get_proxy_bypass': MagicMock(return_value=[]),
            'proxy.set_proxy_win': set_proxy_mock,
        }

        with patch.dict(proxy.__salt__, patches):
            out = proxy.managed('192.168.0.1', '3128', user='frank', password='passw0rd',
                                bypass_domains=['salt.com', 'test.com'])

            set_proxy_mock.assert_called_once_with('192.168.0.1', '3128', ['http', 'https', 'ftp'],
                                                   ['salt.com', 'test.com'])
            self.assertEqual(out, expected)
开发者ID:HowardMei,项目名称:saltstack,代码行数:26,代码来源:proxy_test.py


示例5: test_list_command_with_prefix

 def test_list_command_with_prefix(self):
     eggs = [
         'M2Crypto==0.21.1',
         '-e [email protected]:s0undt3ch/[email protected]#egg=SaltTesting-dev',
         'bbfreeze==1.1.0',
         'bbfreeze-loader==1.1.0',
         'pycrypto==2.6'
     ]
     mock = MagicMock(
         return_value={
             'retcode': 0,
             'stdout': '\n'.join(eggs)
         }
     )
     with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
         ret = pip.list_(prefix='bb')
         mock.assert_called_with(
             'pip freeze',
             runas=None,
             cwd=None,
             python_shell=False,
         )
         self.assertEqual(
             ret, {
                 'bbfreeze-loader': '1.1.0',
                 'bbfreeze': '1.1.0',
             }
         )
开发者ID:wikimedia,项目名称:operations-debs-salt,代码行数:28,代码来源:pip_test.py


示例6: test_uninstall_log_argument_in_resulting_command

    def test_uninstall_log_argument_in_resulting_command(self, mock_path):
        pkg = 'pep8'
        log_path = '/tmp/pip-install.log'
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.uninstall(pkg, log=log_path)
            mock.assert_called_once_with(
                ['pip', 'uninstall', '-y', '--log', log_path, pkg],
                saltenv='base',
                runas=None,
                cwd=None,
                use_vt=False,
                python_shell=False,
            )

        # Let's fake a non-writable log file
        mock_path.exists.side_effect = IOError('Fooo!')
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                IOError,
                pip.uninstall,
                pkg,
                log=log_path
            )
开发者ID:mahak,项目名称:salt,代码行数:25,代码来源:pip_test.py


示例7: test_get_managed_object_name

 def test_get_managed_object_name(self):
     mock_get_managed_object_name = MagicMock()
     with patch('salt.utils.vmware.get_managed_object_name',
                mock_get_managed_object_name):
         vmware.create_cluster(self.mock_dc, 'fake_cluster',
                               self.mock_cluster_spec)
     mock_get_managed_object_name.assert_called_once_with(self.mock_dc)
开发者ID:bryson,项目名称:salt,代码行数:7,代码来源:cluster_test.py


示例8: test_uwsgi_stats

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


示例9: test_delete_volume

    def test_delete_volume(self):
        '''
        Test if it deletes a gluster volume.
        '''
        mock_info = MagicMock(return_value={'Newvolume1': {'status': '1'}})
        with patch.object(glusterfs, 'info', mock_info):
            # volume doesn't exist
            self.assertFalse(glusterfs.delete_volume('Newvolume3'))

            mock_stop_volume = MagicMock(return_value=True)
            mock_run = MagicMock(return_value=xml_command_success)
            with patch.dict(glusterfs.__salt__, {'cmd.run': mock_run}):
                with patch.object(glusterfs, 'stop_volume', mock_stop_volume):
                    # volume exists, should not be stopped, and is started
                    self.assertFalse(glusterfs.delete_volume('Newvolume1',
                                                             False))
                    self.assertFalse(mock_run.called)
                    self.assertFalse(mock_stop_volume.called)

                    # volume exists, should be stopped, and is started
                    self.assertTrue(glusterfs.delete_volume('Newvolume1'))
                    self.assertTrue(mock_run.called)
                    self.assertTrue(mock_stop_volume.called)

        # volume exists and isn't started
        mock_info = MagicMock(return_value={'Newvolume1': {'status': '2'}})
        with patch.object(glusterfs, 'info', mock_info):
            mock_run = MagicMock(return_value=xml_command_success)
            with patch.dict(glusterfs.__salt__, {'cmd.run': mock_run}):
                self.assertTrue(glusterfs.delete_volume('Newvolume1'))
                mock_run.return_value = xml_command_fail
                self.assertFalse(glusterfs.delete_volume('Newvolume1'))
开发者ID:bryson,项目名称:salt,代码行数:32,代码来源:glusterfs_test.py


示例10: test_list_pkgs

    def test_list_pkgs(self):
        '''
        Test for listing installed packages.
        '''
        def _add_data(data, key, value):
            data[key] = value

        pkg_info_out = [
            'png-1.6.23',
            'vim-7.4.1467p1-gtk2',  # vim--gtk2
            'ruby-2.3.1p1'  # ruby%2.3
        ]
        run_stdout_mock = MagicMock(return_value='\n'.join(pkg_info_out))
        patches = {
            'cmd.run_stdout': run_stdout_mock,
            'pkg_resource.add_pkg': _add_data,
            'pkg_resource.sort_pkglist': MagicMock(),
            'pkg_resource.stringify': MagicMock(),
        }
        with patch.dict(openbsdpkg.__salt__, patches):
            pkgs = openbsdpkg.list_pkgs()
            self.assertDictEqual(pkgs, {
                'png': '1.6.23',
                'vim--gtk2': '7.4.1467p1',
                'ruby': '2.3.1p1'})
        run_stdout_mock.assert_called_once_with('pkg_info -q -a',
                                                output_loglevel='trace')
开发者ID:bryson,项目名称:salt,代码行数:27,代码来源:openbsdpkg_test.py


示例11: test_symlinks_argument

 def test_symlinks_argument(self):
     # We test for pyvenv only because with virtualenv this is un
     # unsupported option.
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(virtualenv_mod.__salt__, {"cmd.run_all": mock}):
         virtualenv_mod.create("/tmp/foo", venv_bin="pyvenv", symlinks=True)
         mock.assert_called_once_with(["pyvenv", "--symlinks", "/tmp/foo"], runas=None, python_shell=False)
开发者ID:bryson,项目名称:salt,代码行数:7,代码来源:virtualenv_test.py


示例12: test_list_command

    def test_list_command(self):
        eggs = [
            "M2Crypto==0.21.1",
            "-e [email protected]:s0undt3ch/[email protected]#egg=SaltTesting-dev",
            "bbfreeze==1.1.0",
            "bbfreeze-loader==1.1.0",
            "pycrypto==2.6",
        ]
        mock = MagicMock(
            side_effect=[{"retcode": 0, "stdout": "pip MOCKED_VERSION"}, {"retcode": 0, "stdout": "\n".join(eggs)}]
        )
        with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
            ret = pip.list_()
            mock.assert_called_with("pip freeze", runas=None, cwd=None)
            self.assertEqual(
                ret,
                {
                    "SaltTesting-dev": "[email protected]:s0undt3ch/[email protected]",
                    "M2Crypto": "0.21.1",
                    "bbfreeze-loader": "1.1.0",
                    "bbfreeze": "1.1.0",
                    "pip": "MOCKED_VERSION",
                    "pycrypto": "2.6",
                },
            )

        # Non zero returncode raises exception?
        mock = MagicMock(return_value={"retcode": 1, "stderr": "CABOOOOMMM!"})
        with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
            self.assertRaises(CommandExecutionError, pip.list_)
开发者ID:AccelerationNet,项目名称:salt,代码行数:30,代码来源:pip_test.py


示例13: test_install_download_cache_argument_in_resulting_command

 def test_install_download_cache_argument_in_resulting_command(self):
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
         pip.install("pep8", download_cache="/tmp/foo")
         mock.assert_called_once_with(
             "pip install --download-cache=/tmp/foo 'pep8'", saltenv="base", runas=None, cwd=None
         )
开发者ID:AccelerationNet,项目名称:salt,代码行数:7,代码来源:pip_test.py


示例14: test_install_extra_index_url_argument_in_resulting_command

 def test_install_extra_index_url_argument_in_resulting_command(self):
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
         pip.install("pep8", extra_index_url="http://foo.tld")
         mock.assert_called_once_with(
             "pip install --extra-index-url='http://foo.tld' 'pep8'", saltenv="base", runas=None, cwd=None
         )
开发者ID:AccelerationNet,项目名称:salt,代码行数:7,代码来源:pip_test.py


示例15: run_contents_pillar

    def run_contents_pillar(self, pillar_value, expected):
        def returner(contents, *args, **kwargs):
            returner.returned = (contents, args, kwargs)
        returner.returned = None

        filestate.__salt__ = {
            'file.manage_file': returner
        }

        path = '/tmp/foo'
        pillar_path = 'foo:bar'

        # the values don't matter here
        filestate.__salt__['config.manage_mode'] = MagicMock()
        filestate.__salt__['file.source_list'] = MagicMock(return_value=[None, None])
        filestate.__salt__['file.get_managed'] = MagicMock(return_value=[None, None, None])

        # pillar.get should return the pillar_value
        pillar_mock = MagicMock(return_value=pillar_value)
        filestate.__salt__['pillar.get'] = pillar_mock

        ret = filestate.managed(path, contents_pillar=pillar_path)

        # make sure the pillar_mock is called with the given path
        pillar_mock.assert_called_once_with(pillar_path)

        # make sure no errors are returned
        self.assertEquals(None, ret)

        # make sure the value is correct
        self.assertEquals(expected, returner.returned[1][-1])
开发者ID:jslatts,项目名称:salt,代码行数:31,代码来源:file_test.py


示例16: test_add_volume_bricks

    def test_add_volume_bricks(self):
        '''
        Test if it add brick(s) to an existing volume
        '''
        mock_info = MagicMock(return_value={
            'Newvolume1': {
                'status': '1',
                'bricks': {
                    'brick1': {'path': 'host:/path1'},
                    'brick2': {'path': 'host:/path2'}
                }
            }
        })
        with patch.object(glusterfs, 'info', mock_info):
            mock_run = MagicMock(return_value=xml_command_success)
            with patch.dict(glusterfs.__salt__, {'cmd.run': mock_run}):
                # Volume does not exist
                self.assertFalse(glusterfs.add_volume_bricks('nonExisting',
                                                             ['bricks']))
                # Brick already exists
                self.assertTrue(glusterfs.add_volume_bricks('Newvolume1',
                                                       ['host:/path2']))
                # Already existing brick as a string
                self.assertTrue(glusterfs.add_volume_bricks('Newvolume1',
                                                            'host:/path2'))
                self.assertFalse(mock_run.called)
                # A new brick:
                self.assertTrue(glusterfs.add_volume_bricks('Newvolume1',
                                                            ['host:/new1']))
                self.assertTrue(mock_run.called)

                # Gluster call fails
                mock_run.return_value = xml_command_fail
                self.assertFalse(glusterfs.add_volume_bricks('Newvolume1',
                                                             ['new:/path']))
开发者ID:bryson,项目名称:salt,代码行数:35,代码来源:glusterfs_test.py


示例17: test_wipe

 def test_wipe(self):
     mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
     with patch.dict(blockdev.__salt__, {'cmd.run_all': mock}):
         blockdev.wipe('/dev/sda')
         mock.assert_called_once_with(
             'wipefs /dev/sda'
         )
开发者ID:AccelerationNet,项目名称:salt,代码行数:7,代码来源:blockdev_test.py


示例18: test_installed_enabled

    def test_installed_enabled(self):
        '''
            Test enabling an already enabled bundle ID
        '''
        expected = {
            'changes': {},
            'comment': 'Already in the correct state',
            'name': 'com.apple.Chess',
            'result': True
        }

        installed_mock = MagicMock(return_value=True)
        install_mock = MagicMock()
        enabled_mock = MagicMock(return_value=True)
        enable_mock = MagicMock()

        with patch.dict(assistive.__salt__, {'assistive.installed': installed_mock,
                                             'assistive.install': install_mock,
                                             'assistive.enabled': enabled_mock,
                                             'assistive.enable': enable_mock}):
            out = assistive.installed('com.apple.Chess')
            enabled_mock.assert_called_once_with('com.apple.Chess')
            assert not enable_mock.called
            assert not install_mock.called
            self.assertEqual(out, expected)
开发者ID:HowardMei,项目名称:saltstack,代码行数:25,代码来源:mac_assistive_test.py


示例19: test_add_serial_missing

    def test_add_serial_missing(self):
        '''
            Test adding a certificate to specified certificate store when the file doesn't exist
        '''
        expected = {
            'changes': {},
            'comment': 'Certificate file not found.',
            'name': '/path/to/cert.cer',
            'result': False
        }

        cache_mock = MagicMock(return_value=False)
        get_cert_serial_mock = MagicMock(return_value='ABCDEF')
        get_store_serials_mock = MagicMock(return_value=['123456'])
        add_mock = MagicMock(return_value='Added successfully')
        with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock,
                                            'certutil.get_cert_serial': get_cert_serial_mock,
                                            'certutil.get_stored_cert_serials': get_store_serials_mock,
                                            'certutil.add_store': add_mock}):
            out = certutil.add_store('/path/to/cert.cer', 'TrustedPublisher')
            cache_mock.assert_called_once_with('/path/to/cert.cer', 'base')
            assert not get_cert_serial_mock.called
            assert not get_store_serials_mock.called
            assert not add_mock.called
            self.assertEqual(expected, out)
开发者ID:bryson,项目名称:salt,代码行数:25,代码来源:win_certutil_test.py


示例20: test_package_removed_removed

    def test_package_removed_removed(self):
        '''
            Test removing a package already removed
        '''
        expected = {
            'comment': "The package Pack2 is already removed",
            'changes': {},
            'name': 'Pack2',
            'result': True}

        mock_removed = MagicMock(
            side_effect=[['Pack1'], ['Pack1']])
        mock_remove = MagicMock()
        mock_info = MagicMock(
            return_value={'Package Identity': 'Pack2'})

        with patch.dict(
            dism.__salt__, {'dism.installed_packages': mock_removed,
                            'dism.remove_package': mock_remove,
                            'dism.package_info': mock_info}):

            out = dism.package_removed('Pack2')

            mock_removed.assert_called_once_with()
            assert not mock_remove.called
            self.assertEqual(out, expected)
开发者ID:bryson,项目名称:salt,代码行数:26,代码来源:win_dism_test.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python mock.Mock类代码示例发布时间:2022-05-27
下一篇:
Python mock.patch函数代码示例发布时间: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