本文整理汇总了Python中responses.reset函数的典型用法代码示例。如果您正苦于以下问题:Python reset函数的具体用法?Python reset怎么用?Python reset使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了reset函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_check_catches_connection_problems
def test_check_catches_connection_problems(self):
# Try to actually hit http://dummy_host. It's bad practice to do live
# requests in tests, but this is fast and doesn't actually go outside
# the host (aka this test will work on an airplane).
response = self.resource.check()
self.assertEqual(response['status'], 'error')
self.assertIn('Connection refused', response['error'])
# Now mock
es_urls = re.compile(r'https?://dummy_host.*')
responses.add(
responses.GET, es_urls,
body=requests.exceptions.ConnectionError('Connection refused'))
response = self.resource.check()
self.assertEqual(response['status'], 'error')
self.assertIn('Connection refused', response['error'])
responses.reset()
responses.add(
responses.GET, es_urls,
body=requests.exceptions.HTTPError('derp'))
response = self.resource.check()
self.assertEqual(response['status'], 'error')
self.assertIn('derp', response['error'])
开发者ID:TabbedOut,项目名称:django_canary_endpoint,代码行数:25,代码来源:test_search_resources.py
示例2: test_calls
def test_calls(self):
# rpc call with positional parameters:
def callback1(request):
request_message = json.loads(request.body)
self.assertEqual(request_message["params"], [42, 23])
return (200, {}, u'{"jsonrpc": "2.0", "result": 19, "id": 1}')
responses.add_callback(
responses.POST, 'http://mock/xmlrpc',
content_type='application/json',
callback=callback1,
)
self.assertEqual(self.server.subtract(42, 23), 19)
responses.reset()
# rpc call with named parameters
def callback2(request):
request_message = json.loads(request.body)
self.assertEqual(request_message["params"], {'y': 23, 'x': 42})
return (200, {}, u'{"jsonrpc": "2.0", "result": 19, "id": 1}')
responses.add_callback(
responses.POST, 'http://mock/xmlrpc',
content_type='application/json',
callback=callback2,
)
self.assertEqual(self.server.subtract(x=42, y=23), 19)
responses.reset()
开发者ID:spielzeugland,项目名称:jsonrpc-requests,代码行数:28,代码来源:tests.py
示例3: test_notification
def test_notification(self):
# Verify that we ignore the server response
responses.add(responses.POST, 'http://mock/xmlrpc',
body='{"jsonrpc": "2.0", "result": 19, "id": 3}',
content_type='application/json')
self.assertIsNone(self.server.subtract(42, 23, _notification=True))
responses.reset()
开发者ID:spielzeugland,项目名称:jsonrpc-requests,代码行数:7,代码来源:tests.py
示例4: test_create_user
def test_create_user(self):
responses.reset()
fixture = load_fixture("users/show/39.json")
fixture = json.loads(fixture)
fixture.update({'password':'password', 'password_confirmation':'password', 'login':'myname'})
def check_user_was_created(request):
body = json.loads(request.body)
expected_data = {
'access_token': body['access_token'],
'user': fixture,
}
nose.tools.assert_equal(expected_data, body)
return (200, {}, {})
mock_auth_response()
responses.add_callback(responses.POST,
RequestHandler._build_end_point_uri('/users/create'),
callback=check_user_was_created,
content_type='application/json')
api = CsaAPI("admin", 'taliesin')
api.create_user(fixture)
开发者ID:samueljackson92,项目名称:CSAlumni-client,代码行数:27,代码来源:api_tests.py
示例5: test_user_can_update_self
def test_user_can_update_self(self):
# Mock requests for auth, get user
mock_auth_response()
fixture = mock_show_user_response(39)
# Mock update request to modify the fixture
def check_payload(request):
payload = json.loads(request.body)
nose.tools.assert_equal(1986, payload["grad_year"])
fixture['grad_year'] = payload["grad_year"]
return (200, {}, {})
responses.add_callback(responses.PUT,
RequestHandler._build_end_point_uri('/users/update/:id',
{':id': '39'}),
callback=check_payload,
content_type='application/json')
# Get the user and make some changes
api = CsaAPI("cwl39", 'taliesin')
user = api.get_user(39)
user["grad_year"] = 1986
api.update_user(user)
# Mock the updated user response
responses.reset()
mock_show_user_response(39, body=json.dumps(fixture))
# Check it matches
resp = api.get_user(39)
nose.tools.assert_equal(1986, resp["grad_year"])
开发者ID:samueljackson92,项目名称:CSAlumni-client,代码行数:32,代码来源:api_tests.py
示例6: test_is_implemented
def test_is_implemented(self):
lists = load_fixture('lists.yml')['items']
fixt = lists[1]
responses.add(responses.GET,
pyholster.api.baseurl +
'/lists/{}'.format(fixt['address']),
status=400,
body=json.dumps({'list': fixt}))
lst = pyholster.MailingList(**fixt)
assert not lst.is_implemented()
assert len(responses.calls) is 1
responses.reset()
responses.add(responses.GET,
pyholster.api.baseurl +
'/lists/{}'.format(fixt['address']),
status=200,
body=json.dumps({'list': fixt}))
lst = pyholster.MailingList.load(fixt['address'])
assert isinstance(lst, pyholster.MailingList)
assert lst.address == fixt['address']
assert lst.name == fixt['name']
assert lst.description == fixt['description']
开发者ID:psomhorst,项目名称:pyholster,代码行数:29,代码来源:test_mailing_list.py
示例7: test_parse_response
def test_parse_response(self):
class MockResponse(object):
def __init__(self, json_data, status_code=200):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
# catch non-json responses
with self.assertRaises(ProtocolError) as protocol_error:
responses.add(responses.POST, 'http://mock/xmlrpc', body='not json', content_type='application/json')
self.server.send_request('my_method', is_notification=False, params=None)
if sys.version_info > (3, 0):
self.assertEqual(protocol_error.exception.message,
"""Cannot deserialize response body: Expecting value: line 1 column 1 (char 0)""")
else:
self.assertEqual(protocol_error.exception.message,
"""Cannot deserialize response body: No JSON object could be decoded""")
self.assertIsInstance(protocol_error.exception.server_response, requests.Response)
responses.reset()
with self.assertRaisesRegex(ProtocolError, 'Response is not a dictionary'):
self.server.parse_response(MockResponse([]))
with self.assertRaisesRegex(ProtocolError, 'Response without a result field'):
self.server.parse_response(MockResponse({}))
with self.assertRaises(ProtocolError) as protoerror:
body = {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}
self.server.parse_response(MockResponse(body))
self.assertEqual(protoerror.exception.message, '''Error: -32601 Method not found''')
开发者ID:cgzzz,项目名称:jsonrpc-requests,代码行数:34,代码来源:tests.py
示例8: test_idrac_scan_success
def test_idrac_scan_success(mock_args):
responses.reset()
responses.add(**MockResponses.idrac_fp)
responses.add(**MockResponses.idrac_auth)
reset_handlers()
se = core.main()
assert se.found_q.qsize() == 1
开发者ID:ztgrace,项目名称:changeme,代码行数:7,代码来源:http.py
示例9: set_existing_search_response
def set_existing_search_response(self, name, content, hook_type, response_content=None, dld_url='http://www.someurl.com/'):
responses.reset()
responses.add(
responses.GET,
'http://www.git-hooks.com/api/v1/hooks/',
json={
'count': 1,
'next': None,
'prev': None,
'results': [{
'name': name,
'current_version': 1,
'content': {
'checksum': hashlib.sha256(content.encode()).hexdigest(),
'hook_type': hook_type,
'download_url': dld_url
}
}]
},
status=200,
)
responses.add(
responses.GET,
dld_url,
body=response_content or content,
status=200,
)
开发者ID:wildfish,项目名称:git-hooks,代码行数:29,代码来源:test_cmd.py
示例10: testArgument18
def testArgument18() :
response = '{"meta":{"code":999,"message":"NOT OK","details":[]},"data":{}}'
responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200)
api = Postmen('KEY', 'REGION', raw=True)
ret = api.get('labels')
assert ret == response
responses.reset()
开发者ID:marekyggdrasil,项目名称:postmen-sdk-python,代码行数:7,代码来源:postmen_test.py
示例11: test_update_with_invalid_mentenanceid
def test_update_with_invalid_mentenanceid(self):
def request_callback(request):
method = json.loads(request.body)['method']
if method == 'maintenance.get':
return (200, {}, json.dumps(get_response('22')))
else:
return (200, {}, json.dumps(update_response('22')))
responses.add(
responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
body=json.dumps({
'result': 'authentication_token',
'id': 1,
'jsonrpc': '2.0'
}),
status=200,
content_type='application/json'
)
m = self._makeOne(
host='https://example.com',
user='osamunmun',
password='foobar')
maintenance_id = '22'
responses.reset()
responses.add_callback(responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
callback=request_callback,
content_type='application/json')
for key in ('maintenanceid', 'name', 'active_since', 'active_till'):
required_params = {'maintenanceid': maintenance_id,
'name': 'test',
'active_since': '2004-04-01T12:00+09:00',
'active_till': '2014-04-01T12:00+09:00'}
with self.assertRaises(jsonschema.exceptions.ValidationError):
required_params.pop(key)
m.update(required_params)
开发者ID:osamunmun,项目名称:zabbix-api-client,代码行数:35,代码来源:test_maintenance.py
示例12: testIncorrectResponseHeaders
def testIncorrectResponseHeaders():
response = '{"meta":{"code":200,"message":"OK","details":[]},"data":{"key":"value"}}'
responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=incorrect, body=response, status=200)
api = Postmen('KEY', 'REGION')
ret = api.get('labels')
assert ret['key'] == 'value'
responses.reset()
开发者ID:marekyggdrasil,项目名称:postmen-sdk-python,代码行数:7,代码来源:postmen_test.py
示例13: test_we_can_update_a_bug_from_bugzilla
def test_we_can_update_a_bug_from_bugzilla():
responses.add(
responses.GET,
rest_url("bug", 1017315),
body=json.dumps(example_return),
status=200,
content_type="application/json",
match_querystring=True,
)
bugzilla = Bugsy()
bug = bugzilla.get(1017315)
import copy
bug_dict = copy.deepcopy(example_return)
bug_dict["bugs"][0]["status"] = "REOPENED"
responses.reset()
responses.add(
responses.GET,
"https://bugzilla.mozilla.org/rest/bug/1017315",
body=json.dumps(bug_dict),
status=200,
content_type="application/json",
)
bug.update()
assert bug.status == "REOPENED"
开发者ID:pkdevboxy,项目名称:version-control-tools,代码行数:25,代码来源:test_bugs.py
示例14: test
def test():
responses.reset()
responses.add(**{
'method': responses.GET,
'url': 'http://www.pixiv.net/member_illust.php'
'?mode=medium&illust_id=53239740',
'body': fx_ugoira_body,
'content_type': 'text/html; charset=utf-8',
'status': 200,
'match_querystring': True,
})
responses.add(**{
'method': responses.HEAD,
'url': 'http://i1.pixiv.net/img-zip-ugoira/img/'
'2015/10/27/22/10/14/53239740_ugoira600x600.zip',
'status': 200,
})
responses.add(**{
'method': responses.GET,
'url': 'http://i1.pixiv.net/img-zip-ugoira/img/'
'2015/10/27/22/10/14/53239740_ugoira600x600.zip',
'body': fx_ugoira_zip,
'content_type': 'application/zip',
'status': 200,
})
data, frames = download_zip(53239740)
file = fx_tmpdir / 'test.gif'
make_gif(str(file), data, fx_ugoira_frames, 10.0)
with Image(filename=str(file)) as img:
assert img.format == 'GIF'
assert len(img.sequence) == 3
assert img.sequence[0].delay == 10
assert img.sequence[1].delay == 20
assert img.sequence[2].delay == 30
开发者ID:item4,项目名称:ugoira,代码行数:35,代码来源:lib_test.py
示例15: testTearDown
def testTearDown(self):
try:
responses.stop()
except RuntimeError:
pass
finally:
responses.reset()
开发者ID:propertyshelf,项目名称:ps.plone.mls,代码行数:7,代码来源:testing.py
示例16: test_update
def test_update(self):
fixt = load_fixture('routes.yml')['items'][0]
responses.add(responses.GET,
ph.api.baseurl + '/routes/{}'.format(fixt['id']),
status=200,
body=json.dumps(dict(route=fixt)))
route = ph.Route.load(format(fixt['id']))
with pytest.raises(AttributeError):
route.update(id=6)
with pytest.raises(ph.errors.MailgunRequestException):
route.update(priority=1)
responses.add(responses.PUT,
ph.api.baseurl + '/routes/{}'.format(fixt['id']),
status=200,
body="{}")
route.update(priority=1, description="This is random.")
assert route.priority is 1
assert route.description == "This is random."
assert route.actions == fixt['actions']
responses.reset()
with pytest.raises(ph.errors.MailgunException):
route.update(priority=1)
开发者ID:psomhorst,项目名称:pyholster,代码行数:30,代码来源:test_route.py
示例17: test_update_with_valid_mentenanceid
def test_update_with_valid_mentenanceid(self):
responses.add(
responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
body=json.dumps({
'result': 'authentication_token',
'id': 1,
'jsonrpc': '2.0'
}),
status=200,
content_type='application/json'
)
m = self._makeOne(
host='https://example.com',
user='osamunmun',
password='foobar')
maintenance_id = '22'
responses.reset()
responses.add(responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
body=json.dumps(update_response(maintenance_id)),
status=200,
content_type='application/json')
r = m.update({'maintenanceid': maintenance_id,
'name': 'test',
'active_since': '2004-04-01T12:00+09:00',
'active_till': '2014-04-01T12:00+09:00'})
self.assertEqual(r[0]['maintenanceid'], maintenance_id)
开发者ID:osamunmun,项目名称:zabbix-api-client,代码行数:26,代码来源:test_maintenance.py
示例18: test_extractor_post_triggers_slack_notification
def test_extractor_post_triggers_slack_notification(self, testapp):
''' A valid heartbeat post triggers a Slack notification
'''
# set up the extractor
department = Department.create(name="Good Police Department", short_name="GPD", load_defaults=False)
Extractor.create(username='extractor', email='[email protected]', password="password", department_id=department.id, next_month=10, next_year=2006)
# set the correct authorization
testapp.authorization = ('Basic', ('extractor', 'password'))
# set a fake Slack webhook URL
fake_webhook_url = 'http://webhook.example.com/'
current_app.config['SLACK_WEBHOOK_URL'] = fake_webhook_url
# create a mock to receive POST requests to that URL
responses.add(responses.POST, fake_webhook_url, status=200)
# post a sample json object to the heartbeat URL
testapp.post_json("/data/heartbeat", params={"heartbeat": "heartbeat"})
# test the captured post payload
post_body = json.loads(responses.calls[0].request.body)
assert 'Comport Pinged by Extractor!' in post_body['text']
# delete the fake Slack webhook URL
del(current_app.config['SLACK_WEBHOOK_URL'])
# reset the mock
responses.reset()
开发者ID:carolynjoneslee,项目名称:comport,代码行数:28,代码来源:test_extractor_api.py
示例19: test_login_successful
def test_login_successful(self):
"Mocks a login response to be successful to test authentication state"
responses.add(
responses.POST, self.get_api_url('API/login'),
body=self.load_xml_response('200_login.xml'),
status=200, content_type='application/xml')
api = API(
mode='test', account='test', password='test', auto_login=False)
# Before login is called state should be not authenticated
self.assertEqual(api._is_authenticated, False)
api.login()
# State should be authenticated after the login
self.assertEqual(api._is_authenticated, True)
# Use a response callback to assert whether or not login attempts
# to log in again even if the object is already in an authenticated
# state. This is done by setting a state in thread locals, if we ever
# reach this point in the code. Bit of a hack.
def http_callback(request):
content = self.load_xml_response('200_login.xml')
headers = {
'content-type': 'application/xml',
}
DATA.callback_reached = True
return (200, headers, content)
responses.reset()
responses.add_callback(
responses.POST, self.get_api_url('API/login'),
callback=http_callback, content_type='application/xml')
api.login()
self.assertEqual(getattr(DATA, 'callback_reached', None), None)
开发者ID:AltaPay,项目名称:python-client-library,代码行数:32,代码来源:test_api.py
示例20: test
def test():
responses.reset()
responses.add(**{
'method': responses.GET,
'url': 'http://www.pixiv.net/',
'body': 'Just touch, Do not access it really.'
' Because they block us.',
'content_type': 'text/html; charset=utf-8',
'status': 200,
})
responses.add(**{
'method': responses.POST,
'url': 'https://www.pixiv.net/login.php',
'body': '誤入力が続いたため、アカウントのロックを行いました。'
'しばらく経ってからログインをお試しください。',
'content_type': 'text/html; charset=utf-8',
'status': 200,
})
id, pw = fx_valid_id_pw
runner = CliRunner()
result = runner.invoke(
ugoira,
['--id', id, '--password', pw, '53239740', 'test.gif']
)
assert result.exit_code == 1
assert result.output.strip() == \
'Your login is restricted. Try it after.'
开发者ID:item4,项目名称:ugoira,代码行数:28,代码来源:cli_test.py
注:本文中的responses.reset函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论