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


Python mock.MagicMock方法代码示例

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


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

示例1: mock_pywin32

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def mock_pywin32():
    """Mock pywin32 module.

    Resulting in Linux hosts, including ReadTheDocs,
    and other environments that don't have pywin32 can generate the docs
    properly including the PDF version.
    See:
    http://read-the-docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
    """
    if try_import('win32api'):
        return

    from unittest import mock

    MOCK_MODULES = [
        'win32api', 'win32con', 'win32event', 'win32service',
        'win32serviceutil',
    ]
    for mod_name in MOCK_MODULES:
        sys.modules[mod_name] = mock.MagicMock() 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:22,代码来源:conf.py

示例2: test_distro_detection

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_distro_detection(self):
        def os_path_exists(f):
            if f.endswith('multibootusb.log'):
                return False
            return True
        os_path_exists_mock = MM()
        log_mock = MM()
        @patch('os.path.exists', os_path_exists)
        @patch('scripts.distro.log', log_mock)
        def _():
            fn = distro.detect_iso_from_file_list
            assert fn(['BOOT.wim', 'Sources']) == 'Windows'
            assert fn(['BOOT.wim', 'Sause']) is None
            assert fn(['config.isoclient', 'foo']) == 'opensuse'
            assert fn(['bar', 'dban', 'foo']) == 'slitaz'
            assert fn(['memtest.img']) == 'memtest'
            assert fn(['mt86.png','isolinux']) == 'raw_iso'
            assert fn(['menu.lst']) == 'grub4dos'
            assert fn(['bootwiz.cfg', 'bootmenu_logo.png']) == \
                'grub4dos_iso'
        _() 
开发者ID:mbusb,项目名称:multibootusb,代码行数:23,代码来源:test-distro.py

示例3: setUp

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

        # We need to be in the same directory than the script so the commands in the dockerfiles work as
        # expected. But the script can be invoked from a different path
        base = os.path.split(os.path.realpath(__file__))[0]
        os.chdir(base)

        docker_cache._login_dockerhub = MagicMock()  # Override login

        # Stop in case previous execution was dirty
        try:
            self._stop_local_docker_registry()
        except Exception:
            pass

        # Start up docker registry
        self._start_local_docker_registry() 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:20,代码来源:test_docker_cache.py

示例4: test_execute

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_execute(self, mock_zipfile, mock_makedirs, mock_exists, mock_expanduser):
        mock_expanduser.return_value = "test/dummy"
        mock_exists.return_value = False

        mock_zip = mock.MagicMock()
        mock_zipfile.ZipFile.return_value = mock_zip
        config = sb.objects.config.Config()
        args = argparse.Namespace(plugin="test.zip")

        plugin = sb.components.plugin.Plugin()
        plugin.execute(config, args)

        mock_zipfile.ZipFile.assert_called_with("test.zip", "r")
        mock_zip.extractall.assert_called()
        mock_zip.close.assert_called()

        mock_makedirs.assert_any_call("test/dummy", exist_ok=True) 
开发者ID:carsdotcom,项目名称:skelebot,代码行数:19,代码来源:test_components_plugin.py

示例5: test_comparison

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_comparison(self):
        mock = Mock()
        def comp(s, o):
            return True
        mock.__lt__ = mock.__gt__ = mock.__le__ = mock.__ge__ = comp
        self. assertTrue(mock < 3)
        self. assertTrue(mock > 3)
        self. assertTrue(mock <= 3)
        self. assertTrue(mock >= 3)

        self.assertRaises(TypeError, lambda: MagicMock() < object())
        self.assertRaises(TypeError, lambda: object() < MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() < MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() > object())
        self.assertRaises(TypeError, lambda: object() > MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() > MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() <= object())
        self.assertRaises(TypeError, lambda: object() <= MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() <= MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() >= object())
        self.assertRaises(TypeError, lambda: object() >= MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() >= MagicMock()) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:24,代码来源:testmagicmethods.py

