本文整理汇总了Python中mock.Mock类的典型用法代码示例。如果您正苦于以下问题:Python Mock类的具体用法?Python Mock怎么用?Python Mock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Mock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_or_create_sheet_gets_existing_sheet
def test_get_or_create_sheet_gets_existing_sheet():
("XL backend should create a new sheet when a sheet of that name"
" does not exist yet")
# Given a mocked workbook and XL backend with one sheet
workbook = Mock()
sheet = Mock()
sheet.name = 'awesomesheet'
sheet.rows = {0: 'stuff', 1: 'more stuff'}
class MyXL(XL):
def get_sheets(self):
return [sheet]
xl_backend = MyXL(workbook=workbook)
# When I call get_or_create_sheet of `awesome sheet1
current_sheet, current_row = xl_backend.get_or_create_sheet('awesomesheet')
# Then workbook.add_sheet should not have been called
workbook.add_sheet.called.should.be.false
# And the current sheet is equal to the mocked sheet
current_sheet.should.equal(sheet)
# And current_row should be 1
current_row.should.equal(1)
示例2: get_backup_file
def get_backup_file(self):
file = Mock()
file.platform = amo.PLATFORM_ALL.id
file.latest_xpi_url.return_value = 'xpi.backup'
file.get_url_path.return_value = 'xpi.backup.url'
file.status = amo.STATUS_PUBLIC
return file
示例3: test_getattr_consults_schema_item_default_factory_with_context
def test_getattr_consults_schema_item_default_factory_with_context(self):
content = Item()
content.id = u"id"
content.portal_type = u"testtype"
from zope.interface import provider
from zope.schema.interfaces import IContextAwareDefaultFactory
@provider(IContextAwareDefaultFactory)
def defaultFactory(context):
return u"{0:s}_{1:s}".format(context.id, context.portal_type)
class ISchema(Interface):
foo = zope.schema.TextLine(title=u"foo",
defaultFactory=defaultFactory)
bar = zope.schema.TextLine(title=u"bar")
# FTI mock
fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
fti_mock.lookupSchema = Mock(return_value=ISchema)
self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")
SCHEMA_CACHE.invalidate('testtype')
self.assertEqual(u"id_testtype", content.foo)
self.assertEqual(None, content.bar)
self.assertEqual(u"id", content.id)
self.assertRaises(AttributeError, getattr, content, 'baz')
示例4: test_get_agent_bindings
def test_get_agent_bindings(self, mock_factory):
bind_payload = {'a': 1, 'b': 2}
distributor = {'distributor_type_id': '3838'}
mock_distributor_manager = Mock()
mock_distributor_manager.get_distributor = Mock(return_value=distributor)
mock_distributor_manager.create_bind_payload = Mock(return_value=bind_payload)
mock_factory.repo_distributor_manager = Mock(return_value=mock_distributor_manager)
# test manager
bindings = [
{'consumer_id': '10', 'repo_id': '20', 'distributor_id': '30', 'binding_config': {}},
{'consumer_id': '40', 'repo_id': '50', 'distributor_id': '60', 'binding_config': {}},
]
agent_bindings = AgentManager._bindings(bindings)
# validation
for binding in bindings:
mock_distributor_manager.get_distributor.assert_any_call(
binding['repo_id'], binding['distributor_id'])
mock_distributor_manager.create_bind_payload.assert_any_call(
binding['repo_id'], binding['distributor_id'], binding['binding_config'])
self.assertEqual(len(agent_bindings), 2)
for binding, agent_binding in itertools.izip(bindings, agent_bindings):
self.assertEqual(binding['repo_id'], agent_binding['repo_id'])
self.assertEqual(distributor['distributor_type_id'], agent_binding['type_id'])
self.assertEqual(bind_payload, agent_binding['details'])
示例5: test_annotate_decorator
def test_annotate_decorator(self):
from celery.app.task import Task
class adX(Task):
abstract = True
def run(self, y, z, x):
return y, z, x
check = Mock()
def deco(fun):
def _inner(*args, **kwargs):
check(*args, **kwargs)
return fun(*args, **kwargs)
return _inner
app = Celery(set_as_current=False)
app.conf.CELERY_ANNOTATIONS = {
adX.name: {"@__call__": deco}
}
adX.bind(app)
self.assertIs(adX.app, app)
i = adX()
i(2, 4, x=3)
check.assert_called_with(i, 2, 4, x=3)
i.annotate()
i.annotate()
示例6: test_mysql_mode_locks_unlocks_tables
def test_mysql_mode_locks_unlocks_tables(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen):
mock_get_vol_fs_type.return_value = 'xfs'
mock_get_lvm_info.return_value = {
'volgroup': 'lvm_volgroup',
'srcvol': 'lvm_device',
'snap_path': 'snap_path'}
mock_process = Mock()
mock_process.communicate.return_value = '', ''
mock_process.returncode = 0
mock_popen.return_value = mock_process
backup_opt = Mock()
backup_opt.snapshot = True
backup_opt.lvm_auto_snap = ''
backup_opt.path_to_backup = '/just/a/path'
backup_opt.lvm_dirmount = '/var/mountpoint'
backup_opt.lvm_snapperm = 'ro'
backup_opt.mode = 'mysql'
backup_opt.mysql_db_inst = Mock()
mock_cursor = Mock()
backup_opt.mysql_db_inst.cursor.return_value = mock_cursor
self.assertTrue(lvm.lvm_snap(backup_opt))
first_call = call('FLUSH TABLES WITH READ LOCK')
second_call = call('UNLOCK TABLES')
self.assertEquals(first_call, mock_cursor.execute.call_args_list[0])
self.assertEquals(second_call, mock_cursor.execute.call_args_list[1])
示例7: test_side_effect
def test_side_effect(self):
mock = Mock()
def effect(*args, **kwargs):
raise SystemError('kablooie')
mock.side_effect = effect
self.assertRaises(SystemError, mock, 1, 2, fish=3)
mock.assert_called_with(1, 2, fish=3)
results = [1, 2, 3]
def effect():
return results.pop()
mock.side_effect = effect
self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
"side effect not used correctly")
mock = Mock(side_effect=sentinel.SideEffect)
self.assertEqual(mock.side_effect, sentinel.SideEffect,
"side effect in constructor not used")
def side_effect():
return DEFAULT
mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
self.assertEqual(mock(), sentinel.RETURN)
示例8: test_run
def test_run(self, *mocks):
eddaclient = Mock()
eddaclient._since = 500
def ret_list(args):
return [
{'imageId': 'ami-1', 'instanceId': 'a', 'launchTime': '500',
'tags': [{'key': 'service_name', 'value': 'conversion'}, {'key': 'started_by', 'value': 'john'}]},
{'imageId': 'ami-1', 'instanceId': 'b', 'launchTime': '2000',
'tags': [{'key': 'service_name', 'value': 'router'}]},
{'imageId': 'ami-2', 'instanceId': 'c', 'launchTime': '400'}]
m = Mock()
m.query = Mock(side_effect=ret_list)
eddaclient.clean = Mock(return_value=m)
self.plugin.init(eddaclient, self.config, {'first_seen': {"ami-1": 1000, "ami-2": 400}})
real = self.plugin.run()
expected = [
{'id': 'ami-1', 'plugin_name': 'ami', 'details': [
('a', 500, [{'service_name': 'conversion'}, {'started_by': 'john'}]),
('b', 2000, [{'service_name': 'router'}])]}
]
self.assertEqual(expected, real)
m.query.assert_has_calls([call('/api/v2/view/instances;_expand')])
self.assertEqual(self.plugin.status, {'first_seen': {'ami-1': 500, 'ami-2': 400}})
示例9: test_error_output
def test_error_output(self):
from planterbox import FeatureTestSuite, step
test_feature = """Feature: A Test Feature
Scenario: A Test Scenario
When I fail a test
"""
@step(r'I fail a test')
def fail_test(test):
test.fail('Expected Failure')
mock_world = Mock()
mock_world.fail_test = fail_test
test_suite = FeatureTestSuite(mock_world, test_feature)
test_case = test_suite._tests[0]
def mock_addFailure(result, exc):
self.exc_info = exc
mock_result = Mock(addFailure=Mock(side_effect=mock_addFailure))
test_case.run(mock_result)
formatted = test_case.formatTraceback(self.exc_info)
formatted_lines = formatted.split('\n')
self.assertEqual(formatted_lines[0], 'When I fail a test')
self.assertEqual(formatted_lines[-2],
'AssertionError: Expected Failure')
self.assertEqual(unicode(test_case),
'A Test Scenario (A Test Feature)')
示例10: frame
def frame():
frame = Mock()
f_code = Mock()
f_code.co_filename = 'foo.py'
f_code.co_firstlineno = 23
frame.f_code = f_code
return frame
示例11: test_resource_policy_event_callback
def test_resource_policy_event_callback(self):
event_data = Mock()
event_data.resource_id = 'resource._id'
event_data.resource_type = 'resource.type_'
event_data.resource_name = 'resource.name'
event_data.origin = 'policy._id'
policy_rules = 'policy_rules'
pc = Mock()
pc.get_active_resource_access_policy_rules.return_value = policy_rules
self.governance_controller.policy_client = pc
self.governance_controller.system_actor_user_header = {}
# call resource_policy_event_callback without a PDP
self.governance_controller.resource_policy_event_callback(event_data)
# expect that nothing happened since there was no PDP to update
self.assertEqual(pc.get_active_resource_access_policy_rules.called, False)
#add a pdp
pdp = Mock()
self.governance_controller.policy_decision_point_manager = pdp
self.governance_controller.resource_policy_event_callback(event_data)
# expect that policy rules are retrieved for resource
pc.get_active_resource_access_policy_rules.assert_called_with(event_data.resource_id, headers={})
# expect that pdp is called with new rules
pdp.load_resource_policy_rules.assert_called_with(event_data.resource_id, policy_rules)
示例12: test___init__
def test___init__(self):
manager = Mock()
manager.write_to_completion_cache = Mock(return_value=None)
info_ = {}
robj = base.Resource(manager, info_)
self.assertEqual(0, manager.write_to_completion_cache.call_count)
info_ = {"id": "id-with-less-than-36-char"}
robj = base.Resource(manager, info_)
self.assertEqual(info_["id"], robj.id)
self.assertEqual(0, manager.write_to_completion_cache.call_count)
id_ = "id-with-36-char-"
for i in range(36 - len(id_)):
id_ = id_ + "-"
info_ = {"id": id_}
robj = base.Resource(manager, info_)
self.assertEqual(info_["id"], robj.id)
self.assertEqual(1, manager.write_to_completion_cache.call_count)
info_["name"] = "test-human-id"
# Resource.HUMAN_ID is False
robj = base.Resource(manager, info_)
self.assertEqual(info_["id"], robj.id)
self.assertEqual(None, robj.human_id)
self.assertEqual(2, manager.write_to_completion_cache.call_count)
# base.Resource.HUMAN_ID = True
info_["HUMAN_ID"] = True
robj = base.Resource(manager, info_)
self.assertEqual(info_["id"], robj.id)
self.assertEqual(info_["name"], robj.human_id)
self.assertEqual(4, manager.write_to_completion_cache.call_count)
示例13: setUp
def setUp(self):
super(ManagerListTest, self).setUp()
@contextlib.contextmanager
def completion_cache_mock(*arg, **kwargs):
yield
self.manager = base.Manager()
self.manager.api = Mock()
self.manager.api.client = Mock()
self.response_key = "response_key"
self.data_p = ["p1", "p2"]
self.body_p = {self.response_key: self.data_p}
self.url_p = "test_url_post"
self.manager.api.client.post = Mock(return_value=(self.url_p,
self.body_p))
self.data_g = ["g1", "g2", "g3"]
self.body_g = {self.response_key: self.data_g}
self.url_g = "test_url_get"
self.manager.api.client.get = Mock(return_value=(self.url_g,
self.body_g))
mock = Mock()
mock.side_effect = completion_cache_mock
self.manager.completion_cache = mock
示例14: test__create
def test__create(self):
manager = base.Manager()
manager.api = Mock()
manager.api.client = Mock()
response_key = "response_key"
data_ = "test-data"
body_ = {response_key: data_}
url_ = "test_url_post"
manager.api.client.post = Mock(return_value=(url_, body_))
return_raw = True
r = manager._create(url_, body_, response_key, return_raw)
self.assertEqual(data_, r)
return_raw = False
@contextlib.contextmanager
def completion_cache_mock(*arg, **kwargs):
yield
mock = Mock()
mock.side_effect = completion_cache_mock
manager.completion_cache = mock
manager.resource_class = Mock(return_value="test-class")
r = manager._create(url_, body_, response_key, return_raw)
self.assertEqual("test-class", r)
示例15: test_has_object_permission_user
def test_has_object_permission_user(self):
self.request.user = self.user
self.request.amo_user = self.request.user
obj = Mock()
obj.user = self.user
eq_(self.permission.has_object_permission(self.request, 'myview', obj),
True)