当前位置: 首页>>代码示例>>Python>>正文


Python mock.mock_open方法代码示例

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


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

示例1: test_title_changed_to_include_image_name_when_title_given

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_title_changed_to_include_image_name_when_title_given(self,
            mock_open, mock_add_header, mock_add_img_subj, mock_index,
            mock_exists, mock_writable):
        mock_file = MagicMock(spec=io.IOBase)
        mock_open.return_value.__enter__.return_value = mock_file
        mock_exists.return_value = False
        mock_writable.return_value = True
        qc_config = self.get_config_stub()

        html.write_index_pages(self.qc_dir, qc_config, self.subject,
                title='QC mode for image {}')

        for image in qc_config.images:
            name = image.name
            found = False
            for call in mock_index.call_args_list:
                if name in call[1]['title']:
                    found = True
            assert found 
开发者ID:edickie,项目名称:ciftify,代码行数:21,代码来源:test_html.py

示例2: test_title_not_added_when_not_given

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_title_not_added_when_not_given(self, mock_open, mock_header):
        # Set up
        # fake page to 'open' and write to
        html_page = MagicMock()
        mock_open.return_value.__enter__.return_value = html_page
        # qc_config.Config stub
        class MockQCConfig(object):
            def __init__(self):
                pass

        # Call
        html.write_image_index(self.qc_dir, self.subjects, MockQCConfig(),
                self.page_subject, self.image_name)

        # Assert
        for call in html_page.write.call_args_list:
            assert '<h1>' not in call[0]
        assert mock_header.call_count == 1
        header_kword_args = mock_header.call_args_list[0][1]
        assert 'title' in header_kword_args.keys()
        assert header_kword_args['title'] == None 
开发者ID:edickie,项目名称:ciftify,代码行数:23,代码来源:test_html.py

示例3: test_pull_image_success

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_pull_image_success(self, mock_find_image, mock_download_image,
                                mock_should_pull_image, mock_search_on_host):
        mock_should_pull_image.return_value = True
        mock_search_on_host.return_value = {'image': 'nginx', 'path': 'xyz',
                                            'checksum': 'xxx'}
        image_meta = mock.MagicMock()
        image_meta.id = '1234'
        image_meta.name = 'image'
        image_meta.tags = ['latest']
        mock_find_image.return_value = image_meta
        mock_download_image.return_value = 'content'
        CONF.set_override('images_directory', self.test_dir, group='glance')
        out_path = os.path.join(self.test_dir, '1234' + '.tar')
        mock_open_file = mock.mock_open()
        with mock.patch('zun.image.glance.driver.open', mock_open_file):
            ret = self.driver.pull_image(None, 'image', 'latest', 'always',
                                         None)
        mock_open_file.assert_any_call(out_path, 'wb')
        self.assertTrue(mock_search_on_host.called)
        self.assertTrue(mock_should_pull_image.called)
        self.assertTrue(mock_find_image.called)
        self.assertTrue(mock_download_image.called)
        self.assertEqual(({'image': 'image', 'path': out_path,
                           'tags': ['latest']}, False), ret) 
开发者ID:openstack,项目名称:zun,代码行数:26,代码来源:test_driver.py

示例4: test_binary

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_binary(self, mocker):
        """Test if _open and _write correctly handle binary files."""
        open_mock = mock.mock_open()
        mocker.patch('builtins.open', open_mock)

        testdata = b'\xf0\xff'

        lineparser = lineparsermod.BaseLineParser(
            self.CONFDIR, self.FILENAME, binary=True)
        with lineparser._open('r') as f:
            lineparser._write(f, [testdata])

        open_mock.assert_called_once_with(
            str(pathlib.Path(self.CONFDIR) / self.FILENAME), 'rb')

        open_mock().write.assert_has_calls([
            mock.call(testdata),
            mock.call(b'\n')
        ]) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:21,代码来源:test_lineparser.py

示例5: test_resgroup_add_pids

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_resgroup_add_pids(makedirs_mock, set_effective_root_uid_mock,
                           resgroup_name, pids, mongroup_name,
                           expected_writes, expected_setuid_calls_count, expected_makedirs):
    """Test that for ResGroup created with resgroup_name, when add_pids() is called with
    pids and given mongroup_name, expected writes (filenames with expected bytes writes)
    will happen together with number of setuid calls and makedirs calls.
    """
    write_mocks = {filename: mock_open() for filename in expected_writes}
    resgroup = ResGroup(name=resgroup_name)

    # if expected_log:
    with patch('builtins.open', new=create_open_mock(write_mocks)):
        resgroup.add_pids(pids, mongroup_name)

    for filename, write_mock in write_mocks.items():
        expected_filename_writes = expected_writes[filename]
        expected_write_calls = [call().write(write_body) for write_body in expected_filename_writes]
        write_mock.assert_has_calls(expected_write_calls, any_order=True)

    # makedirs used
    makedirs_mock.assert_has_calls(expected_makedirs)

    # setuid used (at least number of times)
    expected_setuid_calls = [call.__enter__()] * expected_setuid_calls_count
    set_effective_root_uid_mock.assert_has_calls(expected_setuid_calls, any_order=True) 