示例6: test_magic_methods_and_spec

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_magic_methods_and_spec(self):
        class Iterable(object):
            def __iter__(self):
                pass

        mock = Mock(spec=Iterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        mock.__iter__ = Mock(return_value=iter([]))
        self.assertEqual(list(mock), [])

        class NonIterable(object):
            pass
        mock = Mock(spec=NonIterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        def set_int():
            mock.__int__ = Mock(return_value=iter([]))
        self.assertRaises(AttributeError, set_int)

        mock = MagicMock(spec=Iterable)
        self.assertEqual(list(mock), [])
        self.assertRaises(AttributeError, set_int) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:25,代码来源:testmagicmethods.py

示例7: test_magic_methods_and_spec_set

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_magic_methods_and_spec_set(self):
        class Iterable(object):
            def __iter__(self):
                pass

        mock = Mock(spec_set=Iterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        mock.__iter__ = Mock(return_value=iter([]))
        self.assertEqual(list(mock), [])

        class NonIterable(object):
            pass
        mock = Mock(spec_set=NonIterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        def set_int():
            mock.__int__ = Mock(return_value=iter([]))
        self.assertRaises(AttributeError, set_int)

        mock = MagicMock(spec_set=Iterable)
        self.assertEqual(list(mock), [])
        self.assertRaises(AttributeError, set_int) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:25,代码来源:testmagicmethods.py

示例8: test_title_changed_to_include_image_name_when_title_given

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [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

示例9: test_title_not_added_when_not_given

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [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

示例10: test_image_and_subject_page_linked_for_each_subject

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_image_and_subject_page_linked_for_each_subject(self, mock_open,
            mock_link):
        # Set up
        html_page = MagicMock()
        mock_open.return_value.__enter__.return_value = html_page
        class MockQCConfig(object):
            def __init__(self):
                pass
            def get_navigation_list(self, path):
                return []

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

        # Assert
        assert mock_link.call_count == len(self.subjects) 
开发者ID:edickie,项目名称:ciftify,代码行数:19,代码来源:test_html.py

示例11: test_body_raw_body

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_body_raw_body(monkeypatch):
    app = MagicMock()
    app.default_content_type = 'application/json'
    p = {'application/json': JSONParser()}
    monkeypatch.setattr('waspy.webtypes.parsers', p)

    # Test happy path
    original_body = {'test': 'original'}
    r = Response(body=original_body)
    r.app = app
    assert r.body == original_body
    assert r.raw_body == json.dumps(original_body).encode()

    # Test changing the body later
    new_body = {'test': 'new body'}
    r.body = new_body
    assert r.body == new_body
    assert r.raw_body == json.dumps(new_body).encode() 
开发者ID:wasp,项目名称:waspy,代码行数:20,代码来源:test_content_types.py

示例12: test_container_commit

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_container_commit(
            self, mock_save, mock_unpause, mock_pause, mock_commit,
            mock_get_image, mock_upload_image_data, mock_action_finish,
            mock_event_finish, mock_event_start):
        container = Container(self.context, **utils.get_test_container(
            status=consts.PAUSED))
        mock_get_image_response = mock.MagicMock()
        mock_get_image_response.data = StringIO().read()
        mock_get_image.return_value = mock_get_image_response
        mock_upload_image_data.return_value = mock.MagicMock()

        self.compute_manager._do_container_commit(self.context,
                                                  mock_get_image_response,
                                                  container, 'repo', 'tag')
        mock_commit.assert_called_once_with(
            self.context, container, 'repo', 'tag')
        mock_pause.assert_not_called()
        mock_unpause.assert_not_called()
        self.assertEqual(
            (self.context, container.uuid, 'compute__do_container_commit'),
            mock_event_finish.call_args[0])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_val'])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_tb']) 
开发者ID:openstack,项目名称:zun,代码行数:25,代码来源:test_compute_manager.py

示例13: test_container_commit_with_pause

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_container_commit_with_pause(
            self, mock_save, mock_unpause, mock_pause, mock_commit,
            mock_get_image, mock_upload_image_data, mock_action_finish,
            mock_event_finish, mock_event_start):
        container = Container(self.context, **utils.get_test_container())
        mock_get_image_response = mock.MagicMock()
        mock_get_image_response.data = StringIO().read()
        mock_get_image.return_value = mock_get_image_response
        mock_upload_image_data.return_value = mock.MagicMock()
        mock_unpause.return_value = container
        mock_pause.return_value = container

        self.compute_manager._do_container_commit(self.context,
                                                  mock_get_image_response,
                                                  container, 'repo', 'tag')
        mock_commit.assert_called_once_with(
            self.context, container, 'repo', 'tag')
        mock_pause.assert_called_once_with(self.context, container)
        mock_unpause.assert_called_once_with(self.context, container)
        self.assertEqual(
            (self.context, container.uuid, 'compute__do_container_commit'),
            mock_event_finish.call_args[0])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_val'])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_tb']) 
开发者ID:openstack,项目名称:zun,代码行数:26,代码来源:test_compute_manager.py

示例14: test_container_create

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_container_create(self, mock_schedule_container,
                              mock_image_search,
                              mock_container_create,
                              mock_record_action_start):
        CONF.set_override('enable_image_validation', True, group="api")
        container = self.container
        container.status = consts.CREATING
        image_meta = mock.MagicMock()
        image_meta.id = '1234'
        mock_schedule_container.return_value = {'host': u'Centos',
                                                'nodename': None,
                                                'limits': {}}
        mock_image_search.return_value = [image_meta]
        self.compute_api.container_create(self.context, container,
                                          {}, None, None, False)
        self.assertTrue(mock_schedule_container.called)
        self.assertTrue(mock_image_search.called)
        self.assertTrue(mock_container_create.called) 
开发者ID:openstack,项目名称:zun,代码行数:20,代码来源:test_compute_api.py

示例15: test_connect_container_to_network_failed

# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import MagicMock [as 别名]
def test_connect_container_to_network_failed(self, mock_neutron_api_cls):
        container = Container(self.context, **utils.get_test_container())
        network_name = 'c02afe4e-8350-4263-8078'
        requested_net = {'ipv4_address': '10.5.0.22',
                         'port': 'fake-port-id',
                         'preserve_on_delete': True}
        mock_neutron_api_cls.return_value = self.network_api.neutron_api
        old_port = self.network_api.neutron_api.list_ports(
            id='fake-port-id')['ports'][0]
        self.assertEqual('', old_port['device_id'])
        self.network_api.docker = mock.MagicMock()
        self.network_api.docker.connect_container_to_network = \
            mock.Mock(side_effect=exception.DockerError)
        self.assertRaises(exception.DockerError,
                          self.network_api.connect_container_to_network,
                          container, network_name, requested_net)
        new_port = self.network_api.neutron_api.list_ports(
            id='fake-port-id')['ports'][0]
        self.assertEqual('', new_port['device_id']) 
开发者ID:openstack,项目名称:zun,代码行数:21,代码来源:test_kuryr_network.py


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