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

Python mock.mock_open函数代码示例

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

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



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

示例1: 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


示例2: test_persist_no_conf_success

 def test_persist_no_conf_success(self):
     '''
     Tests successful add of config file when previously not one
     '''
     mock = mock_open()
     with patch('salt.utils.fopen', mock_open(read_data=mock)) as m_open:
         darwin_sysctl.persist('net.inet.icmp.icmplim', 50)
         helper_open = m_open()
         helper_open.write.assert_called_once_with(
             '#\n# Kernel sysctl configuration\n#\n')
开发者ID:ricardoheyn,项目名称:forzen-salt,代码行数:10,代码来源:darwin_sysctl_test.py


示例3: test_persist_no_conf_failure

 def test_persist_no_conf_failure(self):
     '''
     Tests adding of config file failure
     '''
     mock = mock_open()
     with patch('salt.utils.fopen', mock_open(read_data=mock)) as m_open:
         helper_open = m_open()
         helper_open.write.assertRaises(CommandExecutionError,
                                        darwin_sysctl.persist,
                                        'net.inet.icmp.icmplim',
                                        50, config=None)
开发者ID:ricardoheyn,项目名称:forzen-salt,代码行数:11,代码来源:darwin_sysctl_test.py


示例4: test_diff_binary_files

 def test_diff_binary_files(self):
     fopen_effect = [
         mock_open(read_data="dummy binary").return_value,
         mock_open(read_data="dummy binary").return_value,
     ]
     with patch('salt.utils.fopen') as fopen_mock:
         fopen_mock.side_effect = fopen_effect
         module_ret = {
             "/tmp/foo3": MODULE_RET['DIFF']["/tmp/foo3"],
         }
         self.assertEqual(snapper.diff(), module_ret)
开发者ID:SUSE,项目名称:salt-snapper-module,代码行数:11,代码来源:snapper_test.py


示例5: 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


示例6: test_diff_text_files

 def test_diff_text_files(self):
     fopen_effect = [
         mock_open(read_data=FILE_CONTENT["/tmp/foo"]['pre']).return_value,
         mock_open(read_data=FILE_CONTENT["/tmp/foo"]['post']).return_value,
         mock_open(read_data=FILE_CONTENT["/tmp/foo2"]['post']).return_value,
     ]
     with patch('salt.utils.fopen') as fopen_mock:
         fopen_mock.side_effect = fopen_effect
         module_ret = {
             "/tmp/foo": MODULE_RET['DIFF']["/tmp/foo"],
             "/tmp/foo2": MODULE_RET['DIFF']["/tmp/foo2"],
         }
         self.assertEqual(snapper.diff(), module_ret)
开发者ID:SUSE,项目名称:salt-snapper-module,代码行数:13,代码来源:snapper_test.py


示例7: test_summary

    def test_summary(self):
        '''
            Test to show a summary of the last puppet agent run
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            with patch('salt.utils.fopen',
                        mock_open(read_data="resources: 1")):
                self.assertDictEqual(puppet.summary(), {'resources': 1})

            with patch('salt.utils.fopen', mock_open()) as m_open:
                m_open.side_effect = IOError(13, 'Permission denied:', '/file')
                self.assertRaises(CommandExecutionError, puppet.summary)
开发者ID:bryson,项目名称:salt,代码行数:13,代码来源:puppet_test.py


示例8: test_summary

    def test_summary(self):
        '''
            Test to show a summary of the last puppet agent run
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            with patch('salt.utils.fopen',
                        mock_open(read_data="resources: 1")):
                self.assertDictEqual(puppet.summary(), {'resources': 1})

            with patch('salt.utils.fopen', mock_open()) as m_open:
                helper_open = m_open()
                helper_open.write.assertRaises(CommandExecutionError,
                                                puppet.summary)
开发者ID:HowardMei,项目名称:saltstack,代码行数:14,代码来源:puppet_test.py