开发者ID:intel,项目名称:workload-collocation-agent,代码行数:27,代码来源:test_resctrl_measurements.py

示例6: test__interface_by_mac_not_found

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test__interface_by_mac_not_found(self, mock_ipr):
        mock_ipr_instance = mock.MagicMock()
        mock_ipr_instance.link_lookup.return_value = []
        mock_ipr().__enter__.return_value = mock_ipr_instance

        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        isfile_mock = mock.Mock()
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock), mock.patch.object(
                os.path, 'isfile', isfile_mock):
            self.assertRaises(wz_exceptions.HTTPException,
                              self.test_plug._interface_by_mac,
                              FAKE_MAC_ADDRESS.upper())
        open_mock.assert_called_once_with('/sys/bus/pci/rescan', os.O_WRONLY)
        fd_mock().write.assert_called_once_with('1') 
开发者ID:openstack,项目名称:octavia,代码行数:18,代码来源:test_plug.py

示例7: test_get_secret

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_get_secret(self):
        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        secret_id = uuidutils.generate_uuid()
        # Attempt to retrieve the secret
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock):
            local_cert_mgr.LocalCertManager.get_secret(None, secret_id)

        # Verify the correct files were opened
        flags = os.O_RDONLY
        open_mock.assert_called_once_with('/tmp/{0}.crt'.format(secret_id),
                                          flags)

        # Test failure path
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock) as mock_open:
            mock_open.side_effect = IOError
            self.assertRaises(exceptions.CertificateRetrievalException,
                              local_cert_mgr.LocalCertManager.get_secret,
                              None, secret_id) 
开发者ID:openstack,项目名称:octavia,代码行数:23,代码来源:test_local.py

示例8: test_flash_with_path_to_runtime

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_flash_with_path_to_runtime():
    """
    Use the referenced runtime hex file when building the hex file to be
    flashed onto the device.
    """
    mock_o = mock.mock_open(read_data=b'script')
    with mock.patch.object(builtins, 'open', mock_o) as mock_open:
        with mock.patch('uflash.embed_hex', return_value='foo') as em_h:
            with mock.patch('uflash.find_microbit', return_value='bar'):
                with mock.patch('uflash.save_hex') as mock_save:
                    uflash.flash('tests/example.py',
                                 path_to_runtime='tests/fake.hex')
                    assert mock_open.call_args[0][0] == 'tests/fake.hex'
                    assert em_h.call_args[0][0] == b'script'
                    expected_hex_path = os.path.join('bar', 'micropython.hex')
                    mock_save.assert_called_once_with('foo', expected_hex_path) 
开发者ID:ntoll,项目名称:uflash,代码行数:18,代码来源:test_uflash.py

示例9: test_extract_paths

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_extract_paths():
    """
    Test the different paths of the extract() function.
    It should open and extract the contents of the file (input arg)
    When called with only an input it should print the output of extract_script
    When called with two arguments it should write the output to the output arg
    """
    mock_e = mock.MagicMock(return_value=b'print("hello, world!")')
    mock_o = mock.mock_open(read_data='script')

    with mock.patch('uflash.extract_script', mock_e) as mock_extract_script, \
            mock.patch.object(builtins, 'print') as mock_print, \
            mock.patch.object(builtins, 'open', mock_o) as mock_open:
        uflash.extract('foo.hex')
        mock_open.assert_called_once_with('foo.hex', 'r')
        mock_extract_script.assert_called_once_with('script')
        mock_print.assert_called_once_with(b'print("hello, world!")')

        uflash.extract('foo.hex', 'out.py')
        assert mock_open.call_count == 3
        mock_open.assert_called_with('out.py', 'w')
        assert mock_open.return_value.write.call_count == 1 
开发者ID:ntoll,项目名称:uflash,代码行数:24,代码来源:test_uflash.py

示例10: test_render_template_to_file_with_makedirs

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_render_template_to_file_with_makedirs(self, mock_makedirs,
                                                   mock_exists,
                                                   mock_open):
        mock_exists.return_value = False

        output_path = '/tmp/designate/resources/templates/hello.jinja2'

        template = jinja2.Template('Hello {{name}}')

        utils.render_template_to_file(
            template, makedirs=True, output_path=output_path, name='World'
        )

        mock_makedirs.assert_called_once_with(
            '/tmp/designate/resources/templates'
        )
        mock_open.assert_called_once_with(output_path, 'w')
        mock_open().write.assert_called_once_with('Hello World') 
