Python源码示例:responses.reset()
示例1
def test_interest_form_post_triggers_slack_notification(self, testapp):
''' A valid interest form post triggers a Slack notification.
'''
# 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 an interest form submission
testapp.post("/interest/", params=dict(name="Jean Weaver", agency="Clinton Police Department", location="Clinton, OK", phone="580-970-3338", email="jean.weaver@example.com", comments="I'm interested in Comport as an open-source tool!"))
# test the captured post payload
post_body = json.loads(responses.calls[0].request.body)
assert 'New Interest Form Submission!' in post_body['text']
# delete the fake Slack webhook URL
del(current_app.config['SLACK_WEBHOOK_URL'])
# reset the mock
responses.reset()
示例2
def testRetryDelay():
global call
call = 0
def request_callback(request):
global call
if call == 0 :
call = 1
return (200, headers, '{"meta":{"code":999,"message":"PROBLEM","retryable":true, "details":[]},"data":{}}')
elif call == 1 :
call = 2
"second attempt"
return (200, headers, '{"meta":{"code":999,"message":"PROBLEM","retryable":true,"details":[]},"data":{}}')
elif call == 2 :
call = 3
return (200, headers, '{"meta":{"code":200,"message":"OK","details":[]},"data":{}}')
responses.add_callback(responses.GET, 'https://REGION-api.postmen.com/v3/labels', callback=request_callback)
api = Postmen('KEY', 'REGION')
api.get('labels')
responses.reset()
# TEST 9
示例3
def testRetryMaxAttempt(monkeypatch):
monkeypatch.setattr(time, 'sleep', lambda s: None)
global call
call = 0
def request_callback(request):
global call
if call < 4 :
call += 1
return (200, headers, '{"meta":{"code":999,"message":"PROBLEM","retryable":true, "details":[]},"data":{}}')
else :
return (200, headers, '{"meta":{"code":200,"message":"OK","details":[]},"data":{}}')
responses.add_callback(responses.GET, 'https://REGION-api.postmen.com/v3/labels', callback=request_callback)
api = Postmen('KEY', 'REGION')
before = time.time()
api.get('labels')
after = time.time()
responses.reset()
monkeypatch.setattr(time, 'sleep', lambda s: None)
# TEST 10
示例4
def testRetryMaxAttemptExceeded(monkeypatch):
monkeypatch.setattr(time, 'sleep', lambda s: None)
global call
call = 0
def request_callback(request):
global call
if call < 5 :
call += 1
return (200, headers, '{"meta":{"code":999,"message":"PROBLEM","retryable":true, "details":[]},"data":{}}')
else :
pytest.fail("Maximum 5 attempts of retry, test #10 failed")
responses.add_callback(responses.GET, 'https://REGION-api.postmen.com/v3/labels', callback=request_callback)
api = Postmen('KEY', 'REGION')
with pytest.raises(PostmenException) as e:
api.get('labels')
responses.reset()
monkeypatch.setattr(time, 'sleep', lambda s: None)
assert "PROBLEM" in str(e.value.message())
assert 999 == e.value.code()
# TEST 11
示例5
def testArguments11(monkeypatch):
monkeypatch.setattr(time, 'sleep', lambda s: None)
global call
call = 0
def request_callback(request):
global call
if call < 1 :
call += 1
return (200, headers, '{"meta":{"code":999,"message":"PROBLEM","retryable":true, "details":[]},"data":{}}')
else :
pytest.fail("Shall not retry if retry = False, test #11 failed")
responses.add_callback(responses.GET, 'https://REGION-api.postmen.com/v3/labels', callback=request_callback)
api = Postmen('KEY', 'REGION', retry=False)
with pytest.raises(PostmenException) as e:
api.get('labels')
responses.reset()
monkeypatch.setattr(time, 'sleep', lambda s: None)
assert "PROBLEM" in str(e.value.message())
assert 999 == e.value.code()
assert e.value.retryable()
# TEST 12
示例6
def testRateLimit(monkeypatch):
monkeypatch.setattr(time, 'sleep', lambda s: None)
global call
call = 0
def request_callback(request):
global call
if call == 0 :
call = 1
return (200, exceeded, '{"meta":{"code":429,"message":"EXCEEDED","retryable":true, "details":[]},"data":{}}')
elif call == 1 :
return (200, headers, '{"meta":{"code":200,"message":"OK","details":[]},"data":{}}')
responses.add_callback(responses.GET, 'https://REGION-api.postmen.com/v3/labels', callback=request_callback)
api = Postmen('KEY', 'REGION')
api.get('labels')
responses.reset()
monkeypatch.setattr(time, 'sleep', lambda s: None)
# TEST 14
示例7
def test_create_node(self):
"""
Verify that node creation makes the correct request and returns the ID
contained in the response, and raises an exception for non-201 status codes.
"""
self.mock_api_client()
response_data = {'id': self.node_id}
self.mock_node_create(response_data, 201)
node_data = {'foo': 'bar'}
node_id = self.publisher.create_node(node_data)
assert responses.calls[-1].request.url == self.publisher.node_api_base
assert json.loads(responses.calls[-1].request.body) == node_data
assert node_id == self.node_id
responses.reset()
self.mock_api_client()
self.mock_node_create(response_data, 500)
with pytest.raises(NodeCreateError):
self.publisher.create_node(node_data)
示例8
def test_edit_node(self):
"""
Verify that node editing makes the correct request and raises an exception
for non-200 status codes.
"""
self.mock_api_client()
self.mock_node_edit(200)
node_data = {'foo': 'bar'}
self.publisher.edit_node(self.node_id, node_data)
assert responses.calls[-1].request.url == '{base}/{node_id}'.format(
base=self.publisher.node_api_base,
node_id=self.node_id
)
assert json.loads(responses.calls[-1].request.body) == node_data
responses.reset()
self.mock_api_client()
self.mock_node_edit(500)
with pytest.raises(NodeEditError):
self.publisher.edit_node(self.node_id, node_data)
示例9
def test_delete_node(self):
"""
Verify that node deletion makes the correct request and raises an exception
for non-204 status codes.
"""
self.mock_api_client()
self.mock_node_delete(200)
self.publisher.delete_node(self.node_id)
assert responses.calls[-1].request.url == '{base}/{node_id}'.format(
base=self.publisher.node_api_base,
node_id=self.node_id
)
responses.reset()
self.mock_api_client()
self.mock_node_delete(500)
with pytest.raises(NodeDeleteError):
self.publisher.delete_node(self.node_id)
示例10
def test_access_token(self):
""" Verify the property retrieves, and caches, an access token from the OAuth 2.0 provider. """
token = 'abc123'
partner = PartnerFactory()
url = '{root}/access_token'.format(root=partner.oauth2_provider_url)
body = {
'access_token': token,
'expires_in': 3600,
}
responses.add(responses.POST, url, json=body, status=200)
assert partner.access_token == token
assert len(responses.calls) == 1
# No HTTP calls should be made if the access token is cached.
responses.reset()
assert partner.access_token == token
示例11
def test_get_user_api_data(self):
""" Verify the method retrieves data from the User API and caches it. """
username = Faker().user_name()
data = {
'username': username,
}
url = '{root}accounts/{username}'.format(root=self.site_configuration.user_api_url, username=username)
responses.add(responses.GET, url, body=json.dumps(data), content_type=JSON, status=200)
self.mock_access_token_response()
actual = self.site_configuration.get_user_api_data(username)
self.assertEqual(actual, data)
self.assertEqual(len(responses.calls), 2)
# Verify the data is cached
responses.reset()
actual = self.site_configuration.get_user_api_data(username)
self.assertEqual(actual, data)
self.assertEqual(len(responses.calls), 0)
示例12
def test_handle_processor_response(self):
"""Verify that the processor creates the appropriate PaymentEvent and Source objects."""
for payer_info in (PaypalMixin.PAYER_INFO, {"shipping_address": None}):
responses.reset()
log.info("Testing payer_info with email set to: %s", payer_info.get("email"))
self.mock_oauth2_response()
self.mock_payment_creation_response(self.basket, find=True)
self.mock_payment_execution_response(self.basket, payer_info=payer_info)
handled_response = self.processor.handle_processor_response(self.RETURN_DATA, basket=self.basket)
self.assertEqual(handled_response.currency, self.basket.currency)
self.assertEqual(handled_response.total, self.basket.total_incl_tax)
self.assertEqual(handled_response.transaction_id, self.PAYMENT_ID)
self.assertEqual(
handled_response.card_number,
'PayPal ({})'.format(payer_info['email']) if 'email' in payer_info else 'PayPal Account')
self.assertIsNone(handled_response.card_type)
示例13
def mock_urls(request):
data = _DATA.tostring()
checksum = _CHECKSUM
url_data = _URL
url_checksum = _URL + '.md5'
if not request.param[0]:
# Data URL is corrupted.
url_data = url_data[:-1]
if not request.param[1]:
# Data is corrupted.
data = data[:-1]
if not request.param[2]:
# Checksum URL is corrupted.
url_checksum = url_checksum[:-1]
if not request.param[3]:
# Checksum is corrupted.
checksum = checksum[:-1]
_add_mock_response(url_data, data)
_add_mock_response(url_checksum, checksum)
yield request.param, url_data, url_checksum
responses.reset()
示例14
def test_learnings_alternate_command_echoed(self):
''' The learnings alternate command is echoed in the bot's reponse
'''
alternate_action = "recent"
# 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)
rsp = self.post_command(text=alternate_action)
self.assertTrue(rsp.status_code in range(200, 299), rsp.status_code)
# test the captured post payload
payload = json.loads(responses.calls[0].request.body)
self.assertIsNotNone(payload['text'])
self.assertTrue("gloss {action}".format(action=alternate_action) in payload['text'])
# delete the fake Slack webhook URL
del(current_app.config['SLACK_WEBHOOK_URL'])
# reset the mock
responses.reset()
示例15
def test_custom_slash_command_for_public_learnings(self):
''' A slash command other than /gloss is echoed in the bot's response
to a public learnings request.
'''
test_command = "/gg"
# 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)
rsp = self.post_command(text="learnings", slash_command=test_command)
self.assertTrue(rsp.status_code in range(200, 299), rsp.status_code)
# test the captured post payload
payload = json.loads(responses.calls[0].request.body)
self.assertIsNotNone(payload['text'])
self.assertTrue("{command} learnings".format(command=test_command) in payload['text'])
# delete the fake Slack webhook URL
del(current_app.config['SLACK_WEBHOOK_URL'])
# reset the mock
responses.reset()
示例16
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="IM Police Department", short_name="IMPD", load_defaults=False)
extractor, _ = Extractor.from_department_and_password(department=department, password="password")
# set the correct authorization
testapp.authorization = ('Basic', (extractor.username, '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()
示例17
def test_sample_metadata_export(self):
url = reverse(sample_metadata_export, args=[COMPOUND_HET_PROJECT_GUID])
self.check_staff_login(url)
# Test invalid airtable responses
responses.add(responses.GET, '{}/Samples'.format(AIRTABLE_URL), status=402)
response = self.client.get(url)
self.assertEqual(response.status_code, 402)
responses.reset()
responses.add(responses.GET, '{}/Samples'.format(AIRTABLE_URL), status=200)
response = self.client.get(url)
self.assertEqual(response.status_code, 500)
self.assertEqual(response.json()['message'], 'Unable to retrieve airtable data: No JSON object could be decoded')
responses.reset()
responses.add(responses.GET, '{}/Samples'.format(AIRTABLE_URL),
json=PAGINATED_AIRTABLE_SAMPLE_RECORDS, status=200)
responses.add(responses.GET, '{}/Samples'.format(AIRTABLE_URL),
json=AIRTABLE_SAMPLE_RECORDS, status=200)
responses.add(responses.GET, '{}/Collaborator'.format(AIRTABLE_URL),
json=AIRTABLE_COLLABORATOR_RECORDS, status=200)
response = self.client.get(url)
self.assertEqual(response.status_code, 500)
self.assertEqual(
response.json()['message'],
'Found multiple airtable records for sample NA19675 with mismatched values in field dbgap_study_id')
self.assertEqual(len(responses.calls), 2)
self.assertIsNone(responses.calls[0].request.params.get('offset'))
self.assertEqual(responses.calls[1].request.params.get('offset'), 'abc123')
# Test success
responses.add(responses.GET, '{}/Collaborator'.format(AIRTABLE_URL),
json=AIRTABLE_COLLABORATOR_RECORDS, status=200)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
response_json = response.json()
self.assertListEqual(response_json.keys(), ['rows'])
self.assertIn(EXPECTED_SAMPLE_METADATA_ROW, response_json['rows'])
示例18
def pytest_runtest_teardown(item):
if not get_withoutresponses_marker(item):
try:
responses_.stop()
responses_.reset()
except RuntimeError:
# patcher was already uninstalled and responses doesnt let us
# force maintain it
pass
示例19
def testNotRaiseException() :
response = '{"meta":{"code":200,"message":"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')
api.get('labels')
responses.reset()
# TEST 2
示例20
def testNonSerializableJSON():
response = 'THIS IS NOT A VALID JSON OBJECT'
responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200, content_type='text/plain')
api = Postmen('KEY', 'REGION')
with pytest.raises(PostmenException) as e:
api.get('labels')
responses.reset()
assert "Something went wrong on Postmen's end" in str(e.value)
assert 500 == e.value.code()
assert not e.value.retryable()
# TEST 3
示例21
def testException3():
response = '{"meta":{"code":999,"message":"PROBLEM","retryable":true,"details":[]},"data":{}}'
responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200)
api = Postmen('KEY', 'REGION')
with pytest.raises(PostmenException) as e:
api.get('labels')
responses.reset()
assert "PROBLEM (999)" in str(e.value)
assert 999 == e.value.code()
assert e.value.retryable()
# TEST 4
示例22
def testException4():
response = '{"meta":{"code":999,"message":"PROBLEM","retryable":false,"details":[]},"data":{}}'
responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200)
api = Postmen('KEY', 'REGION')
with pytest.raises(PostmenException) as e:
api.get('labels')
responses.reset()
assert "PROBLEM" in str(e.value.message())
assert 999 == e.value.code()
assert not e.value.retryable()
# TEST 5
示例23
def testException5():
response = '{"meta":{"code":999,"message":"PROBLEM","retryable":false,"details":[{"key":"value"}]},"data":{}}'
responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200)
api = Postmen('KEY', 'REGION')
with pytest.raises(PostmenException) as e:
api.get('labels')
responses.reset()
assert "PROBLEM" in str(e.value.message())
assert 999 == e.value.code()
assert not e.value.retryable()
details = e.value.details()
assert details[0]['key'] == 'value'
# TEST 6
示例24
def testArguments7():
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, content_type='text/plain')
api = Postmen('KEY', 'REGION')
api.get('labels', safe=True)
responses.reset()
e = api.getError()
assert "NOT OK" in str(e.message())
# TEST 8
示例25
def testArgument14():
response = '{"meta":{"code":429,"message":"EXCEEDED","retryable":true, "details":[]},"data":{}}'
responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=exceeded, body=response, status=200)
api = Postmen('KEY', 'REGION', rate=False)
with pytest.raises(PostmenException) as e:
api.get('labels')
responses.reset()
assert "EXCEEDED" in str(e.value.message())
assert 429 == e.value.code()
assert e.value.retryable()
# TEST 15
示例26
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()
# TEST 16
示例27
def testArgument17() :
response = '{"meta":{"code":200,"message":"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()
# TEST 18
示例28
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()
示例29
def response_fixture_factory(url, data=None, status=200):
@pytest.yield_fixture
def fixture():
responses.add(
responses.POST,
url,
status=status,
body=json.dumps(data or {}),
content_type='application/json',
)
responses.start()
yield responses
responses.stop()
responses.reset()
return fixture
示例30
def tearDown(self):
os.unlink(self.token_path)
responses.reset()