本文整理汇总了Python中mock.MagicMock类的典型用法代码示例。如果您正苦于以下问题:Python MagicMock类的具体用法?Python MagicMock怎么用?Python MagicMock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MagicMock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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'])
示例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
示例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
示例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])
示例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
示例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
示例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)
示例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
示例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)
示例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)
示例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)
示例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)
示例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