示例9: test_get_zone

    def test_get_zone(self):
        '''
        Test to get current timezone (i.e. America/Denver)
        '''
        zone = 'MST'

        with patch.object(salt.utils, 'which', return_value=True):
            mock_cmd = MagicMock(return_value={'stderr': 'error', 'retcode': 1})
            with patch.dict(timezone.__salt__, {'cmd.run_all': mock_cmd}):
                self.assertRaises(CommandExecutionError, timezone.get_zone)

            mock_cmd = MagicMock(return_value={'stdout': 'Timezone: {0}'.format(zone),
                                               'retcode': 0})
            with patch.dict(timezone.__salt__, {'cmd.run_all': mock_cmd}):
                self.assertEqual(timezone.get_zone(), zone)

            mock_cmd = MagicMock(return_value={'stdout': 'ZoneCTL: {0}'.format(zone),
                                               'retcode': 0})
            with patch.dict(timezone.__salt__, {'cmd.run_all': mock_cmd}):
                self.assertRaises(CommandExecutionError, timezone.get_zone)

        with patch.object(salt.utils, 'which', return_value=False):
            file_data = '\n'.join(['#', 'A'])
            with patch('salt.utils.fopen', mock_open(read_data=file_data),
                       create=True) as mfile:
                mfile.return_value.__iter__.return_value = file_data.splitlines()
                with patch.dict(timezone.__grains__, {'os_family': 'Debian',
                                                      'os': 'Debian'}):
                    self.assertEqual(timezone.get_zone(), '#\nA')

                with patch.dict(timezone.__grains__, {'os_family': 'Gentoo',
                                                      'os': 'Gentoo'}):
                    self.assertEqual(timezone.get_zone(), '')

            with patch.dict(timezone.__grains__, {'os_family': 'FreeBSD',
                                                  'os': 'FreeBSD'}):
                zone = 'America/Denver'
                linkpath = '/usr/share/zoneinfo/' + zone
                with patch.object(os, 'readlink', return_value=linkpath):
                    self.assertEqual(timezone.get_zone(), zone)

            with patch.dict(timezone.__grains__, {'os_family': 'Solaris',
                                                  'os': 'Solaris'}):
                fl_data = 'TZ=Foo\n'
                with patch('salt.utils.fopen',
                           mock_open(read_data=fl_data)) as mfile:
                    mfile.return_value.__iter__.return_value = [fl_data]
                    self.assertEqual(timezone.get_zone(), 'Foo')
开发者ID:HowardMei,项目名称:saltstack,代码行数:48,代码来源:timezone_test.py


示例10: test_vfstab

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


示例11: test_swaps

    def test_swaps(self):
        """
        Return a dict containing information on active swap
        """

        file_data = "\n".join(["Filename Type Size Used Priority", "/dev/sda1 partition 31249404 4100 -1"])
        with patch.dict(mount.__grains__, {"os": "", "kernel": ""}):
            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.assertDictEqual(
                    mount.swaps(),
                    {"/dev/sda1": {"priority": "-1", "size": "31249404", "type": "partition", "used": "4100"}},
                )

        file_data = "\n".join(
            ["Device Size Used Unknown Unknown Priority", "/dev/sda1 31249404 4100 unknown unknown -1"]
        )
        mock = MagicMock(return_value=file_data)
        with patch.dict(mount.__grains__, {"os": "OpenBSD", "kernel": "OpenBSD"}):
            with patch.dict(mount.__salt__, {"cmd.run_stdout": mock}):
                self.assertDictEqual(
                    mount.swaps(),
                    {"/dev/sda1": {"priority": "-1", "size": "31249404", "type": "partition", "used": "4100"}},
                )
开发者ID:bryson,项目名称:salt,代码行数:25,代码来源:mount_test.py


示例12: test_config

 def test_config(self):
     '''
     Test if it create VirtualHost configuration files
     '''
     with patch('salt.utils.fopen', mock_open()):
         self.assertEqual(apache.config('/ports.conf',
                                        [{'Listen': '22'}]), 'Listen 22')
开发者ID:DaveQB,项目名称:salt,代码行数:7,代码来源:apache_test.py


示例13: 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


示例14: test_check_request

    def test_check_request(self):
        '''
            Test to return the state request information
        '''
        with patch.dict(state.__opts__, {"cachedir": "D"}):
            mock = MagicMock(return_value=True)
            with patch.object(os.path, 'join', mock):
                mock = MagicMock(side_effect=[True, True, False])
                with patch.object(os.path, 'isfile', mock):
                    with patch('salt.utils.fopen', mock_open()):
                        self.assertDictEqual(state.check_request(), {'A': 'B'})

                    with patch('salt.utils.fopen', mock_open()):
                        self.assertEqual(state.check_request("A"), 'B')

                    self.assertDictEqual(state.check_request(), {})
开发者ID:DaveQB,项目名称:salt,代码行数:16,代码来源:state_test.py


