當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。