本文整理汇总了Python中mock.MagicMock类的典型用法代码示例。如果您正苦于以下问题:Python MagicMock类的具体用法?Python MagicMock怎么用?Python MagicMock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MagicMock类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_poll_requeues_loops
def test_poll_requeues_loops(self):
loop = MagicMock()
loop.function = MagicMock()
loop.requeue = True
self.engine._callbacks.append(loop)
self.engine.poll(0.02)
self.assertTrue(loop in self.engine._callbacks)
开发者ID:larbing,项目名称:pants,代码行数:7,代码来源:test_engine.py
示例2: test_import
def test_import(self, server_proxy, requests):
"""
Test import operation
"""
proxy = MagicMock()
proxy.ImportInfrastructure.return_value = (True, "newinfid")
server_proxy.return_value = proxy
options = MagicMock()
options.auth_file = get_abs_path("../../auth.dat")
options.restapi = None
parser = MagicMock()
out = StringIO()
oldstdout = sys.stdout
sys.stdout = out
res = main("import", options, [get_abs_path("../files/test.radl")], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("New Inf: newinfid", output)
out = StringIO()
sys.stdout = out
options.xmlrpc = None
options.restapi = "https://localhost:8800"
requests.side_effect = self.get_response
res = main("import", options, [get_abs_path("../files/test.radl")], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("New Inf: newinfid", output)
sys.stdout = oldstdout
开发者ID:grycap,项目名称:im-client,代码行数:30,代码来源:test_client.py
示例3: test_save_grade_success
def test_save_grade_success(self):
data = {
'rubric_scores[]': [0, 0],
'location': self.location,
'submission_id': 1,
'submission_key': 'fake key',
'score': 2,
'feedback': 'feedback',
'submission_flagged': 'false',
'answer_unknown': 'false',
'rubric_scores_complete' : 'true'
}
qdict = MagicMock()
def fake_get_item(key):
return data[key]
qdict.__getitem__.side_effect = fake_get_item
qdict.getlist = fake_get_item
qdict.keys = data.keys
response = self.peer_module.save_grade(qdict)
self.assertTrue(response['success'])
开发者ID:6thfdwp,项目名称:edx-platform,代码行数:25,代码来源:tests.py
示例4: test_getstate
def test_getstate(self, server_proxy, requests):
"""
Test getstate operation
"""
proxy = MagicMock()
proxy.GetInfrastructureState.return_value = (True, {"state": "running", "vm_states": {"vm1": "running"}})
server_proxy.return_value = proxy
options = MagicMock()
options.auth_file = get_abs_path("../../auth.dat")
options.restapi = None
parser = MagicMock()
out = StringIO()
oldstdout = sys.stdout
sys.stdout = out
res = main("getstate", options, ["infid"], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("The infrastructure is in state: running\nVM ID: vm1 is in state: running.", output)
out = StringIO()
sys.stdout = out
options.xmlrpc = None
options.restapi = "https://localhost:8800"
requests.side_effect = self.get_response
res = main("getstate", options, ["infid"], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("The infrastructure is in state: running\nVM ID: vm1 is in state: running.", output)
sys.stdout = oldstdout
开发者ID:grycap,项目名称:im-client,代码行数:30,代码来源:test_client.py
示例5: test_rebootvm
def test_rebootvm(self, server_proxy, requests):
"""
Test rebootvm operation
"""
proxy = MagicMock()
proxy.RebootVM.return_value = (True, "")
server_proxy.return_value = proxy
options = MagicMock()
options.auth_file = get_abs_path("../../auth.dat")
options.restapi = None
parser = MagicMock()
out = StringIO()
oldstdout = sys.stdout
sys.stdout = out
res = main("rebootvm", options, ["infid", "vmid"], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("VM successfully rebooted", output)
out = StringIO()
sys.stdout = out
options.xmlrpc = None
options.restapi = "https://localhost:8800"
requests.side_effect = self.get_response
res = main("rebootvm", options, ["infid", "vmid"], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("VM successfully rebooted", output)
sys.stdout = oldstdout
开发者ID:grycap,项目名称:im-client,代码行数:30,代码来源:test_client.py
示例6: test_comit_no_parents
def test_comit_no_parents(self):
mocked_repo = MagicMock()
mocked_parent = MagicMock()
mocked_parent.id = 1
mocked_repo.status.return_value = True
mocked_repo.index.write_tree.return_value = "tree"
mocked_repo.revparse_single.return_value = mocked_parent
mocked_repo.create_commit.return_value = "commit"
author = ("author_1", "author_2")
commiter = ("commiter_1", "commiter_2")
with patch('gitfs.repository.Signature') as mocked_signature:
mocked_signature.return_value = "signature"
repo = Repository(mocked_repo)
commit = repo.commit("message", author, commiter)
assert commit == "commit"
assert mocked_repo.status.call_count == 1
assert mocked_repo.index.write_tree.call_count == 1
assert mocked_repo.index.write.call_count == 1
mocked_signature.has_calls([call(*author), call(*commiter)])
mocked_repo.revparse_single.assert_called_once_with("HEAD")
mocked_repo.create_commit.assert_called_once_with("HEAD",
"signature",
"signature",
"message",
"tree", [1])
开发者ID:krodyrobi,项目名称:gitfs,代码行数:32,代码来源:test_repository.py
示例7: test_addresource
def test_addresource(self, server_proxy, requests):
"""
Test addresource operation
"""
proxy = MagicMock()
proxy.AddResource.return_value = (True, ["1"])
server_proxy.return_value = proxy
options = MagicMock()
options.auth_file = get_abs_path("../../auth.dat")
options.restapi = None
parser = MagicMock()
out = StringIO()
oldstdout = sys.stdout
sys.stdout = out
res = main("addresource", options, ["infid", get_abs_path("../files/test.radl")], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("Resources with IDs: 1 successfully added.", output)
out = StringIO()
sys.stdout = out
options.xmlrpc = None
options.restapi = "https://localhost:8800"
requests.side_effect = self.get_response
res = main("addresource", options, ["infid", get_abs_path("../files/test.radl")], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("Resources with IDs: 1 successfully added.", output)
sys.stdout = oldstdout
开发者ID:grycap,项目名称:im-client,代码行数:30,代码来源:test_client.py
示例8: test_valid_enable_ipmi
def test_valid_enable_ipmi(login_mock, query_dn_mock, set_mo_mock):
# Patch ImcHandle.login to create a Faux ImcHandle object w/o real CIMC
# Patch ImcHandle.set_mo to simulate CIMC interaction w/o real CIMC
login_mock.return_value = True
set_mo_mock.return_value = True
ipmi_enabled_mock = MagicMock()
ipmi_enabled_mock.admin_state = "enabled"
test_cimc = ImcHandle(ip='169.254.1.1',
username='admin',
password='right')
test_cimc._set_platform(platform=IMC_PLATFORM.TYPE_CLASSIC)
query_dn_mock.return_value = ipmi_enabled_mock
# Scenario: Enable IPMI default values
assert ipmi_enable(test_cimc) is ipmi_enabled_mock
# Assert values of the object passed to add_mo()
test_ipmi_mo = set_mo_mock.call_args[0][0]
assert test_ipmi_mo.admin_state == "enabled"
assert test_ipmi_mo.priv == CommIpmiLanConsts.PRIV_ADMIN
assert test_ipmi_mo.key == '0'*40
# Scenario: Enable IPMI custom priv and key
assert ipmi_enable(test_cimc, priv="user", key='1'*40) is ipmi_enabled_mock
test_ipmi_mo = set_mo_mock.call_args[0][0]
assert test_ipmi_mo.admin_state == "enabled"
assert test_ipmi_mo.priv == "user"
assert test_ipmi_mo.key == '1'*40
开发者ID:CiscoUcs,项目名称:imcsdk,代码行数:28,代码来源:test_ipmi.py
示例9: test_create_aggregate_projections
def test_create_aggregate_projections(self):
connection = MagicMock()
self.create_task(cls=CopyToVerticaDummyTableWithProjections).create_aggregate_projections(connection)
self.assertEquals([
call('CREATE PROJECTION IF NOT EXISTS foobar.dummy_table_projection_2 DEFINITION_2 on foobar.dummy_table;'),
call('SELECT start_refresh();'),
], connection.cursor().execute.mock_calls)
开发者ID:hks-epod,项目名称:edx-analytics-pipeline,代码行数:7,代码来源:test_vertica_load.py
示例10: test_search_q
def test_search_q():
user = MagicMock(spec=auth_models.User)
user.is_staff = True
queryset = MagicMock(spec=QuerySet)
expected_result = MagicMock(spec=QuerySet)
(queryset
.select_related.return_value
.prefetch_related.return_value
.filter.return_value) = expected_result
params = {'q': ['meow']}
result = models.place.objects.get_search_queryset(user, queryset, params)
q = (
MyQ(title__icontains='meow')
| MyQ(address__icontains='meow')
| MyQ(address2__icontains='meow')
| MyQ(city__icontains='meow')
| MyQ(state__icontains='meow')
| MyQ(country__icontains='meow')
)
chained = (
call
.select_related('cover_photo')
.prefetch_related('cover_photo__photo_file_set')
.filter(q)
)
assert queryset.mock_calls == chained.call_list()
assert result is expected_result
开发者ID:brianmay,项目名称:spud,代码行数:30,代码来源:test_search.py
示例11: test_notification_rate_limit2
def test_notification_rate_limit2(self, mock_retry, mock_summ, mock_delay,
verify_signature_mock, debug_mock):
""" Test that the notification task rate limit errors ok """
# Check that we fail gracefully when we hit the rate limit
mock_delay.side_effect = lambda arg: process_notification(arg)
resp = MagicMock()
resp.headers = {'x-ratelimit-reset': 1404298869}
exc = misfit_exceptions.MisfitRateLimitError(429, '', resp)
mock_summ.side_effect = exc
mock_retry.side_effect = Exception
with HTTMock(JsonMock().goal_http,
JsonMock().profile_http,
JsonMock('summary_detail').summary_http):
try:
content = json.dumps(self.notification_content).encode('utf8')
self.client.post(reverse('misfit-notification'), data=content,
content_type='application/json')
assert False, 'We should have raised an exception'
except Exception:
assert True
mock_delay.assert_called_once_with(content)
mock_summ.assert_called_once_with(
detail=True,
end_date=datetime.date(2014, 10, 8),
start_date=datetime.date(2014, 10, 5))
mock_retry.assert_called_once_with(countdown=549)
eq_(Goal.objects.filter(user=self.user).count(), 2)
eq_(Profile.objects.filter(user=self.user).count(), 1)
eq_(Summary.objects.filter(user=self.user).count(), 0)
开发者ID:orcasgit,项目名称:django-misfit,代码行数:29,代码来源:test_tasks.py
示例12: test_poll_processes_events
def test_poll_processes_events(self):
channel = MagicMock()
channel._handle_events = MagicMock()
self.engine._channels = {1: channel}
self.engine._poller.poll = MagicMock(return_value={1:Engine.ALL_EVENTS})
self.engine.poll(0.02)
channel._handle_events.assert_called_once_with(Engine.ALL_EVENTS)
开发者ID:larbing,项目名称:pants,代码行数:7,代码来源:test_engine.py
示例13: test_systemexit_during_deferred_processing_is_raised
def test_systemexit_during_deferred_processing_is_raised(self):
defer = MagicMock()
defer.function = MagicMock(side_effect=SystemExit)
defer.requeue = False
defer.end = self.engine.latest_poll_time - 1
self.engine._deferreds.append(defer)
self.assertRaises(SystemExit, self.engine.poll, 0.02)
开发者ID:larbing,项目名称:pants,代码行数:7,代码来源:test_engine.py
示例14: test_keyboardinterrupt_during_deferred_processing_is_raised
def test_keyboardinterrupt_during_deferred_processing_is_raised(self):
defer = MagicMock()
defer.function = MagicMock(side_effect=KeyboardInterrupt)
defer.requeue = False
defer.end = self.engine.latest_poll_time - 1
self.engine._deferreds.append(defer)
self.assertRaises(KeyboardInterrupt, self.engine.poll, 0.02)
开发者ID:larbing,项目名称:pants,代码行数:7,代码来源:test_engine.py
示例15: test_getattr_with_correct_path
def test_getattr_with_correct_path(self):
mocked_repo = MagicMock()
mocked_first = MagicMock()
mocked_last = MagicMock()
mocked_first.return_value = "tomorrow"
mocked_last.return_value = "tomorrow"
mocked_repo.get_commit_dates.return_value = ['/']
with patch('gitfs.views.history.lru_cache') as mocked_cache:
mocked_cache.__call__ = lambda f: f
history = HistoryView(repo=mocked_repo, uid=1, gid=1,
mount_time="now")
history._get_first_commit_time = mocked_first
history._get_last_commit_time = mocked_last
result = history.getattr("/", 1)
asserted_result = {
'st_uid': 1,
'st_gid': 1,
'st_ctime': "tomorrow",
'st_mtime': "tomorrow",
'st_nlink': 2,
'st_mode': S_IFDIR | 0o555,
}
assert asserted_result == result
开发者ID:HWL-RobAt,项目名称:gitfs,代码行数:26,代码来源:test_history.py
示例16: test_rename
def test_rename(self):
mocked_re = MagicMock()
mocked_index = MagicMock()
mocked_os = MagicMock()
mocked_result = MagicMock()
mocked_result.rename.return_value = True
mocked_re.sub.return_value = "new"
mocked_os.path.split.return_value = [1, 1]
with patch.multiple('gitfs.views.current', re=mocked_re,
os=mocked_os):
from gitfs.views import current as current_view
old_rename = current_view.PassthroughView.rename
current_view.PassthroughView.rename = lambda self, old, new: True
current = CurrentView(regex="regex", repo="repo",
repo_path="repo_path",
ignore=CachedIgnore())
current._stage = mocked_index
result = current.rename("old", "new")
assert result is True
mocked_index.assert_called_once_with(**{
'remove': 1,
'add': "new",
"message": "Rename old to new"
})
mocked_os.path.split.assert_called_once_with("old")
current_view.PassthroughView.rename = old_rename
开发者ID:Marius786,项目名称:gitfs,代码行数:30,代码来源:test_current.py
示例17: get_group_with_posting_members
def get_group_with_posting_members(members):
'A helper function to generate groups to test'
retval = MagicMock()
# --=mpj17=-- I am not proud of this next line
gp = retval.site_root().ListManager.get_list().getProperty
gp.return_value = members
return retval
开发者ID:groupserver,项目名称:gs.group.type.announcement,代码行数:7,代码来源:canpostrules.py
示例18: test_reap_tmp_images
def test_reap_tmp_images(self, _os_datastore_path, _uuid):
""" Test that stray images are found and deleted by the reaper """
def _fake_ds_folder(datastore, folder):
return "%s__%s" % (datastore, folder)
ds = MagicMock()
ds.id = "dsid"
ds.type = DatastoreType.EXT3
# In a random transient directory, set up a directory to act as the
# tmp images folder and to contain a stray image folder with a file.
tmpdir = file_util.mkdtemp(delete=True)
tmp_images_folder = _fake_ds_folder(ds.id, TMP_IMAGE_FOLDER_NAME)
tmp_images_dir = os.path.join(tmpdir, tmp_images_folder)
tmp_image_dir = os.path.join(tmp_images_dir, "stray_image")
os.mkdir(tmp_images_dir)
os.mkdir(tmp_image_dir)
(fd, path) = tempfile.mkstemp(prefix='strayimage_', dir=tmp_image_dir)
self.assertTrue(os.path.exists(path))
def _fake_os_datastore_path(datastore, folder):
return os.path.join(tmpdir, _fake_ds_folder(datastore, folder))
_os_datastore_path.side_effect = _fake_os_datastore_path
ds_manager = MagicMock()
ds_manager.get_datastores.return_value = [ds]
image_manager = EsxImageManager(self.vim_client, ds_manager)
image_manager.reap_tmp_images()
# verify stray image is deleted
self.assertFalse(os.path.exists(path))
开发者ID:tomzhang,项目名称:photon-controller,代码行数:34,代码来源:test_esx_image_manager.py
示例19: test_create
def test_create(self, server_proxy, requests):
"""
Test create operation
"""
proxy = MagicMock()
proxy.CreateInfrastructure.return_value = (True, "inf1")
server_proxy.return_value = proxy
options = MagicMock()
options.auth_file = get_abs_path("../../auth.dat")
options.restapi = None
parser = MagicMock()
out = StringIO()
oldstdout = sys.stdout
sys.stdout = out
res = main("create", options, [get_abs_path("../files/test.radl")], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("Infrastructure successfully created with ID: inf1", output)
sys.stdout = oldstdout
out = StringIO()
sys.stdout = out
options.xmlrpc = None
options.restapi = "https://localhost:8800"
requests.side_effect = self.get_response
res = main("create", options, [get_abs_path("../files/test.radl")], parser)
self.assertEquals(res, True)
output = out.getvalue().strip()
self.assertIn("Infrastructure successfully created with ID: inf1", output)
sys.stdout = oldstdout
开发者ID:grycap,项目名称:im-client,代码行数:31,代码来源:test_client.py
示例20: test_redirect_to_course_position
def test_redirect_to_course_position(self):
mock_module = MagicMock()
mock_module.descriptor.id = 'Underwater Basketweaving'
mock_module.position = 3
mock_module.get_display_items.return_value = []
self.assertRaises(Http404, views.redirect_to_course_position,
mock_module, views.CONTENT_DEPTH)
开发者ID:HowestX,项目名称:edx-platform,代码行数:7,代码来源:test_views.py
注:本文中的mock.MagicMock类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论