开发者ID:openstack,项目名称:designate,代码行数:20,代码来源:test_utils.py

示例11: test__serializer_load_metrics

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test__serializer_load_metrics(self, mocked_load):
        obj = {"key", 1}
        mocked_load.return_value = obj
        object_reference = "_metrics"

        class _EAction(EngineBaseAction):
            _metrics = None

            def execute(self, params, **kwargs):
                pass

        mocked_open = mock.mock_open()
        with mock.patch('marvin_python_toolbox.engine_base.engine_base_action.open', mocked_open, create=False):
            _metrics = _EAction(default_root_path="/tmp/.marvin", persistence_mode="local")._load_obj(object_reference)

        mocked_load.assert_called_once_with(ANY)
        mocked_open.assert_called_once()
        assert obj == _metrics 
开发者ID:marvin-ai,项目名称:marvin-python-toolbox,代码行数:20,代码来源:test_engine_base_action.py

示例12: test__serializer_dump_metrics

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test__serializer_dump_metrics(self, mocked_dump):
        obj = {"key", 1}
        object_reference = "_metrics"

        class _EAction(EngineBaseAction):
            _metrics = None

            def execute(self, params, **kwargs):
                pass

        mocked_open = mock.mock_open()
        with mock.patch('marvin_python_toolbox.engine_base.engine_base_action.open', mocked_open, create=False):
            _EAction(default_root_path="/tmp/.marvin", persistence_mode="local")._save_obj(object_reference, obj)

        mocked_dump.assert_called_once_with(obj, ANY, indent=4, separators=(u',', u': '), sort_keys=True)
        mocked_open.assert_called_once() 
开发者ID:marvin-ai,项目名称:marvin-python-toolbox,代码行数:18,代码来源:test_engine_base_action.py

示例13: test_hive_generateconf_write_file_with_json

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def test_hive_generateconf_write_file_with_json(mocked_json):
    default_conf = [{
        "origin_host": "xxx_host_name",
        "origin_db": "xxx_db_name",
        "origin_queue": "marvin",
        "target_table_name": "xxx_table_name",
        "sample_sql": "SELECT * FROM XXX",
        "sql_id": "1"
    }]

    mocked_open = mock.mock_open()
    with mock.patch('marvin_python_toolbox.management.hive.open', mocked_open, create=True):
        hive.hive_generateconf(None)

    mocked_open.assert_called_once_with('hive_dataimport.conf', 'w')
    mocked_json.dump.assert_called_once_with(default_conf, mocked_open(), indent=2) 
开发者ID:marvin-ai,项目名称:marvin-python-toolbox,代码行数:18,代码来源:test_hive.py

示例14: setUp

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def setUp(self):

        self.file1_open = mock_open(
            read_data=(
                "Date,Time,Technician,Lab,Plot,Seed sample,Humidity,Light,"
                "Temperature,Equipment Fault,Plants,Blossoms,Fruit,Min Height,"
                "Max Height,Median Height,Notes\r\n"
                "2018-06-01,8:00,J Simms,A,2,AX478,24.47,1.01,21.44,False,14,"
                "27,1,2.35,9.2,5.09,\r\n"
                "2018-06-01,8:00,J Simms,A,3,AX479,24.15,1,20.82,False,18,49,"
                "6,2.47,14.2,11.83,\r\n"
            )
        )
        self.file2_open = mock_open(
            read_data=''
        )

        self.model1 = models.CSVModel('file1')
        self.model2 = models.CSVModel('file2') 
开发者ID:PacktPublishing,项目名称:Python-GUI-Programming-with-Tkinter,代码行数:21,代码来源:test_models.py

示例15: distro

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import mock_open [as 别名]
def distro(self, isobin_exists, filelist_in_iso, input_text):
        mock_isobin_exists = MM(return_value=isobin_exists)
        mock_iso_list = MM(return_value=filelist_in_iso)
        mock_os_walk = MM(return_value=[('/', [], ['grub.cfg'])])
        @patch('scripts.iso.isolinux_bin_exist', mock_isobin_exists)
        @patch('os.walk', mock_os_walk)
        @patch('scripts._7zip.list_iso', mock_iso_list)
        @patch('builtins.open', mock_open(read_data=input_text))
        def test_when_isolinux_bin_is_available():
            return (distro.distro('{iso-cfg-dir}', 'ProDOS2.iso'))
        return test_when_isolinux_bin_is_available() 
开发者ID:mbusb,项目名称:multibootusb,代码行数:13,代码来源:test-distro.py


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