本文整理汇总了Python中mock.Mock.json方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.json方法的具体用法?Python Mock.json怎么用?Python Mock.json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.Mock
的用法示例。
在下文中一共展示了Mock.json方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_content_item_deploy_fail
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_content_item_deploy_fail(self):
# failed deployment
response_deployment_state = Mock()
response_deployment_state.cookies = {}
response_deployment_state.json = Mock(return_value={"value": {
'name': 'def',
'id': 'id'}})
response_failed_deployment = Mock()
response_failed_deployment.cookies = {}
response_failed_deployment.json = Mock(return_value={"value": {
'name': 'def',
'succeeded': False,
'id': 'id'}})
_responses = [self.response_logout,
response_failed_deployment,
response_deployment_state,
self.response_login]
def _fake_response(*argc, **kwargs):
return _responses.pop()
requests = Mock()
requests.request = _fake_response
# check correct deployment
with patch("cloudify_vsphere.contentlibrary.requests", requests):
with self.assertRaises(NonRecoverableError):
cl = contentlibrary.ContentLibrary({'host': 'host',
'username': 'username',
'password': 'password',
'allow_insecure': True})
cl.content_item_deploy(
"abc", {'target': '_target'}, {'param': '_param'})
cl.__del__()
示例2: test_get_techloan_data
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_get_techloan_data(self):
"""
Tests that getting the data from the techloan instance
returns the expected data and raises errors appropriately
"""
test_json = self.load_json_file('cte_techloan_type_data.json')
status_codes = [200, 400]
# Mock a get call with different status codes returned
for status in status_codes:
mock = Mock()
mock.status_code = status
mock.json = Mock(return_value=test_json)
with patch.object(requests, 'get', return_value=mock):
techloan_data = cte_techloan.get_techloan_data()
if (status == 200):
self.assertEqual(techloan_data, test_json)
else:
self.assertIs(techloan_data, None)
# Mock a call with invalid techloan_data
test_json = 1
mock = Mock()
mock.status_code = 200
mock.json = Mock(return_value=test_json)
with patch.object(requests, 'get', return_value=mock):
techloan_data = cte_techloan.get_techloan_data()
self.assertIs(techloan_data, None)
示例3: test_init
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_init(self):
requests = Mock()
requests.request = Mock(return_value=self.response_login)
with patch("cloudify_vsphere.contentlibrary.requests", requests):
# correct session id
cl = contentlibrary.ContentLibrary({'host': 'host',
'username': 'username',
'password': 'password',
'allow_insecure': True})
cl.__del__()
# wrong session id
response = Mock()
response.json = Mock(return_value={"value": 'other_id'})
response.cookies = {'vmware-api-session-id': 'session_id'}
requests.request = Mock(return_value=response)
with self.assertRaises(NonRecoverableError):
contentlibrary.ContentLibrary({'host': 'host',
'username': 'username',
'password': 'password',
'allow_insecure': True})
# no response
response = Mock()
response.json = Mock(return_value={})
response.cookies = {}
requests.request = Mock(return_value=response)
with self.assertRaises(NonRecoverableError):
contentlibrary.ContentLibrary({'host': 'host',
'username': 'username',
'password': 'password',
'allow_insecure': True})
示例4: get_mock
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def get_mock():
ysc = youtube_status_code
yu = youtube_url
yc = youtube_cookies
yt = youtube_text
yh = youtube_headers
yosc = youtube_oembed_status_code
you = youtube_oembed_url
yoh = youtube_oembed_headers
yot = youtube_oembed_text
mock_obj_1 = Mock()
mock_obj_1.status_code = ysc
mock_obj_1.url = yu
mock_obj_1.headers = yh
mock_obj_1.cookies = yc
mock_obj_1.text = yt
mock_obj_1.json = lambda: json.loads(mock_obj_1.text)
mock_obj_2 = Mock()
mock_obj_2.status_code = 200
mock_obj_2.url = you
mock_obj_2.headers = yoh
mock_obj_2.text = yot
mock_obj_2.json = lambda: json.loads(mock_obj_2.text)
return [mock_obj_1, mock_obj_1, mock_obj_2]
示例5: test_content_library_get
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_content_library_get(self):
response_list = Mock()
response_list.cookies = {}
response_list.json = Mock(return_value={"value": ['abc']})
response_library = Mock()
response_library.cookies = {}
response_library.json = Mock(return_value={"value": {'name': 'abc',
'id': 'id'}})
_responses = [self.response_logout,
response_library,
response_list,
self.response_login]
def _fake_response(*argc, **kwargs):
return _responses.pop()
requests = Mock()
requests.request = _fake_response
# check content libraries list
with patch("cloudify_vsphere.contentlibrary.requests", requests):
cl = contentlibrary.ContentLibrary({'host': 'host',
'username': 'username',
'password': 'password',
'allow_insecure': True})
self.assertEqual(cl.content_library_get("abc"),
{'name': 'abc', 'id': 'id'})
cl.__del__()
示例6: mock_response
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def mock_response(self, content, status_code=200, bad_json=False):
mock = Mock(spec=requests.Response)
mock.content = content
mock.ok = (status_code >= 200 and status_code < 300)
mock.status_code = status_code
mock.iter_content = lambda size: mock.content
if bad_json:
mock.json = self._raise(ValueError)
else:
mock.json = lambda: json.loads(mock.content or '""')
mock.raise_for_status = lambda: None
return mock
示例7: test_get_digest_subscribers_multi_page
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_get_digest_subscribers_multi_page(self):
"""
"""
# multi page result
expected_multi_p1 = {
"count": 5,
"next": "not none",
"previous": None,
"results": [mkresult(1), mkresult(2), mkresult(3)]
}
expected_multi_p2 = {
"count": 5,
"next": None,
"previous": "not none",
"results": [mkresult(4), mkresult(5)]
}
expected_pages = [expected_multi_p1, expected_multi_p2]
def side_effect(*a, **kw):
return expected_pages.pop(0)
m = Mock()
with patch('requests.get', return_value=m) as p:
res = []
m.json = expected_multi_p1
g = get_digest_subscribers()
res.append(g.next())
p.assert_called_once_with(
self.expected_api_url,
params=self.expected_params,
headers=self.expected_headers)
res.append(g.next())
res.append(g.next()) # result 3, end of page
self.assertEqual([
mkexpected(mkresult(1)),
mkexpected(mkresult(2)),
mkexpected(mkresult(3))], res)
# still should only have called requests.get() once
self.assertEqual(1, p.call_count)
p.reset_mock() # reset call count
self.expected_params['page']=2
m.json = expected_multi_p2
self.assertEqual(mkexpected(mkresult(4)), g.next())
p.assert_called_once_with(
self.expected_api_url,
params=self.expected_params,
headers=self.expected_headers)
self.assertEqual(mkexpected(mkresult(5)), g.next())
self.assertEqual(1, p.call_count)
self.assertRaises(StopIteration, g.next)
示例8: _mock_response
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def _mock_response(self, requests_mock, json_result, status_code=200,
content=None):
response_mock = Mock()
response_mock.status_code = status_code
response_mock.json = Mock(return_value=json_result)
response_mock.content = content
requests_mock.return_value = response_mock
示例9: test_3login_flow
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_3login_flow(self):
ver_code_of_last_user, last_uid = DBSession.query(User.ver_code, User.id).all()[-1]
self.assert_(ver_code_of_last_user, 'Wrong order of tests')
req = DummyRequest(path='linkedin_confirm/%s' % ver_code_of_last_user,
matchdict={'code': ver_code_of_last_user}, user=self.founder)
auth_uids = []
confirm_acc.remember = lambda x, y: auth_uids.append(y)
ret = confirm_acc.linkedin_confirm_view(req)
self.assert_(last_uid in auth_uids, 'User should be logged in')
self.assert_(isinstance(ret, HTTPFound), 'Should redirect to linkedin')
# now test the linkedin return but mock out all the linkedin credential checks
req2 = Mock()
req2.params = {'code': 'test'}
req2.authenticated_userid = last_uid
login.get_oauth_flow_linkedin = Mock()
login.requests = Mock()
linkedin_user_resp = Mock()
linkedin_email = '[email protected]'
linkedin_user_resp.json = {'id': 'dummyLinkedinID', 'emailAddress': linkedin_email}
login.requests.get = lambda *x, **k: linkedin_user_resp
login.check_csrf_token = Mock()
# end of mocks
self.assert_(self.get_linkedin_email_db(last_uid) != linkedin_email, 'Linkedin email should not be set yet')
ret = login.oauthcallback_view(req2)
# oauth callback view calls complete_confirm_acc
self.assert_(isinstance(ret, HTTPFound), 'Should redirect to profile')
self.assert_(self.get_linkedin_email_db(last_uid) == linkedin_email,
'Linkedin email should be set by complete_confirm_acc')
示例10: test_authorize_sets_correct_session_if_user_can_sign_in
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_authorize_sets_correct_session_if_user_can_sign_in(
self,
oauth_authorization_url_patch,
oauth_get_patch,
oauth_fetch_token_patch):
token = "token_token"
user = {
'permissions': ['signin'],
'uid': "bleep_bloop_blarp"
}
oauth_get_response = Mock()
oauth_get_response.json = Mock(return_value={
'user': user
})
oauth_get_patch.return_value = oauth_get_response
oauth_fetch_token_patch.return_value = token
with self.client.session_transaction() as sess:
sess['oauth_state'] = "foo"
response = self.client.get(
'/auth/gds/callback')
self.assert_session_contains('oauth_user', user)
self.assert_session_contains('oauth_token', token)
self.assert_flashes('You have been successfully signed in')
assert_equal(response.headers['Location'], 'http://localhost/')
assert_equal(response.status_code, 302)
示例11: default_args
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def default_args():
args = Mock()
args.conf_file = '.lamvery.yml'
args.alias = 'foo'
args.version = '1'
args.json = '{"foo": "bar"}'
return args
示例12: SessionResourceTestCase
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
class SessionResourceTestCase(TestCase):
def setUp(self):
self.schema_url = "/schema"
self.response = Mock()
self.response.headers = {"content-type": "application/json; profile=%s" % self.schema_url}
self.session = Session()
patch.object(self.session, "request").start()
self.session.request.return_value = self.response
def tearDown(self):
patch.stopall()
@patch("pluct.session.Resource.from_response")
@patch("pluct.session.LazySchema")
def test_creates_resource_from_response(self, LazySchema, from_response):
LazySchema.return_value = "fake schema"
self.session.resource("/")
LazySchema.assert_called_with(href=self.schema_url, session=self.session)
from_response.assert_called_with(response=self.response, session=self.session, schema="fake schema")
@patch("pluct.session.Schema")
def test_creates_schema_from_response(self, Schema):
self.session.schema("/")
Schema.assert_called_with("/", raw_schema=self.response.json(), session=self.session)
示例13: test_load_post
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_load_post(self, RequestsGetMock):
# set up a mock response with stubbed json to simulate the API
def read_post_json():
with open(os.path.join(os.path.dirname(__file__), "data", "post.json")) as post_json_file:
return json.load(post_json_file)
mock_response = Mock(Response)
mock_response.ok = True
mock_response.text = "some text"
mock_response.json = read_post_json
RequestsGetMock.return_value = mock_response
# call we're testing
post = self.loader.load_post(1)
# some validations
self.assertIsInstance(post, Post)
self.assertEqual(post.wp_id, 1)
self.assertEqual(post.title, "This is a Test Post")
self.assertEqual(post.author.name, "testauthor")
self.assertEqual(post.categories.first().name, "News")
self.assertEqual(post.tags.first().name, "Testing")
self.assertEqual(post.attachments.first().url, "https://test.local/testpost.jpg")
示例14: test_put_validation_error
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_put_validation_error(self):
path = 'foo'
url = 'https://api.jirafe.com/v1/id/foo'
data_string = '{"bar":"baz"}'
auth_header = "some header"
session = Mock()
session.site_id = 'id'
session.get_header = Mock(return_value=auth_header)
options = {
"data": data_string,
"headers": auth_header
}
errors = {
'foo': 'foo error',
'bar': 'bar error',
}
json_response = {'success': False, 'error_type': 'validation', 'errors': errors}
put_response = {'errors': errors}
mock_response = Mock()
mock_response.json = Mock(return_value=put_response)
mock_response.status_code = 400
self.requests.put = Mock(return_value=mock_response)
actual_response = self.client._put(session, path, data_string)
self.requests.put.assert_called_with(url, **options)
self.assertEqual(json_response, actual_response)
示例15: test_descargar_actualizacion
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import json [as 别名]
def test_descargar_actualizacion(self, mock_get):
'''
Prueba la descarga de la ultima version desde el servidor. Debe
retornar una lista de clases de trafico en forma de diccionarios.
'''
# preparo datos
clases = [
{
'id': 1,
'nombre': 'foo',
'descripcion': 'bar',
},
{
'id': 2,
'nombre': 'fulano',
'descripcion': 'mengano',
},
]
mock_response = Mock()
mock_response.status_code = 200
mock_response.json = Mock(return_value={'clases': clases})
mock_get.return_value = mock_response
# llamo metodo a probar
descarga = self.actualizador.descargar_actualizacion()
# verifico que todo este bien
for clase in clases:
assert clase in descarga