本文整理匯總了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()
示例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'
_()
示例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()
示例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)
示例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())
示例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)
示例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)
示例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
示例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
示例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)
示例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()
示例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'])
示例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'])
示例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)
示例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'])