本文整理汇总了Python中mocker.Mocker.patch方法的典型用法代码示例。如果您正苦于以下问题:Python Mocker.patch方法的具体用法?Python Mocker.patch怎么用?Python Mocker.patch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mocker.Mocker
的用法示例。
在下文中一共展示了Mocker.patch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BundleDeserializationTests
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
class BundleDeserializationTests(TestCaseWithScenarios):
scenarios = [
('dummy_import_failure', {
'pathname': '/public/personal/admin/',
'is_public': 'true',
'content': 'bogus',
'content_filename': 'test1.json',
}),
]
def setUp(self):
super(BundleDeserializationTests, self).setUp()
self.bundle = fixtures.create_bundle(
self.pathname, self.content, self.content_filename)
self.mocker = Mocker()
def tearDown(self):
self.bundle.delete_files()
self.mocker.restore()
self.mocker.verify()
super(BundleDeserializationTests, self).tearDown()
def test_deserialize_failure_leaves_trace(self):
mock = self.mocker.patch(self.bundle)
expect(mock._do_deserialize(False)).throw(Exception("boom"))
self.mocker.replay()
self.bundle.deserialize(False)
self.assertFalse(self.bundle.is_deserialized)
self.assertEqual(self.bundle.deserialization_error.error_message, "boom")
def test_deserialize_ignores_deserialized_bundles(self):
# just reply as we're not using mocker in this test case
self.mocker.replay()
self.bundle.is_deserialized = True
self.bundle.deserialize(False)
self.assertTrue(self.bundle.is_deserialized)
def test_deserialize_sets_is_serialized_on_success(self):
mock = self.mocker.patch(self.bundle)
expect(mock._do_deserialize(False))
self.mocker.replay()
self.bundle.deserialize(False)
self.assertTrue(self.bundle.is_deserialized)
def test_deserialize_clears_old_error_on_success(self):
BundleDeserializationError.objects.create(
bundle=self.bundle,
error_message="not important").save()
mock = self.mocker.patch(self.bundle)
expect(mock._do_deserialize(False))
self.mocker.replay()
self.bundle.deserialize(False)
# note we cannot check for self.bundle.deserialization_error
# directly due to the way django handles operations that affect
# existing instances (it does not touch them like storm would
# IIRC).
self.assertRaises(
BundleDeserializationError.DoesNotExist,
BundleDeserializationError.objects.get, bundle=self.bundle)
示例2: test_template_context_does_not_have_RequestContext_things
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_template_context_does_not_have_RequestContext_things(self):
mocker = Mocker()
report = mocker.patch(DataReport())
expect(report._get_raw_html()).result("{{MEDIA_URL}}")
with mocker:
observed = report.get_html()
expected = ""
self.assertEqual(observed, expected)
示例3: test_template_context_has_API_URL
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_template_context_has_API_URL(self):
mocker = Mocker()
report = mocker.patch(DataReport())
expect(report._get_raw_html()).result("{{API_URL}}")
with mocker:
observed = report.get_html()
expected = '/RPC2'
self.assertEqual(observed, expected)
示例4: test_converte2opl
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_converte2opl(self):
linhas_arquivo_entrada = [['4','3'],['0','1','2','4'],['0','2','4','8'],['1','3','6','12'],['0','3']]
linhas_arquivo_saida_esperada = ['s = "0";','d = "3";',
'A = {<"0","1",[2,4]>,\n<"0","2",[4,8]>,\n<"1","3",[6,12]>};']
converte2opl = Converte2OPL('arquivo.txt','arquivo_saida.txt')
mocker = Mocker()
obj = mocker.patch(converte2opl)
obj.le_arquivo_entrada()
mocker.result(linhas_arquivo_entrada)
mocker.replay()
obj.converte()
self.assertListEqual(linhas_arquivo_saida_esperada,obj.linhas_arquivo_saida)
示例5: test_getCategories_HTTPError
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_getCategories_HTTPError(self):
from collective.flattr.browser.flattr import Flattr
mocker = Mocker()
view = Flattr(self.portal, self.layer['request'])
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('[{"id": "text", "text": "Text"}, {"id": "images", "text": "Images"}]', error=True))
with mocker:
ret = view.getCategories()
self.failUnless(isinstance(ret, list))
self.assertEquals(len(ret), 0)
示例6: test_getCategories
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_getCategories(self):
from collective.flattr.browser.flattr import Flattr
mocker = Mocker()
view = Flattr(self.portal, self.layer['request'])
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('[{"id": "text", "text": "Text"}, {"id": "images", "text": "Images"}]'))
with mocker:
ret = view.getCategories()
self.failUnless(isinstance(ret, list))
self.assertEquals(len(ret), 2)
self.assertEquals(ret[0], {'id': u'text',
'text': u'Text'})
self.assertEquals(ret[1], {'id': u'images',
'text': u'Images'})
示例7: test_getLanguages
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_getLanguages(self):
from collective.flattr.browser.flattr import Flattr
mocker = Mocker()
view = Flattr(self.portal, self.layer['request'])
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('[{"id": "de_DE", "text": "German"}, {"id": "en_US", "text": "English"}]'))
with mocker:
ret = view.getLanguages()
self.failUnless(isinstance(ret, list))
self.assertEquals(len(ret), 2)
self.assertEquals(ret[0], {'id': u'de_DE',
'text': u'German'})
self.assertEquals(ret[1], {'id': u'en_US',
'text': u'English'})
示例8: test_updateThing_HTTPError
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_updateThing_HTTPError(self):
from collective.flattr.browser.flattr import Flattr
mocker = Mocker()
view = Flattr(self.portal, self.layer['request'])
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('{ "message": "ok", "description": "Thing was updated successfully" }', verify_data = lambda x: x.get_full_url().endswith('431547') and x.get_data() == 'title=Hello&hidden=True&description=desc&category=cat&language=de_DE&tags=a%2Cb&_method=patch', error=True))
with mocker:
ret = view.updateThing(u'Hello',
431547,
description='desc',
category='cat',
language='de_DE',
tags='a,b',
hidden=True)
self.assertEquals(ret, {})
示例9: test_createThing_HTTPError
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_createThing_HTTPError(self):
from collective.flattr.browser.flattr import Flattr
mocker = Mocker()
view = Flattr(self.portal, self.layer['request'])
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('{ "id": 431547, "link": "https://api.flattr.dev/rest/v2/things/431547", "message": "ok", "description": "Thing was created successfully" }', verify_data = lambda x: x.get_data() == 'title=Hello&hidden=True&url=http%3A%2F%2Flocalhost%2F&description=desc&category=cat&language=de_DE&tags=a%2Cb', error=True))
with mocker:
ret = view.createThing(u'Hello',
url=u'http://localhost/',
description='desc',
category='cat',
language='de_DE',
tags='a,b',
hidden=True)
self.assertEquals(ret, {})
示例10: test_getAccessToken
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_getAccessToken(self):
reg = getUtility(IRegistry).forInterface(ICollectiveFlattr)
reg.customer_key = u'customer'
reg.customer_secret = u'secret'
with as_manager(self.portal) as view:
mocker = Mocker()
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('{"access_token":"NEW_ACCESS_TOKEN","token_type":"bearer"}',
verify_data=lambda x: x.get_full_url()==u'https://flattr.com/oauth/token' and x.data=='{"redirect_uri": "http://nohost/plone/collective_flattr", "code": 1234, "grant_type": "authorization_code"}' and x.headers=={'Content-type': 'application/json'}))
obj.opener
mocker.result(MockOpener('{"error":"invalid_request","error_description":"error desc"}',
error=True,
verify_data=lambda x: x.get_full_url()==u'https://flattr.com/oauth/token' and x.data=='{"redirect_uri": "http://nohost/plone/collective_flattr", "code": 1234, "grant_type": "authorization_code"}' and x.headers=={'Content-type': 'application/json'}
))
with mocker:
ret = view.getAccessToken(1234)
self.failUnless(u'error' not in ret)
self.failUnless(u'error_description' not in ret)
self.failUnless(u'access_token' in ret)
self.failUnless(u'token_type' in ret)
self.assertEquals(ret['access_token'], u'NEW_ACCESS_TOKEN')
self.assertEquals(ret['token_type'], u'bearer')
# second call get an inner status of != 200 and
# will return None
ret = view.getAccessToken(1234)
self.failUnless(u'error' in ret)
self.failUnless(u'error_description' in ret)
self.failUnless(u'access_token' not in ret)
self.failUnless(u'token_type' not in ret)
self.assertEquals(ret['error'], u'invalid_request')
self.assertEquals(ret['error_description'], u'error desc')
示例11: test_getThing_with_next
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_getThing_with_next(self):
from collective.flattr.browser.flattr import Flattr
mocker = Mocker()
view = Flattr(self.portal, self.layer['request'])
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('[ { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 }, { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2} ]', verify_data=lambda x: 'count=30&page=' in x.get_data()))
mocker.count(2)
# if the same thing is called twice, it is called for the first page
# and again for the second page. So there is a result, what means that
# there is a next page
with mocker:
ret = view.getThings()
self.failUnless(u'data' in ret)
self.failUnless(u'next_page' in ret)
self.assertTrue(ret['next_page'])
self.assertEquals(ret['data'][0], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 })
self.assertEquals(ret['data'][1], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2})
示例12: test_getThing
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test_getThing(self):
from collective.flattr.browser.flattr import Flattr
mocker = Mocker()
view = Flattr(self.portal, self.layer['request'])
def test_func(x):
return 'count=30&page=' in x.get_data()
obj = mocker.patch(view)
obj.opener
mocker.result(MockOpener('[ { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 }, { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2} ]', verify_data=test_func))
obj.opener
mocker.result(MockOpener('', verify_data=test_func, error=True))
with mocker:
ret = view.getThings()
self.failUnless(u'data' in ret)
self.failUnless(u'next_page' in ret)
self.assertFalse(ret['next_page'])
self.assertEquals(ret['data'][0], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/1", "link": "https://flattr.dev/thing/1", "id": 1 })
self.assertEquals(ret['data'][1], { "type": "thing", "resource": "https://api.flattr.dev/rest/v2/things/2", "link": "https://flattr.dev/thing/2", "id": 2})
示例13: test
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
def test(eds_config, ud_is_none=False):
ac = Application()
m = Mocker()
df_class = m.replace("editxt.application.NSUserDefaults")
eds = []
mac = m.patch(ac)
mac.iter_editors() >> eds
settings = []
for i, ed_config in enumerate(eds_config):
ed = m.mock(Editor)
eds.append(ed)
serial = ed.serialize() >> (("<serial %s>" % i)
if ed_config else None)
if serial:
settings.append(serial)
ud = m.mock(NSUserDefaults)
if ud_is_none:
df_class.standardUserDefaults() >> ud
args = ()
else:
args = (ud,)
ud.setObject_forKey_(settings, const.WINDOW_CONTROLLERS_DEFAULTS_KEY)
with m:
ac.save_open_projects(*args)
示例14: TestControlPanel
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
class TestControlPanel(unittest.TestCase):
layer = COLLECTIVE_FLATTR_INTEGRATION_TESTING
def setUp(self):
self.portal = self.layer['portal']
setRoles(self.portal, TEST_USER_ID, ('Manager',))
self.reg = getUtility(IRegistry).forInterface(ICollectiveFlattr)
self.mocker = None
alsoProvides(self.layer['request'], IFormLayer)
def tearDown(self):
if self.mocker:
self.mocker.reset()
def test_test_access_token_fail(self):
self.reg.access_token = u'NEW'
self.reg.access_token_type = u'Bearer'
self.mocker = Mocker()
flattr_view = self.mocker.patch(Flattr)
flattr_view.opener
self.mocker.result(MockOpener('{"error": "unauthorized", "error_description": "Hello World"}', error=True, verify_data=lambda x: x.get_full_url()==u'https://api.flattr.com/rest/v2/user' and x.headers=={'Content-type':'application/json'}))
self.layer['request'].form = {'form.button.TestAccessToken': True}
with controlpanel(self.portal, self.layer['request']) as view:
with self.mocker:
ret = view()
self.failUnless(u'Configured access token does not work :(' in ret)
self.failUnless(u'error' in ret)
self.assertEquals(view.test_access_token,
u'Configured access token does not work :(')
def test_test_access_token_success(self):
self.reg.access_token = u'NEW'
self.reg.access_token_type = u'Bearer'
self.reg.customer_key = u'Key'
self.reg.customer_secret = u'Secret'
self.mocker = Mocker()
flattr_view = self.mocker.patch(Flattr)
flattr_view.opener
self.mocker.result(MockOpener('{"username": "Hello World"}', verify_data=lambda x: x.get_full_url()==u'https://api.flattr.com/rest/v2/user' and x.headers=={'Content-type':'application/json'}))
self.layer['request'].form = {'form.button.TestAccessToken': True}
with controlpanel(self.portal, self.layer['request']) as view:
with self.mocker:
ret = view()
self.failUnless(u'username' in ret)
self.failUnless(u'Hello World' in ret)
self.failUnless(u'username' in view.test_access_token)
self.failUnless(u'Hello World' in view.test_access_token)
# call again. without access token
self.reg.access_token = u''
self.reg.access_token_type = u''
ret = view()
self.failUnless(u'error' in ret)
self.failUnless(u'No access token configured' in ret)
def test_authenticate(self):
self.reg.customer_key = u'Key'
self.reg.customer_secret = u'Secret'
self.layer['request'].form = {'form.button.AcquireToken': True}
with controlpanel(self.portal, self.layer['request']) as view:
self.reg.customer_key = u''
ret = view()
self.failUnless(u'error' in ret)
self.failUnless(u'Unable to create authorize '
'url. consumer and consumer_secret not configured :(' in ret)
# call again for success
self.reg.customer_key = u'consumer'
ret = view()
self.assertEquals(ret, None)
redirect = self.layer['request'].response.headers['location']
self.failUnless(redirect.startswith(self.reg.authorize_url))
self.failUnless(u'collective_flattr' in redirect)
self.failUnless(u'client_id=consumer' in redirect)
self.failUnless(u'redirect_uri' in redirect)
self.failUnless(u'scope=thing' in redirect)
self.failUnless(u'response_type=code' in redirect)
def test_clear_access_token(self):
self.layer['request'].form = {'form.button.ClearAccessToken': True}
#.........这里部分代码省略.........
示例15: OAuthTwitterTest
# 需要导入模块: from mocker import Mocker [as 别名]
# 或者: from mocker.Mocker import patch [as 别名]
#.........这里部分代码省略.........
'twitter_id': '1'})
self.assertEqual(response.status_code, 200)
self.assertRaises(TwitterUser.DoesNotExist,
TwitterUser.objects.get, user=self.twitter)
def test_association_user_revoked(self):
# User visits associate after revoking their Twitter credentials.
self.assertTrue(self.twitter.twitter)
self.assertTrue(self.client.login(username=self.twitter.username,
password=self.twitter.username))
Api = self.mocker.replace(TwitterApi)
Api(ANY).GetUserInfo()
self.mocker.throw(HTTPError('url', 401, '', {}, None))
with self.mocker:
# User goes off to Twitter and gets redirected back to callback
session = self.client.session
session[REQUEST_KEY] = TOKEN.to_string()
session.save()
response = self.client.get(reverse('twitter_associate'))
self.assertEqual(response.status_code, 200)
def test_callback(self):
# User goes directly to the callback page.
response = self.client.get(reverse(oauthtwitter.callback))
self.assertEqual(response['Location'],
'http://testserver%s' % settings.LOGIN_URL)
# User goes directly to the callback page. but tampers with oauth_token
response = self.client.get(reverse(oauthtwitter.callback),
{'oauth_token': 'bad'})
self.assertEqual(response['Location'],
'http://testserver%s' % settings.LOGIN_URL)
# User comes in through Twitter OAuth, but tampers with oauth_token
o = self.mocker.patch(oauthtwitter)
request = self.mocker.mock()
request.GET
self.mocker.result({'oauth_token': 'bad'})
request.session
self.mocker.result({})
self.mocker.count(1, None)
request.twitter_request_token
self.mocker.result(TOKEN)
# New user comes in through Twitter OAuth
request.GET
self.mocker.result({'oauth_token': 'a'})
request.twitter_request_token
self.mocker.result(TOKEN)
Api = self.mocker.replace(TwitterApi)
Api(TOKEN).getAccessToken()
self.mocker.result(TOKEN)
request.twitter_access_token = ANY
request.user
self.mocker.result(AnonymousUser())
userinfo = self.mocker.mock()
cui = self.mocker.replace(cached_user_info)
cui(request, TOKEN)
self.mocker.result(userinfo)
o._authenticate(userinfo=userinfo)
self.mocker.result(None)
# Existing user comes in through Twitter OAuth
request.GET
self.mocker.result({'oauth_token': 'a'})
request.twitter_request_token
self.mocker.result(TOKEN)
Api(TOKEN).getAccessToken()
self.mocker.result(TOKEN)