本文整理汇总了Python中minimock.mock函数的典型用法代码示例。如果您正苦于以下问题:Python mock函数的具体用法?Python mock怎么用?Python mock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了mock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
super(StartStateMachineTests, self).setUp()
filename = 'test-TaskQueueFSMTests.yaml'
setUpByFilename(self, filename)
self.machineName = getMachineNameByFilename(filename)
self.mockQueue = TaskQueueDouble()
mock(name='Queue.add', returns_func=self.mockQueue.add, tracker=None)
示例2: test_cb
def test_cb(self):
"""Callback from proxy"""
minimock.mock('flickrapi.FlickrAPI.get_token_part_one', returns=('token', 'frob'))
def _bad_api(auth_response):
raise FlickrError('Error: 108: Invalid frob')
minimock.mock('flickrapi.FlickrAPI.get_token_part_two',
returns_func=_bad_api)
self.hit_cb = False
def _cb(proxy, perms, token, frob):
assert perms == 'write'
assert token == 'token'
assert frob == 'frob'
if self.hit_cb:
return True
else:
self.hit_cb = True
assert_raises(FlickrError, get_proxy, wait_callback=_cb)
assert self.hit_cb
示例3: setUp
def setUp(self):
self.maxDiff = None
run.Redis = fakeredis.FakeRedis
self.r = fakeredis.FakeStrictRedis()
self.tt = TraceTracker()
self.return_value = ''
mock('run.analyse', tracker=self.tt, returns_func=self.get_return_value)
示例4: setUp
def setUp(self):
self.api = MediaMosaAPI('http://video.example.com')
self.tt = TraceTracker()
mock('self.api.session', tracker=self.tt)
self.response = Mock('requests.Response')
self.response.status_code = 200
self.api.session.get.mock_returns = self.response
示例5: mock_send_email
def mock_send_email(request):
"""Mock up smtplib.SMTP and keyring.get_password for send_email."""
import smtplib
import keyring
# capture all calls into mock objects
# (instead of letting output go to stdout)
tracker = minimock.TraceTracker()
# mock up smtplib
minimock.mock('smtplib.SMTP',
returns=minimock.Mock('smtp_connection', tracker=tracker),
tracker=tracker)
# mock up keyring.get_password
minimock.mock('keyring.get_password',
returns='send_email_secret',
tracker=tracker)
def finalizer():
# restore all objects in global module state that minimock replaced
minimock.restore()
request.addfinalizer(finalizer)
return tracker
示例6: setUp
def setUp(self):
self.api = MediaMosaAPI('http://video.example.com')
self.tt = TraceTracker()
mock('self.api.session', tracker=self.tt)
self.response = Mock('requests.Response')
self.response.status_code = 200
self.api.session.get.mock_returns = self.response
self.item_dict = {u'is_original_file': u'FALSE',
u'is_streamable': u'FALSE', u'is_downloadable': u'FALSE',
u'app_id': u'2', u'transcode_inherits_acl': u'TRUE',
u'tag': '', u'response_metafile_available': u'TRUE',
u'mediafile_id_source': u'u2ilZNiHdl7iNUdexL7BcFMY',
u'asset_id': u'g1QkoSmSeHdWfGkMKlOlldLn',
u'mediafile_id': u'Md2RgaUEVFhfJMeUIbwPOMei',
u'transcode_profile_id': u'17',
u'filename': u'Sintel_Trailer1.1080p.DivX_Plus_HD.mp4',
u'is_protected': u'FALSE', u'ega_stream_url': '',
u'file_extension': u'mp4', 'metadata': {
u'is_inserted_md': u'FALSE', u'fps': u'24', u'bpp': u'0.31',
u'file_duration': u'00:00:52.20', u'colorspace': u'yuv420p',
u'container_type': u'mov;mp4;m4a;3gp;3g2;mj2', u'height': u'478',
u'channels': u'stereo', u'width': u'852', u'sample_rate': u'44100',
u'filesize': u'20543936', u'audio_codec': u'aac',
u'video_codec': u'h264', u'is_hinted': u'TRUE',
u'bitrate': u'3012', u'mime_type': u'video/mp4'},
u'ega_download_url': '', u'ega_play_url': '', u'tool': u'ffmpeg',
u'response_plain_available': u'TRUE', u'owner_id': u'krkeppen',
u'response_object_available': u'TRUE',
u'created': u'2012-07-05 11:38:14',
u'changed': u'2012-07-05 11:38:14', u'uri': '',
u'is_still': u'FALSE', u'command':
u'audiocodec:libfaac;audiobitrate:128000;audiosamplingrate:44100;audiochannels:2;videocodec:libx264;videopreset_quality:slow;videopreset_profile:baseline;2_pass_h264_encoding:2;videobitrate:800000;qmax:17;size:852x480;maintain_aspect_ratio:yes',
u'group_id': ''}
示例7: mock_set_password
def mock_set_password(request):
"""Mock up getpass.getpass and keyring.set_password for set_password."""
import getpass
import keyring
# capture all calls into mock objects
# (instead of letting output go to stdout)
tracker = minimock.TraceTracker()
# mock up getpass.getpass
minimock.mock('getpass.getpass',
returns='set_password_secret',
tracker=tracker)
# mock up keyring.set_password
minimock.mock('keyring.set_password',
tracker=tracker)
def finalizer():
# restore all objects in global module state that minimock replaced
minimock.restore()
request.addfinalizer(finalizer)
return tracker
示例8: setUp
def setUp(self):
"""
Nadgers haystack SearchView so that:
- we don't need a search backend
- response is a TemplateResponse, not and HttpResponse (so
that in tests we can check context contents)
"""
import django.template.response
import haystack.views
# SearchView passes a RequestContext to render_to_response,
# but we want to be able to get hold of the request itself
# (to pass on to TemplateResponse).
class RequestContext(django.template.response.RequestContext):
def __init__(self, request):
super(RequestContext, self).__init__(request)
self.request = request
def render_to_response(template, context, context_instance):
return django.template.response.TemplateResponse(
request = context_instance.request,
template = template,
context = context)
self.context_class = RequestContext
minimock.mock("haystack.views.render_to_response", returns_func=render_to_response, tracker=None)
minimock.mock("haystack.views.SearchView.get_results", returns_func=self.get_results, tracker=None)
self.org = OrganizationFactory()
示例9: test_ok
def test_ok(self):
"""OK proxy"""
minimock.mock('flickrapi.FlickrAPI.get_token_part_one')
minimock.mock('flickrapi.FlickrAPI.get_token_part_two', returns=True)
assert isinstance(get_proxy(), flickrapi.FlickrAPI)
示例10: test_offline
def test_offline(self):
"""Proxy when offline"""
import urllib
minimock.mock('urllib.urlopen', raises=IOError)
get_proxy()
示例11: test_multipleLevelMountPointExtraPathInfo
def test_multipleLevelMountPointExtraPathInfo(self):
url = '/other/mount/point/fsm/MyMachine/state1/to/state2'
request = buildRequest(path=url)
from fantasm import config
mock('config.currentConfiguration', returns=MockConfigRootUrl('/other/mount/point/'), tracker=None)
name = getMachineNameFromRequest(request)
self.assertEquals(name, 'MyMachine')
示例12: test_users_from_url
def test_users_from_url(self):
mock('obswatch.http_GET', tracker=self.tt,
returns=StringIO('''<?xml version="1.0" encoding="UTF-8"?>
<project name="superkde" created="2005-01-01T00:00:02+01:00" updated="2007-01-19T10:44:45+01:00">
<title>SuperKDE</title>
<description>SuperKDE is a heavily tuned version of KDE.</description>
<link project="openSUSE:11.2:Update" />
<link project="openSUSE:11.2" />
<person role="maintainer" userid="Geeko"/>
<person role="maintainer" userid="BrownGeeko"/>
<group role="reviewer" groupid="release_team"/>
<build>
<disable />
</build>
<repository name="kde4:factory" rebuild="transitive">
<path project="kde4" repository="factory"/>
<arch>i386</arch>
<arch>x86_64</arch>
</repository>
</project>'''))
mock('obswatch.get_user_email', returns='[email protected]')
result = obswatch.get_users_from_url('%ssource/superkde/_meta' %
obswatch.APIURL)
assert_same_trace(self.tt, """Called obswatch.http_GET(
'%ssource/superkde/_meta')""" % obswatch.APIURL)
self.assertEqual(len(result), 2)
self.assertEqual(result['Geeko'], '[email protected]')
self.assertEqual(result['BrownGeeko'], '[email protected]')
示例13: setUp
def setUp(self):
super(FanInMergeJoinDispatchTest, self).setUp()
setUpByString(self, FAN_IN_MACHINE, machineName='FanInMachine', instanceName='foo')
mock('config.currentConfiguration', returns=self.currentConfig, tracker=None)
for i in range(20):
SimpleModel(key_name='%d' % i).put()
memcache.set('calls', 0)
memcache.set('raise', False)
context = self.factory.createFSMInstance(self.machineConfig.name, instanceName='foo')
context[constants.STEPS_PARAM] = 1
obj = TemporaryStateObject()
obj[constants.TASK_NAME_PARAM] = 'taskName'
obj[constants.RETRY_COUNT_PARAM] = 0
self.context = None
self.obj = None
random.seed(0)
context.dispatch('pseudo-init', obj) # write down a work package
self.index = context[constants.INDEX_PARAM]
self.assertEqual(1, _FantasmFanIn.all().count())
self.assertEqual('foo--InitialState--ok--FanInState--step-2-2957927341',
_FantasmFanIn.all().get().workIndex)
示例14: testTripwireTripped
def testTripwireTripped(self):
'''Tripwire test, tripped'''
tt = minimock.TraceTracker()
minimock.mock('tripwire.sendEmail', tracker=tt)
datevalue = datetime.date(2011, 8, 16)
dtmock = minimock.Mock('datetime.date')
minimock.mock('datetime.date', mock_obj=dtmock)
dtmock.mock_returns = dtmock
dtmock.today.mock_returns = datevalue
dtmock.today.mock_tracker = tt
#can't just do minimock.mock('datetime.date.today', returns=datevalue, tracker=tt)
#because datetime.date is in an extension (ie, not native python)
#Add another value to make the tripwire trip
self.session.add(model.MeasuredValue(6))
self.session.commit()
tripwire.main()
expected = r'''Called datetime.date.today()
Called tripwire.sendEmail(3.0, datetime.date(2011, 8, 16))'''
self.assertTrue(tt.check(expected), tt.diff(expected))
minimock.restore()
示例15: setUp
def setUp(self):
from netprintbox.data import OAuthRequestToken
super(DropboxServiceSetupTest, self).setUp()
token = 'oauth_token=token&oauth_token_secret=secret'
token = OAuthRequestToken(key=self.key, token=token)
token.put()
class client(object):
@staticmethod
def account_info():
return {'uid': self.uid,
'email': 'email',
'display_name': 'display_name',
'country': 'JP',
}
class session(object):
@staticmethod
def obtain_access_token(request_token):
pass
class token(object):
key = 'access_key'
secret = 'access_secret'
import dropbox.client
import dropbox.session
mock('dropbox.client.DropboxClient', returns=client)
mock('dropbox.session.DropboxSession', returns=session)