示例15: test_keys

    def test_keys(self):
        '''
        Test to manage libvirt keys.
        '''
        name = 'sunrise'

        ret = {'name': name,
               'result': True,
               'comment': '',
               'changes': {}}

        mock = MagicMock(side_effect=[[], ['libvirt.servercert.pem'],
                                      {'libvirt.servercert.pem': 'A'}])
        with patch.dict(libvirt.__salt__, {'pillar.ext': mock}):
            comt = ('All keys are correct')
            ret.update({'comment': comt})
            self.assertDictEqual(libvirt.keys(name), ret)

            with patch.dict(libvirt.__opts__, {'test': True}):
                comt = ('Libvirt keys are set to be updated')
                ret.update({'comment': comt, 'result': None})
                self.assertDictEqual(libvirt.keys(name), ret)

            with patch.dict(libvirt.__opts__, {'test': False}):
                with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
                    comt = ('Updated libvirt certs and keys')
                    ret.update({'comment': comt, 'result': True,
                                'changes': {'servercert': 'new'}})
                    self.assertDictEqual(libvirt.keys(name), ret)
开发者ID:dmyerscough,项目名称:salt,代码行数:29,代码来源:libvirt_test.py


示例16: test_request

 def test_request(self):
     '''
         Test to request the local admin execute a state run
     '''
     mock = MagicMock(return_value=True)
     with patch.object(state, 'apply_', mock):
         with patch.dict(state.__opts__, {"cachedir": "D"}):
             mock = MagicMock(return_value=True)
             with patch.object(os.path, 'join', mock):
                 mock = MagicMock(return_value=
                                  {"test_run": "",
                                   "mods": "",
                                   "kwargs": ""})
                 with patch.object(state, 'check_request', mock):
                     mock = MagicMock(return_value=True)
                     with patch.object(os, 'umask', mock):
                         with patch.object(salt.utils, 'is_windows', mock):
                             with patch.dict(state.__salt__,
                                             {'cmd.run': mock}):
                                 with patch('salt.utils.fopen',
                                            mock_open()):
                                     mock = MagicMock(
                                                      return_value=True)
                                     with patch.object(os, 'umask',
                                                       mock):
                                         self.assertTrue(
                                                         state.request("A")
                                                         )
开发者ID:DaveQB,项目名称:salt,代码行数:28,代码来源:state_test.py


示例17: test_get_saved_rules

 def test_get_saved_rules(self):
     '''
     Test if it return a data structure of the rules in the conf file
     '''
     with patch.dict(nftables.__grains__, {'os_family': 'Debian'}):
         with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
             self.assertListEqual(nftables.get_saved_rules(), [])
开发者ID:bryson,项目名称:salt,代码行数:7,代码来源:nftables_test.py


示例18: test_swaps

    def test_swaps(self):
        '''
        Return a dict containing information on active swap
        '''

        file_data = '\n'.join(['Filename Type Size Used Priority',
                               '/dev/sda1 partition 31249404 4100 -1'])
        with patch.dict(mount.__grains__, {'os': ''}):
            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.assertDictEqual(mount.swaps(), {'/dev/sda1':
                                                     {'priority': '-1',
                                                      'size': '31249404',
                                                      'type': 'partition',
                                                      'used': '4100'}})

        file_data = '\n'.join(['Device Size Used Unknown Unknown Priority',
                               '/dev/sda1 31249404 4100 unknown unknown -1'])
        mock = MagicMock(return_value=file_data)
        with patch.dict(mount.__grains__, {'os': 'OpenBSD'}):
            with patch.dict(mount.__salt__, {'cmd.run_stdout': mock}):
                self.assertDictEqual(mount.swaps(), {'/dev/sda1':
                                                     {'priority': '-1',
                                                      'size': '31249404',
                                                      'type': 'partition',
                                                      'used': '4100'}})
开发者ID:HowardMei,项目名称:saltstack,代码行数:29,代码来源:mount_test.py


示例19: test_set_host_true

 def test_set_host_true(self):
     '''
     Tests true if the alias is set
     '''
     with patch('salt.utils.fopen', mock_open()):
         mock_opt = MagicMock(return_value=None)
         with patch.dict(hosts.__salt__, {'config.option': mock_opt}):
             self.assertTrue(hosts.set_host('10.10.10.10', 'Salt1'))
开发者ID:DaveQB,项目名称:salt,代码行数:8,代码来源:hosts_test.py


示例20: test_read_file

 def test_read_file(self):
     '''
     Test if the parsing function works
     '''
     with patch('salt.utils.fopen', mock_open(read_data=MOCK_FILE)):
         self.assertListEqual(pam.read_file('/etc/pam.d/login'),
                              [{'arguments': [], 'control_flag': 'ok',
                                'interface': 'ok', 'module': 'ignore'}])
开发者ID:bryson,项目名称:salt,代码行数:8,代码来源:pam_test.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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